feat(ecs): opt-in localhost between an awsvpc task's containers (#8654)

On Fargate the containers of an awsvpc task share one network namespace
and reach each other on localhost. Floci gave each container a namespace
of its own unless security-group enforcement was on, and enforcement
needs rootful Docker, so a sidecar task definition (nginx in front of
php-fpm on 127.0.0.1:9000) could not run unchanged on rootless Docker or
Podman.

floci.services.ecs.shared-task-network (FLOCI_SERVICES_ECS_SHARED_TASK_NETWORK),
off by default, gives such a task one namespace while enforcement is off.
A helper container holds it, as the ECS agent's pause container does. The
firewall manager starts it from the same code as a protected helper, with
no nftables table and no rootful requirement, and every container in the
task joins it. The helper holds what the task has once rather than per
container: its published ports, the link-local address its containers
reach the task-role credential endpoint from, and its ENI address on the
VPC's Docker network. FireLens's FLUENT_HOST is 127.0.0.1, the value the
ECS agent sets for awsvpc. The helper is removed once the task's
containers are, before its link-local address is handed on, and a helper
a previous run left behind is swept at startup with the task's other
containers. A helper Docker keeps is marked pending on the task's handle,
which the service keeps to retry the removal; its address stays reserved
until then, and it is taken off the VPC network so the ENI address is free
when the ENI is released. Launch cleanup removes a helper by name even when
its start failed part way, and now also covers the VPC attachment, so a
failed attachment no longer leaves the task's containers running. With
enforcement on, nothing changes.

The helper image now builds from docker.io/library/alpine: Podman refuses
a short name it cannot prompt about, and the task-role credentials proxy
builds from the same Dockerfile.

Closes #4331
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-16 19:23:57 -04:00
1 parent 3007534104
commit 895981ac8d
14 files changed
+939 -52

No files matched your search

@@ -563,6 +563,7 @@ These services spawn Docker containers. They require access to the Docker socket
| `FLOCI_SERVICES_ECS_ENABLED` | `true` | Enable the ECS service |
| `FLOCI_SERVICES_ECS_MOCK` | `false` | When `true`, tasks are registered but not actually run |
| `FLOCI_SERVICES_ECS_PUBLISH_AWSVPC_PORTS_TO_HOST` | `false` | Publish `awsvpc` task ports on stable Docker host ports for host-side clients |
| `FLOCI_SERVICES_ECS_SHARED_TASK_NETWORK` | `false` | Put an `awsvpc` task's containers in one network namespace, held by a helper container, so they reach each other on `localhost` as on Fargate. Applies while security-group enforcement is off and needs no privileges, so it works on rootless Docker and Podman |
| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default task memory when not specified in the task definition |
| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default task CPU units when not specified in the task definition |
| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | _(none)_ | Docker network for ECS task containers |
+36 -7
View File
@@ -197,9 +197,11 @@ An injected `http://` endpoint also gets `tls Off`. Fluent Bit 1.9 (the `aws-for
and `:latest` line) still calls `flb_tls_session_create` on HTTP S3 and SIGSEGVs on a NULL
TLS context; the scheme alone is not enough. A `tls` the task definition already set is left
alone.
The TCP forward listens on `0.0.0.0` rather than AWS's awsvpc `127.0.0.1` because Floci only
shares a network namespace when security-group enforcement is enabled for an awsvpc task. In every
other case, the injected `FLUENT_HOST` (the router's container IP) must be reachable. Fluent Bit
The TCP forward listens on `0.0.0.0` rather than AWS's awsvpc `127.0.0.1` because Floci shares a
network namespace only when security-group enforcement or
[a shared task network](#same-task-localhost-for-awsvpc-tasks) gives an awsvpc task one. Such a task
gets `FLUENT_HOST=127.0.0.1`, the value the ECS agent sets for awsvpc. In every other case, the
injected `FLUENT_HOST` (the router's container IP) must be reachable. Fluent Bit
config is written to `/fluent-bit/etc/fluent-bit.conf`. Fluentd config is
written to `/fluentd/etc/fluent.conf` and uses `@type` (not `Name`) for output plugins; Floci
does not inject an `endpoint` into Fluentd outputs.
@@ -381,8 +383,10 @@ With Docker-backed VPC networks (`FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED=true`
address, so an EC2 instance, a `VpcConfig` Lambda function or any other container on that network
reaches the task at the `privateIPv4Address` that `DescribeTasks` reports. AWS gives the whole task
that one address; Floci gives it to one container, the first in the task definition that maps a
port, else the first, and the task's other containers do not answer at it. A task in a
security-group protected namespace keeps that namespace and does not join the VPC network.
port, else the first, and the task's other containers do not answer at it. A task with
[a shared task network](#same-task-localhost-for-awsvpc-tasks) gives it to the helper holding its
namespace instead, so every container answers at it. A task in a security-group protected namespace
keeps that namespace and does not join the VPC network.
#### Capacity providers
@@ -634,7 +638,7 @@ carries `AWS_INSTANCE_IPV4` and `AWS_INSTANCE_PORT`, chosen by network mode:
| Network mode | `AWS_INSTANCE_IPV4` | `AWS_INSTANCE_PORT` |
|---|---|---|
| `awsvpc` | the address the task's container holds on the Docker network it was created on | the entry's `containerPort` |
| `awsvpc` | the address the task's container holds on the Docker network it was created on, or the namespace helper's for a task whose containers share one | the entry's `containerPort` |
| `bridge` or `host` | the address Floci reaches the container at: `127.0.0.1` when Floci runs natively, the container's Docker network address when Floci runs in Docker | the host port the entry's `containerPort` was published on, or the `containerPort` when it has no binding |
An explicit `port` on the registry entry is registered as-is in every mode, as on AWS. The
@@ -934,13 +938,14 @@ resource type in the Service Authorization Reference (`ListClusters`, `ListServi
## Configuration
Every `awsvpc` task receives an ENI in its subnet. With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, a Docker-backed task's containers additionally share one protected network namespace built around that ENI, and packets are filtered against its security groups. A task without explicit security groups uses its subnet VPC's default group. Containers in the same task can communicate over localhost. Bridge and host task networking do not attach task-level `awsvpc` security groups. Mock mode reports control-plane state, including the ENI, and does not enforce packet filtering.
Every `awsvpc` task receives an ENI in its subnet. With `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_ENABLED=true`, a Docker-backed task's containers additionally share one protected network namespace built around that ENI, and packets are filtered against its security groups. Without enforcement, `FLOCI_SERVICES_ECS_SHARED_TASK_NETWORK=true` gives them one namespace with no filtering; see [Same-task localhost for awsvpc tasks](#same-task-localhost-for-awsvpc-tasks). A task without explicit security groups uses its subnet VPC's default group. Containers in the same task can communicate over localhost. Bridge and host task networking do not attach task-level `awsvpc` security groups. Mock mode reports control-plane state, including the ENI, and does not enforce packet filtering.
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_ECS_ENABLED` | `true` | Enable or disable the ECS service |
| `FLOCI_SERVICES_ECS_MOCK` | `false` | Skip Docker; tasks reach `RUNNING` with nothing running behind them (useful for CI) |
| `FLOCI_SERVICES_ECS_DOCKER_NETWORK` | *(unset)* | Docker network for task containers |
| `FLOCI_SERVICES_ECS_SHARED_TASK_NETWORK` | `false` | Put an `awsvpc` task's containers in one network namespace, so they reach each other on `localhost`, without security-group enforcement (see [Same-task localhost for awsvpc tasks](#same-task-localhost-for-awsvpc-tasks)) |
| `FLOCI_SERVICES_ECS_DEFAULT_MEMORY_MB` | `512` | Default memory (MB) when the task definition omits it |
| `FLOCI_SERVICES_ECS_DEFAULT_CPU_UNITS` | `256` | Default CPU units when the task definition omits it |
| `FLOCI_SERVICES_ECS_HOST_VOLUME_ROOTS` | *(unset)* | Approved parent directories for host volume bind mounts (`volumes[].host.sourcePath`) and container devices (`linuxParameters.devices[].hostPath`) |
@@ -1147,6 +1152,30 @@ services:
FLOCI_SERVICES_ECS_DOCKER_NETWORK: aws-local_default
```
### Same-task localhost for awsvpc tasks
On Fargate, the containers of an `awsvpc` task share one network namespace and reach each other on
`localhost`: an nginx in front of php-fpm on `127.0.0.1:9000`, or an Envoy or log-router sidecar.
Floci gives each task container a namespace of its own by default, so `127.0.0.1:<port of a sibling>`
is refused. Security-group enforcement shares one, but it needs rootful Docker on Linux.
Set `FLOCI_SERVICES_ECS_SHARED_TASK_NETWORK=true` (`floci.services.ecs.shared-task-network`,
default `false`) to share one namespace without enforcement. Each Docker-backed `awsvpc` task then
gets a helper container that holds its namespace, as the ECS agent's pause container does, and every
container in the task joins it. Nothing is filtered, and the helper needs no privileges, so this works
on rootless Docker and Podman. With enforcement on, the setting changes nothing: the task gets its
protected namespace.
The helper holds what the task has once rather than per container: its published ports (with the
host-port settings below), the link-local address its containers reach the
[task-role credential endpoint](#task-iam-role-credentials) from, and its ENI address on the VPC's
Docker network. It is removed when the task stops, and a helper a previous run left behind is
removed at startup with the task's other containers. It uses the security-group helper image,
`FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_HELPER_IMAGE`, which Floci builds locally by default.
As on AWS, two containers in one task can no longer listen on the same port, and a container
reaches its siblings only on `localhost`, not at an address of its own.
### Host access to awsvpc task ports
Native runs publish `awsvpc` task ports on dynamically allocated Docker host ports.
@@ -2705,6 +2705,15 @@ public interface EmulatorConfig {
@WithDefault("127.0.0.1")
String hostPortBindAddress();
/**
* Opt-in: the containers of an {@code awsvpc} task share one network namespace, held by a helper
* container as the ECS agent's pause container holds it, so they reach each other on {@code localhost}
* as on Fargate. Applies while security-group enforcement is off, which already gives a task one
* namespace. Off by default: each container keeps a namespace and address of its own.
*/
@WithDefault("false")
boolean sharedTaskNetwork();
Optional<String> dockerNetwork();
@WithDefault("512")
@@ -34,13 +34,20 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
/** Owns the protected namespace and the Floci-only nftables table for each managed ENI. */
/**
* Owns the network-namespace helpers that EC2 instances and ECS tasks run in: the protected namespace and the
* Floci-only nftables table for each managed ENI, and the shared namespace of an ECS task that only needs its
* containers on one {@code localhost}.
*/
@ApplicationScoped
public class SecurityGroupFirewallManager {
private static final Logger LOG = Logger.getLogger(SecurityGroupFirewallManager.class);
private static final String PROTECTED_HELPER_PREFIX = "sg";
private static final String SHARED_HELPER_PREFIX = "netns";
private final DockerClient dockerClient;
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -121,21 +128,63 @@ public class SecurityGroupFirewallManager {
.anyMatch(option -> option.toLowerCase(Locale.ROOT).contains("rootless"))) {
throw new IllegalStateException("Security-group enforcement requires rootful Docker");
}
ensureHelperImage();
String name = ContainerStorageHelper.resourceName(config, "sg", null,
ContainerBuilder.Builder builder = helperBuilder(PROTECTED_HELPER_PREFIX, service, resourceId, accountId,
region, dockerNetwork, portBindings, hostIp)
.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true",
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.withLabels(extraLabels);
return startHelper(builder, resourceId, "protected",
helperId -> apply(helperId, SecurityGroupNftCompiler.initialRuleset()));
}
/**
* Starts a namespace helper that filters nothing, for containers that only need to share one network
* namespace, as the containers of an {@code awsvpc} task do on Fargate. It needs neither security-group
* enforcement nor rootful Docker: the helper holds the namespace, its published ports and
* {@code linkLocalIps}, and no nftables table.
*/
public Namespace createSharedNamespace(String service, String resourceId, String accountId, String region,
Optional<String> dockerNetwork, Map<Integer, Integer> portBindings,
Map<String, String> extraLabels, String hostIp, List<String> linkLocalIps) {
ContainerBuilder.Builder builder = helperBuilder(SHARED_HELPER_PREFIX, service, resourceId, accountId,
region, dockerNetwork, portBindings, hostIp)
.withLabels(Map.of(ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.withLabels(extraLabels);
linkLocalIps.forEach(builder::withLinkLocalIp);
return startHelper(builder, resourceId, "shared", helperId -> { });
}
/**
* Removes the helper {@link #createSharedNamespace} started for {@code resourceId}, if there is one, and
* throws when Docker keeps it, since it may still hold host ports and a link-local address.
*/
public void removeSharedNamespaceStrict(String resourceId) {
lifecycleManager.removeIfExistsStrict(sharedNamespaceName(resourceId));
}
/** The container name of the helper {@link #createSharedNamespace} starts for {@code resourceId}. */
public String sharedNamespaceName(String resourceId) {
return helperName(SHARED_HELPER_PREFIX, resourceId);
}
private String helperName(String prefix, String resourceId) {
return ContainerStorageHelper.resourceName(config, prefix, null,
resourceId.replaceAll("[^a-zA-Z0-9_.-]", "-"));
}
private ContainerBuilder.Builder helperBuilder(String prefix, String service, String resourceId, String accountId,
String region, Optional<String> dockerNetwork,
Map<Integer, Integer> portBindings, String hostIp) {
ensureHelperImage();
ContainerBuilder.Builder builder = containerBuilder.newContainer(config.network().securityGroupEnforcement().helperImage())
.withName(name)
.withName(helperName(prefix, resourceId))
.withDockerNetwork(dockerNetwork)
// Workloads join this network namespace and use its resolver and hosts file.
.withEmbeddedDns()
.withHostDockerInternalOnLinux()
.withEntrypoint(List.of("sh", "-c"))
.withCmd(List.of("exec sleep 2147483647"))
.withLabels(ContainerStorageHelper.resourceIdentityLabels(service, resourceId, accountId, region))
.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true",
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.withLabels(extraLabels);
.withLabels(ContainerStorageHelper.resourceIdentityLabels(service, resourceId, accountId, region));
if (portBindings != null) {
portBindings.forEach((containerPort, hostPort) -> {
if (hostIp == null) {
@@ -145,6 +194,12 @@ public class SecurityGroupFirewallManager {
}
});
}
return builder;
}
/** Starts the helper, then {@code prepare}s it; a helper that fails either step is removed. */
private Namespace startHelper(ContainerBuilder.Builder builder, String resourceId, String kind,
Consumer<String> prepare) {
ContainerSpec spec = builder.build();
String helperId = null;
try {
@@ -152,15 +207,15 @@ public class SecurityGroupFirewallManager {
Map<String, ContainerNetwork> networks = dockerClient.inspectContainerCmd(helperId).exec()
.getNetworkSettings().getNetworks();
String ip = firstAddress(networks, ContainerNetwork::getIpAddress)
.orElseThrow(() -> new IllegalStateException("Firewall helper has no Docker IP"));
apply(helperId, SecurityGroupNftCompiler.initialRuleset());
.orElseThrow(() -> new IllegalStateException("Namespace helper has no Docker IP"));
prepare.accept(helperId);
return new Namespace(helperId, ip, firstAddress(networks, ContainerNetwork::getGlobalIPv6Address)
.orElse(null));
} catch (Exception e) {
if (helperId != null) {
lifecycleManager.removeIfExists(helperId);
}
throw new IllegalStateException("Cannot prepare protected network namespace for " + resourceId, e);
throw new IllegalStateException("Cannot prepare " + kind + " network namespace for " + resourceId, e);
}
}
@@ -5711,7 +5711,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
private void retainPendingCleanupHandle(String taskArn, EcsTaskHandle handle) {
if (handle != null && (handle.hasOpenLogStreams() || handle.hasTaskVolumes()
|| !handle.allContainersRemoved())) {
|| !handle.allContainersRemoved() || handle.isNamespaceHelperPending())) {
taskHandles.put(taskArn, handle);
} else {
shutdownCleanupTasks.remove(taskArn);
@@ -130,6 +130,8 @@ public class EcsContainerManager {
* or before the Unix epoch is that zero value rather than a time a container reached.
*/
private static final Instant DOCKER_ZERO_TIMESTAMP = Instant.EPOCH;
/** The {@code FLUENT_HOST} the ECS agent gives an {@code awsvpc} task, whose containers share one namespace. */
private static final String FLUENT_AWSVPC_HOST = "127.0.0.1";
private final ContainerBuilder containerBuilder;
private final ContainerLifecycleManager lifecycleManager;
@@ -379,8 +381,18 @@ public class EcsContainerManager {
String networkModeName = taskDef.getNetworkMode() != null
? taskDef.getNetworkMode().name()
: NetworkMode.bridge.name();
SecurityGroupFirewallManager.Namespace sharedNamespace = null;
SecurityGroupFirewallManager.Namespace namespace = protectedNetwork == null ? null : protectedNetwork.namespace();
// The ENI a namespace helper is built around, which is how teardown finds the helper again.
String namespaceEniId = protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId();
try {
if (protectedNetwork == null && sharesTaskNetwork(task, taskDef)) {
// Set before the helper starts, so launch cleanup removes one a failed start left behind.
namespaceEniId = task.getNetworkInterfaceId();
sharedNamespace = prepareSharedNetwork(task, taskDef, region, taskId, taskRoleEndpoint);
namespace = sharedNamespace;
}
for (ContainerDefinition def : launchOrder) {
awaitDependencies(def, containerIds);
String containerName = ContainerStorageHelper.dockerName(config, "ecs-" + taskId + "-" + def.getName());
@@ -416,14 +428,17 @@ public class EcsContainerManager {
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
"ecs", taskId, regionResolver.getAccountId(), region))
.withLabels(ownerLabels());
if (namespace != null) {
specBuilder.withNetworkMode("container:" + namespace.helperId());
}
if (protectedNetwork != null) {
specBuilder.withNetworkMode("container:" + protectedNetwork.namespace().helperId());
specBuilder.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_WORKLOAD_LABEL, "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()) {
// has its own network namespace and so its own routing table. A task sharing one
// namespace has one address, which its helper holds.
if (taskRoleEndpoint.vending() && namespace == null) {
specBuilder.withLinkLocalIp(
linkLocalAddresses.allocate(taskRoleEndpoint.network(), task.getTaskArn()));
}
@@ -478,7 +493,7 @@ public class EcsContainerManager {
// Stable publishing serves existing host clients; dynamic publishing lets
// tasks sharing an awsvpc container port coexist on the Docker host.
if (protectedNetwork == null && def.getPortMappings() != null) {
if (namespace == null && def.getPortMappings() != null) {
boolean awsvpc = taskDef.getNetworkMode() == NetworkMode.awsvpc;
boolean publishAwsvpcPorts = awsvpc && config.services().ecs().publishAwsvpcPortsToHost();
boolean publishToHost = !containerDetector.isRunningInContainer()
@@ -577,7 +592,9 @@ public class EcsContainerManager {
lifecycleManager.removeIfExists(dockerId);
throw e;
}
fluentHost = inspectContainerIp(dockerId);
// The ECS agent's FLUENT_HOST for awsvpc, where every container shares the task's
// namespace; a router joined to a helper has no address of its own to inspect.
fluentHost = namespace != null ? FLUENT_AWSVPC_HOST : inspectContainerIp(dockerId);
} else {
ContainerInfo info = lifecycleManager.createAndStartEphemeral(spec, platform);
dockerId = info.containerId();
@@ -589,7 +606,7 @@ public class EcsContainerManager {
// Resolve network bindings for ECS-specific model
List<NetworkBinding> networkBindings = resolveNetworkBindings(
protectedNetwork == null ? dockerId : protectedNetwork.namespace().helperId(), def);
namespace == null ? dockerId : namespace.helperId(), def);
// Build ECS container model
Container container = buildContainer(task.getTaskArn(), def, dockerId, networkBindings, region,
@@ -614,23 +631,24 @@ public class EcsContainerManager {
}
}
}
// Inside the launch cleanup: a failed attachment leaves containers and a helper to remove.
if (task.getNetworkInterfaceId() != null && protectedNetwork == null) {
joinTaskVpcNetwork(task, taskDef, containerIds,
sharedNamespace == null ? null : sharedNamespace.helperId(), region);
}
} catch (Exception e) {
EcsTaskHandle partial = new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
firelensVolumeName,
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region,
stopTimeouts, taskVolumeNames);
firelensVolumeName, namespaceEniId, region, stopTimeouts, taskVolumeNames);
cleanupStoppedTask(partial);
if (protectedNetwork != null) {
releaseTaskNetwork(task, region);
}
if (!partial.allContainersRemoved() || partial.hasTaskVolumes() || partial.hasOpenLogStreams()) {
if (!partial.allContainersRemoved() || partial.hasTaskVolumes() || partial.hasOpenLogStreams()
|| partial.isNamespaceHelperPending()) {
throw new EcsTaskLaunchException(e, partial);
}
throw e;
}
if (task.getNetworkInterfaceId() != null && protectedNetwork == null) {
joinTaskVpcNetwork(task, taskDef, containerIds, region);
}
Map<String, Container> runtimeContainersByName = new LinkedHashMap<>();
for (Container container : runtimeContainers) {
@@ -658,9 +676,7 @@ public class EcsContainerManager {
task.setContainers(containersInDefinitionOrder);
return new EcsTaskHandle(task.getTaskArn(), containerIds, logStreamsByContainerId,
firelensVolumeName,
protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId(), region,
stopTimeouts, taskVolumeNames);
firelensVolumeName, namespaceEniId, region, stopTimeouts, taskVolumeNames);
}
private String taskVolumeName(EcsTask task, Volume volume) {
@@ -1156,27 +1172,32 @@ public class EcsContainerManager {
}
/**
* Puts one container of an awsvpc task on its VPC's Docker network at the task ENI address, so
* the address DescribeTasks reports answers. AWS gives the whole task that one address; here it
* goes to the first container that maps a port, else to the first container. Without
* Docker-backed VPC networks, or for an ENI address outside the subnet's planned range, the
* containers keep only the network they were created on. Removing the container disconnects
* it, before {@link #releaseTaskNetwork} returns the address.
* Puts the task ENI address on an awsvpc task's VPC Docker network, so the address DescribeTasks
* reports answers. AWS gives the whole task that one address. A task sharing one namespace gives
* it to the helper holding that namespace, so every container answers at it; otherwise it goes to
* the first container that maps a port, else to the first container. Without Docker-backed VPC
* networks, or for an ENI address outside the subnet's planned range, the containers keep only
* the network they were created on. Removing the holder disconnects it, before
* {@link #releaseTaskNetwork} returns the address.
*/
private void joinTaskVpcNetwork(EcsTask task, TaskDefinition taskDef, Map<String, String> containerIds,
String region) {
String namespaceHelperId, String region) {
String vpcId = taskVpcId(task, region);
if (vpcId == null) {
return;
}
List<ContainerDefinition> definitions = taskDef.getContainerDefinitions();
ContainerDefinition holder = definitions.stream()
.filter(def -> def.getPortMappings() != null && !def.getPortMappings().isEmpty())
.findFirst()
.orElse(definitions.getFirst());
String holderId = namespaceHelperId;
if (holderId == null) {
List<ContainerDefinition> definitions = taskDef.getContainerDefinitions();
ContainerDefinition holder = definitions.stream()
.filter(def -> def.getPortMappings() != null && !def.getPortMappings().isEmpty())
.findFirst()
.orElse(definitions.getFirst());
holderId = containerIds.get(holder.getName());
}
ec2Service.attachContainerToVpc(AwsArnUtils.accountOrDefault(task.getTaskArn(), regionResolver.getAccountId()),
region, vpcId, task.getNetworkConfiguration().getAwsvpcConfiguration().getSubnets().getFirst(),
containerIds.get(holder.getName()), task.getPrivateIpAddress());
holderId, task.getPrivateIpAddress());
}
/**
@@ -1391,6 +1412,84 @@ public class EcsContainerManager {
return address == null || address.isBlank() ? "127.0.0.1" : address;
}
/**
* Whether awsvpc tasks' containers share one namespace without security-group enforcement, which
* gives a task its own protected one instead.
*/
private boolean sharedTaskNetworkOn() {
return config.services().ecs().sharedTaskNetwork() && firewallManager != null && !firewallManager.enabled();
}
/**
* Whether this task's containers share one namespace: an awsvpc task, built around its ENI as a
* protected namespace is, so a task without one keeps a namespace per container.
*/
private boolean sharesTaskNetwork(EcsTask task, TaskDefinition definition) {
return definition.getNetworkMode() == NetworkMode.awsvpc && task.getNetworkInterfaceId() != null
&& sharedTaskNetworkOn();
}
/**
* Starts the helper holding an awsvpc task's one network namespace. The helper holds what the task
* has once rather than per container, as the ECS agent's pause container does: the published ports
* and the link-local address the credential endpoint is reached from.
*/
private SecurityGroupFirewallManager.Namespace prepareSharedNetwork(EcsTask task, TaskDefinition definition,
String region, String taskId,
TaskRoleCredentialEndpoint taskRoleEndpoint) {
Map<Integer, Integer> bindings = namespacePortBindings(
definition,
containerDetector.isRunningInContainer(),
config.services().ecs().publishAwsvpcPortsToHost(),
config.services().ecs().dynamicAwsvpcHostPorts());
List<String> linkLocalIps = taskRoleEndpoint.vending()
? List.of(linkLocalAddresses.allocate(taskRoleEndpoint.network(), task.getTaskArn()))
: List.of();
return firewallManager.createSharedNamespace("ecs", taskId, regionResolver.getAccountId(), region,
config.services().ecs().dockerNetwork(), bindings, Map.of(RUN_LABEL, runId), hostPortBindAddress(),
linkLocalIps);
}
/**
* Removes the helper of a task sharing one namespace, once its containers are gone. Throws when
* Docker keeps it, as the protected helper's removal does: the helper still holds the task's host
* ports and link-local address, which must not be handed on while it does. The handle then says the
* helper is pending, so the task's cleanup is retried, and the helper is taken off the VPC network
* so the ENI address it holds there is free when the ENI is released.
*/
private void removeSharedNetwork(EcsTaskHandle handle) {
if (handle.getNetworkInterfaceId() == null || !sharedTaskNetworkOn()) {
return;
}
String taskId = extractTaskId(handle.getTaskArn());
try {
firewallManager.removeSharedNamespaceStrict(taskId);
handle.recordNamespaceHelperPending(false);
} catch (RuntimeException e) {
handle.recordNamespaceHelperPending(true);
detachFromTaskVpc(handle, firewallManager.sharedNamespaceName(taskId));
throw e;
}
}
/** Best effort: a failure is logged, and the retried removal disconnects the helper anyway. */
private void detachFromTaskVpc(EcsTaskHandle handle, String containerName) {
if (ec2Service == null) {
return;
}
try {
ec2Service.describeNetworkInterfaces(handle.getRegion(), List.of(handle.getNetworkInterfaceId()),
Map.of(), 0, null)
.networkInterfaces().stream().findFirst()
.ifPresent(eni -> ec2Service.detachContainerFromVpc(
AwsArnUtils.accountOrDefault(handle.getTaskArn(), regionResolver.getAccountId()),
handle.getRegion(), eni.getVpcId(), containerName));
} catch (RuntimeException e) {
LOG.warnv(e, "Could not take the network namespace helper of ECS task {0} off its VPC network",
handle.getTaskArn());
}
}
static Map<Integer, Integer> namespacePortBindings(
TaskDefinition definition, boolean runningInContainer, boolean publishAwsvpcPortsToHost,
boolean dynamicAwsvpcHostPorts) {
@@ -1453,6 +1552,14 @@ public class EcsContainerManager {
revokeTaskRoleCredentials(handle.getTaskArn());
if (allRemoved) {
removeTaskVolumes(handle);
try {
removeSharedNetwork(handle);
} catch (RuntimeException e) {
// The handle now says the helper is pending, so the caller keeps it and the removal is
// retried; its address stays reserved until then, the cheaper mistake.
LOG.warnv(e, "Could not remove the network namespace helper of ECS task {0}", handle.getTaskArn());
return;
}
releaseTaskLinkLocalAddresses(handle.getTaskArn());
}
}
@@ -1547,6 +1654,7 @@ public class EcsContainerManager {
if (firewallManager != null && handle.getNetworkInterfaceId() != null) {
firewallManager.removeNamespaceStrict(handle.getNetworkInterfaceId());
}
removeSharedNetwork(handle);
cleanupProtectedNetwork(handle);
removeTaskVolumes(handle);
// Only now: a container that survived a failed removal still holds its address.
@@ -1989,7 +2097,8 @@ public class EcsContainerManager {
/**
* 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,
* to them, and the network to give each of them, or the helper of a task sharing one namespace,
* 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.
*/
@@ -42,6 +42,11 @@ public class EcsTaskHandle {
private final Map<String, Integer> exitCodes = new LinkedHashMap<>();
/** Container names confirmed removed, including those whose exit code was unavailable. */
private final Set<String> removedContainers = new HashSet<>();
/**
* Whether Docker kept the helper holding the task's network namespace when it was removed, so its
* removal still has to be retried while it holds the task's host ports and link-local address.
*/
private boolean namespaceHelperPending;
public EcsTaskHandle(String taskArn, Map<String, String> containerIds,
Map<String, Closeable> logStreamsByContainerId) {
@@ -144,4 +149,12 @@ public class EcsTaskHandle {
public boolean hasOpenLogStreams() {
return !logStreamsByContainerId.isEmpty();
}
public boolean isNamespaceHelperPending() {
return namespaceHelperPending;
}
public void recordNamespaceHelperPending(boolean pending) {
namespaceHelperPending = pending;
}
}
@@ -240,8 +240,9 @@ final class FirelensConfigGenerator {
static String tcpListen(String networkMode) {
// AWS binds 127.0.0.1 in awsvpc because every container shares the task's network
// namespace. Floci runs each container in its own namespace, so the router must listen
// on all interfaces for the injected FLUENT_HOST to be reachable from sibling containers.
// namespace. Floci gives each container a namespace of its own unless the task shares one,
// so the router listens on all interfaces for the injected FLUENT_HOST to be reachable from
// sibling containers either way.
return "0.0.0.0";
}
+3
View File
@@ -826,6 +826,9 @@ floci:
publish-awsvpc-ports-to-host: false
dynamic-awsvpc-host-ports: false
host-port-bind-address: "127.0.0.1"
# Put an awsvpc task's containers in one network namespace, so they reach each other on
# localhost as on Fargate, without security-group enforcement.
shared-task-network: false # FLOCI_SERVICES_ECS_SHARED_TASK_NETWORK
host-volume-roots: []
allow-unsafe-host-volumes: false
allow-privileged-containers: false
@@ -1,3 +1,3 @@
FROM alpine:3.21
FROM docker.io/library/alpine:3.21
RUN apk add --no-cache nftables iproute2 socat curl iptables
CMD ["sleep", "2147483647"]
@@ -4,11 +4,13 @@ import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectImageResponse;
import com.github.dockerjava.api.command.ListContainersCmd;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.Info;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.floci.aws.core.common.docker.ContainerSpec;
import io.floci.aws.core.common.docker.DockerHostResolver;
import org.junit.jupiter.api.Test;
@@ -20,6 +22,7 @@ import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -71,6 +74,57 @@ class SecurityGroupFirewallManagerTest {
"the helper resolves host.docker.internal");
}
@Test
void aSharedHelperNeedsNeitherEnforcementNorRootfulDockerAndInstallsNoFirewall() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.network().securityGroupEnforcement().enabled()).thenReturn(false);
when(config.network().securityGroupEnforcement().helperImage()).thenReturn("example/network-helper:test");
when(config.port()).thenReturn(4566);
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
when(config.docker().imageRegistryBase()).thenReturn(Optional.empty());
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
Info rootless = mock(Info.class);
when(rootless.getOsType()).thenReturn("linux");
when(rootless.getArchitecture()).thenReturn("amd64");
when(rootless.getSecurityOptions()).thenReturn(List.of("name=seccomp,profile=builtin", "name=rootless"));
when(dockerClient.infoCmd().exec()).thenReturn(rootless);
when(dockerClient.inspectContainerCmd("helper-id").exec().getNetworkSettings().getNetworks())
.thenReturn(Map.of("floci-net", new ContainerNetwork().withIpv4Address("172.18.0.9")));
DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
when(dockerHostResolver.isLinuxHost()).thenReturn(true);
EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.18.0.2"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenReturn(new ContainerInfo("helper-id", Map.of()));
SecurityGroupFirewallManager manager = new SecurityGroupFirewallManager(dockerClient,
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer), lifecycleManager, config,
embeddedDnsServer);
SecurityGroupFirewallManager.Namespace namespace = manager.createSharedNamespace("ecs", "abc123",
"000000000000", "us-east-1", Optional.of("floci-net"), Map.of(80, 0),
Map.of("io.floci.ecs.run", "run-1"), "127.0.0.1", List.of("169.254.170.1"));
assertEquals("helper-id", namespace.helperId());
assertEquals("172.18.0.9", namespace.transportAddress());
ArgumentCaptor<ContainerSpec> helper = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).createAndStart(helper.capture());
assertEquals("floci-aws-netns-abc123", helper.getValue().name());
assertEquals("floci-net", helper.getValue().networkMode());
assertEquals(List.of("169.254.170.1"), helper.getValue().linkLocalIps());
assertEquals(Map.of(80, 0), helper.getValue().portBindings());
assertEquals(Map.of(80, "127.0.0.1"), helper.getValue().portBindingHostIps());
assertTrue(helper.getValue().dnsServers().contains("172.18.0.2"), "the helper uses Floci's DNS");
assertEquals("ecs", helper.getValue().labels().get("io.floci.service"));
assertEquals("4566", helper.getValue().labels().get("io.floci.owner"));
assertEquals("run-1", helper.getValue().labels().get("io.floci.ecs.run"));
// Not a protected helper: a startup with enforcement on must not quarantine it as one.
assertFalse(helper.getValue().labels().containsKey("io.floci.security-group.helper"));
verify(dockerClient, never()).execCreateCmd(anyString());
manager.removeSharedNamespaceStrict("abc123");
verify(lifecycleManager).removeIfExistsStrict("floci-aws-netns-abc123");
}
@Test
void onlyFlocisDnsIsExemptFromTheSecurityGroups() {
EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
@@ -279,6 +279,34 @@ class EcsEssentialContainerExitServiceTest {
verify(manager, times(1)).releaseTaskNetwork(task, REGION);
}
@Test
void aNamespaceHelperDockerKeptAfterTheContainersExitedIsRetried() {
EcsTask task = runningTask(false);
when(manager.getExitCodeIfStopped("app-id")).thenReturn(9);
when(manager.getExitCodeIfStopped("sidecar-id")).thenReturn(0);
doAnswer(invocation -> {
EcsTaskHandle stopped = invocation.getArgument(0);
stopped.getContainerIds().keySet().forEach(stopped::recordContainerRemoved);
stopped.recordNamespaceHelperPending(true);
return null;
}).when(manager).cleanupStoppedTask(any());
when(manager.stopTaskAndCollectExitCodes(any())).thenAnswer(invocation -> {
handle.recordNamespaceHelperPending(false);
return completeDockerStop();
});
service.reconcile();
service.reconcile();
assertEquals("STOPPED", task.getLastStatus());
verify(manager, times(1)).cleanupStoppedTask(handle);
// The helper still holds the task's host ports and link-local address, so its removal is retried
// until Docker lets it go, and not after.
service.reconcile();
service.reconcile();
verify(manager, times(1)).stopTaskAndCollectExitCodes(handle);
}
private EcsTask runningTask(boolean explicitEssential) {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
@@ -0,0 +1,189 @@
package io.floci.aws.services.ecs;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerNetwork;
import com.github.dockerjava.api.model.HostConfig;
import io.floci.aws.core.common.docker.ContainerExec;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.net.VpcNetworkManager;
import io.floci.aws.services.ecs.model.AwsVpcConfiguration;
import io.floci.aws.services.ecs.model.Container;
import io.floci.aws.services.ecs.model.ContainerDefinition;
import io.floci.aws.services.ecs.model.EcsTask;
import io.floci.aws.services.ecs.model.LaunchType;
import io.floci.aws.services.ecs.model.NetworkConfiguration;
import io.floci.aws.services.ecs.model.NetworkMode;
import io.floci.aws.services.ecs.model.PortMapping;
import io.floci.aws.services.ecs.model.TaskDefinition;
import io.floci.aws.testing.DockerAvailability;
import io.floci.aws.testing.TestImages;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.floci.aws.testing.EcsTaskWaits.awaitLastStatus;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* With a shared task network and no security-group enforcement, the containers of an awsvpc task
* reach each other on localhost, and every one of them answers at the task's ENI address.
*/
@QuarkusTest
@TestProfile(EcsSharedTaskNetworkDockerIntegrationTest.SharedTaskNetworkProfile.class)
class EcsSharedTaskNetworkDockerIntegrationTest {
private static final String REGION = "us-east-1";
private static final String SUBNET = Ec2Service.defaultSubnetId("us-east-1", "a");
private static final int FRONT_PORT = 8080;
private static final int BACKEND_PORT = 8081;
/** Docker-backed ECS and VPC networks with a shared task network, enforcement left off. */
public static final class SharedTaskNetworkProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.ecs.mock", "false",
"floci.services.ec2.mock", "false",
"floci.services.ec2.vpc-networks.enabled", "true",
"floci.network.security-group-enforcement.enabled", "false",
"floci.services.ecs.shared-task-network", "true",
"floci.docker.resource-namespace", "ecs-shared-netns-it");
}
}
@Inject
EcsService ecsService;
@Inject
Ec2Service ec2Service;
@Inject
VpcNetworkManager vpcNetworkManager;
@Inject
DockerClient dockerClient;
@BeforeEach
void requireDocker() throws InterruptedException {
assumeTrue(DockerAvailability.isAvailable(), "Docker must be available for the shared task network test");
}
@Test
void containersOfATaskReachEachOtherOnLocalhostAndAllAnswerAtTheEniAddress() throws InterruptedException {
String clusterName = unique("shared-netns");
ecsService.createCluster(clusterName, REGION);
EcsTask task = ecsService.runTask(clusterName, registerFrontAndBackend().getTaskDefinitionArn(), 1,
LaunchType.FARGATE, null, null, List.of(), awsvpcNetwork(), REGION).getFirst();
String vpcId = ec2Service.describeSubnets(REGION, List.of(SUBNET), Map.of()).getFirst().getVpcId();
String network = null;
String probe = null;
try {
String taskArn = task.getTaskArn();
EcsTask described = awaitLastStatus(
() -> ecsService.describeTasks(clusterName, List.of(taskArn), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED");
assertEquals("RUNNING", described.getLastStatus(), "the task must start: " + described.getStoppedReason());
Container front = container(described, "front");
Container backend = container(described, "backend");
String frontMode = dockerClient.inspectContainerCmd(front.getDockerId()).exec().getHostConfig().getNetworkMode();
String backendMode = dockerClient.inspectContainerCmd(backend.getDockerId()).exec().getHostConfig()
.getNetworkMode();
assertTrue(frontMode.startsWith("container:"), "the front container joins a namespace: " + frontMode);
assertEquals(frontMode, backendMode, "both containers join the same namespace");
String helperId = frontMode.substring("container:".length());
assertNotEquals(front.getDockerId(), helperId, "a helper holds the namespace, not a task container");
ContainerExec.Result local = ContainerExec.run(dockerClient, front.getDockerId(), new String[] {"sh", "-c",
"for i in 1 2 3 4 5 6 7 8 9 10; do wget -q -O- -T 1 http://127.0.0.1:" + BACKEND_PORT
+ "/ && exit 0; sleep 0.2; done; exit 1"}, 30);
assertEquals(0, local.exitCode(), "front must reach backend on localhost: " + local.summary());
assertEquals("backend", local.stdout().trim());
String address = described.getPrivateIpAddress();
assertNotNull(address, "an awsvpc task must report its ENI address");
network = vpcNetworkManager.networkNameFor("000000000000", REGION, vpcId).orElseThrow();
ContainerNetwork onVpc = dockerClient.inspectContainerCmd(helperId).exec()
.getNetworkSettings().getNetworks().get(network);
assertNotNull(onVpc, "the helper must join the VPC network " + network);
assertEquals(address, onVpc.getIpAddress(), "the helper must hold the task's ENI address");
// backend maps no port, so it would not hold the ENI address with a namespace of its own.
probe = dockerClient.createContainerCmd(TestImages.BUSYBOX)
.withHostConfig(HostConfig.newHostConfig().withNetworkMode(network))
.withCmd("sh", "-c", "for i in 1 2 3 4 5 6 7 8 9 10; do "
+ "[ \"$(wget -q -O- -T 1 http://" + address + ":" + BACKEND_PORT + "/)\" = backend ] "
+ "&& exit 0; sleep 0.1; done; exit 1")
.exec().getId();
dockerClient.startContainerCmd(probe).exec();
assertEquals(0, dockerClient.waitContainerCmd(probe).start().awaitStatusCode(60, TimeUnit.SECONDS),
"a peer on the VPC network must reach backend at " + address);
ecsService.stopTask(clusterName, task.getTaskArn(), "shared task network test", REGION);
task = null;
assertThrows(NotFoundException.class, () -> dockerClient.inspectContainerCmd(helperId).exec(),
"a stopped task's helper must be removed");
} finally {
if (task != null) {
ecsService.stopTask(clusterName, task.getTaskArn(), "test teardown", REGION);
}
if (probe != null) {
dockerClient.removeContainerCmd(probe).withForce(true).exec();
}
if (network != null) {
// Also disconnects the endpoint Floci gives itself on the network when it runs in a container.
vpcNetworkManager.deleteVpcNetwork("000000000000", REGION, vpcId);
}
}
}
private TaskDefinition registerFrontAndBackend() {
ContainerDefinition front = server("front", FRONT_PORT);
front.setPortMappings(List.of(new PortMapping(FRONT_PORT)));
ContainerDefinition backend = server("backend", BACKEND_PORT);
return ecsService.registerTaskDefinition(unique("shared-netns-td"), List.of(front, backend),
NetworkMode.awsvpc, null, null, null, null, null, REGION);
}
private static ContainerDefinition server(String name, int port) {
ContainerDefinition container = new ContainerDefinition();
container.setName(name);
container.setImage(TestImages.BUSYBOX);
container.setCommand(List.of("sh", "-c", "mkdir -p /www && echo " + name
+ " > /www/index.html && exec httpd -f -p " + port + " -h /www"));
return container;
}
private static Container container(EcsTask task, String name) {
return task.getContainers().stream()
.filter(container -> name.equals(container.getName()))
.findFirst()
.orElseThrow(() -> new AssertionError("no container " + name + " in " + task.getContainers()));
}
private static NetworkConfiguration awsvpcNetwork() {
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
awsvpc.setSubnets(List.of(SUBNET));
NetworkConfiguration networkConfiguration = new NetworkConfiguration();
networkConfiguration.setAwsvpcConfiguration(awsvpc);
return networkConfiguration;
}
private static String unique(String prefix) {
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
}
}
@@ -0,0 +1,396 @@
package io.floci.aws.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
import com.github.dockerjava.api.command.InspectVolumeCmd;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.docker.ContainerBuilder;
import io.floci.aws.core.common.docker.ContainerDetector;
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
import io.floci.aws.core.common.docker.ContainerLogStreamer;
import io.floci.aws.core.common.docker.LaunchedContainerAwsEnv;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.SecurityGroupFirewallManager;
import io.floci.aws.services.ec2.model.GroupIdentifier;
import io.floci.aws.services.ec2.model.NetworkInterface;
import io.floci.aws.services.ec2.model.NetworkInterfaceListResult;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
import io.floci.aws.services.ecs.model.AwsVpcConfiguration;
import io.floci.aws.services.ecs.model.ContainerDefinition;
import io.floci.aws.services.ecs.model.EcsTask;
import io.floci.aws.services.ecs.model.FirelensConfiguration;
import io.floci.aws.services.ecs.model.LogConfiguration;
import io.floci.aws.services.ecs.model.NetworkConfiguration;
import io.floci.aws.services.ecs.model.NetworkMode;
import io.floci.aws.services.ecs.model.PortMapping;
import io.floci.aws.services.ecs.model.TaskDefinition;
import io.floci.aws.services.lambda.launcher.ImageCacheService.LaunchImage;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.secretsmanager.SecretsManagerService;
import io.floci.aws.services.ssm.SsmService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.LinkedHashMap;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.atLeastOnce;
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;
/**
* An awsvpc task's containers in one network namespace without security-group enforcement, held by
* a helper the firewall manager starts with no firewall in it.
*/
class EcsContainerManagerSharedTaskNetworkTest {
private static final String TASK_ARN = "arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123";
private static final String NETWORK = "floci-net";
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/task-role";
private static final String RELATIVE_URI = "/v2/credentials/abc";
private static final String OTHER_TASK = "arn:aws:ecs:us-east-1:000000000000:task/test-cluster/next";
private ContainerBuilder.Builder builder;
private ContainerLifecycleManager lifecycleManager;
private DockerClient dockerClient;
private EmulatorConfig config;
private Ec2Service ec2Service;
private SecurityGroupFirewallManager firewallManager;
private EcsTaskRoleCredentials taskRoleCredentials;
private EcsTaskLinkLocalAddresses linkLocalAddresses;
private EcsContainerManager manager;
@BeforeEach
void setUp() {
builder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
when(containerBuilder.resolveImage(anyString())).thenAnswer(invocation -> invocation.getArgument(0));
when(containerBuilder.resolveDockerNetwork(any())).thenReturn(Optional.of(NETWORK));
lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
.thenAnswer(invocation -> new LaunchImage(invocation.getArgument(0), null));
when(lifecycleManager.createAndStartEphemeral(any(), any())).thenReturn(new ContainerInfo("docker-id", Map.of()));
dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().sharedTaskNetwork()).thenReturn(true);
RegionResolver regionResolver = mock(RegionResolver.class);
when(regionResolver.getAccountId()).thenReturn("000000000000");
LaunchedContainerAwsEnv awsEnv = mock(LaunchedContainerAwsEnv.class);
when(awsEnv.sdkBaselineEnv(any(), any())).thenReturn(List.of());
EcrRegistryManager ecrRegistryManager = mock(EcrRegistryManager.class);
when(ecrRegistryManager.rewriteImageUri(anyString())).thenAnswer(inv -> inv.getArgument(0));
ec2Service = mock(Ec2Service.class);
firewallManager = mock(SecurityGroupFirewallManager.class);
when(firewallManager.enabled()).thenReturn(false);
when(firewallManager.createSharedNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(),
any(), any())).thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "172.18.0.9"));
taskRoleCredentials = mock(EcsTaskRoleCredentials.class);
when(taskRoleCredentials.issue(any(), any(), any(), any())).thenReturn(Optional.of(RELATIVE_URI));
linkLocalAddresses = new EcsTaskLinkLocalAddresses();
manager = new EcsContainerManager(
containerBuilder, lifecycleManager, mock(ContainerLogStreamer.class),
mock(ContainerDetector.class), config, regionResolver, awsEnv,
mock(SsmService.class), mock(SecretsManagerService.class), mock(S3Service.class),
ecrRegistryManager, mock(HostVolumePolicy.class),
ec2Service, firewallManager, taskRoleCredentials, mock(EcsCredentialsProxy.class),
linkLocalAddresses);
}
@Test
void everyContainerJoinsOneHelperThatHoldsTheTasksPorts() {
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(null,
container("web", 8081), container("proxy", 80)), List.of(), "us-east-1");
verify(builder, times(2)).withNetworkMode("container:helper-id");
verify(builder, never()).withLabels(Map.of("io.floci.security-group.workload", "true"));
verify(builder, never()).withPortBinding(anyInt(), anyInt());
verify(builder, never()).withPortBinding(anyInt(), anyInt(), anyString());
verify(builder, never()).withDynamicPort(anyInt());
verify(builder, never()).withExposedPort(anyInt());
@SuppressWarnings("unchecked")
ArgumentCaptor<Map<Integer, Integer>> ports = ArgumentCaptor.forClass(Map.class);
verify(firewallManager).createSharedNamespace(eq("ecs"), eq("abc123"), eq("000000000000"),
eq("us-east-1"), any(), ports.capture(), any(), eq("127.0.0.1"), eq(List.of()));
Map<Integer, Integer> expected = new LinkedHashMap<>();
expected.put(8081, 0);
expected.put(80, 0);
assertEquals(expected, ports.getValue());
// Each container's network bindings are read off the helper, which publishes them.
verify(dockerClient, atLeastOnce()).inspectContainerCmd("helper-id");
verify(firewallManager, never()).createNamespace(any(), any(), any(), any(), any(), any(), any(), any());
verify(firewallManager, never()).register(any(), any(), any());
verify(ec2Service, never()).createNetworkInterface(any(), any(), any(), any(), any(), any(), any());
assertEquals("eni-1", handle.getNetworkInterfaceId());
}
@Test
void theHelperHoldsTheTasksOneCredentialAddress() {
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 80), container("sidecar", 9000)),
List.of(), "us-east-1");
verify(firewallManager).createSharedNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(),
any(), eq(List.of("169.254.170.1")));
// A container joined to the helper has no network endpoint of its own to give an address to.
verify(builder, never()).withLinkLocalIp(anyString());
@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),
containerEnv.toString());
}
}
@Test
void theHelperHoldsTheEniAddressOnTheVpcNetwork() {
Subnet subnet = new Subnet();
subnet.setVpcId("vpc-1");
when(ec2Service.describeSubnets(eq("us-east-1"), eq(List.of("subnet-1")), any())).thenReturn(List.of(subnet));
manager.startTask(awsvpcTask(), taskDef(null, container("web", 8081), container("proxy", 80)),
List.of(), "us-east-1");
verify(ec2Service).attachContainerToVpc("000000000000", "us-east-1", "vpc-1", "subnet-1", "helper-id",
"10.0.0.10");
}
@Test
void fireLensIsReachedOnLoopbackAsTheEcsAgentSetsItForAwsvpc() {
when(lifecycleManager.create(any(), any())).thenReturn("router-id");
when(lifecycleManager.startCreated(anyString(), any())).thenReturn(new ContainerInfo("router-id", Map.of()));
InspectVolumeCmd inspectVolumeCmd = mock(InspectVolumeCmd.class);
InspectVolumeResponse volume = mock(InspectVolumeResponse.class);
when(dockerClient.inspectVolumeCmd(anyString())).thenReturn(inspectVolumeCmd);
when(inspectVolumeCmd.exec()).thenReturn(volume);
when(volume.getMountpoint()).thenReturn("/var/lib/docker/volumes/floci-ecs-firelens-abc123/_data");
CopyArchiveToContainerCmd copyCmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
when(dockerClient.copyArchiveToContainerCmd("router-id")).thenReturn(copyCmd);
ContainerDefinition router = container("log_router", 0);
router.setFirelensConfiguration(new FirelensConfiguration("fluentbit", Map.of()));
ContainerDefinition app = container("app", 0);
app.setLogConfiguration(new LogConfiguration("awsfirelens", Map.of("Name", "cloudwatch"), null));
manager.startTask(awsvpcTask(), taskDef(null, app, router), List.of(), "us-east-1");
verify(builder, times(2)).withNetworkMode("container:helper-id");
@SuppressWarnings("unchecked")
ArgumentCaptor<List<String>> env = ArgumentCaptor.forClass(List.class);
verify(builder, times(2)).withEnv(env.capture());
assertTrue(env.getAllValues().stream().anyMatch(containerEnv -> containerEnv.contains("FLUENT_HOST=127.0.0.1")),
env.getAllValues().toString());
}
@Test
void stoppingRemovesTheHelperOnceTheContainersAreGoneAndThenFreesItsAddress() {
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 80)),
List.of(), "us-east-1");
manager.stopTaskAndCollectExitCodes(handle);
verify(firewallManager).removeSharedNamespaceStrict("abc123");
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
"the stopped task's address is free again");
}
@Test
void theHelperOutlivesAContainerDockerWouldNotRemove() {
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(null, container("app", 80)),
List.of(), "us-east-1");
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.removeContainerCmd("docker-id")).thenReturn(remove);
doThrow(new IllegalStateException("removal in progress")).when(remove).exec();
manager.stopTaskAndCollectExitCodes(handle);
verify(firewallManager, never()).removeSharedNamespaceStrict(anyString());
}
@Test
void aHelperDockerKeepsIsTakenOffTheVpcNetworkAndRetriedBeforeItsAddressIsFreed() {
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
when(firewallManager.sharedNamespaceName("abc123")).thenReturn("floci-aws-netns-abc123");
NetworkInterface eni = new NetworkInterface();
eni.setNetworkInterfaceId("eni-1");
eni.setVpcId("vpc-1");
when(ec2Service.describeNetworkInterfaces(eq("us-east-1"), eq(List.of("eni-1")), anyMap(), eq(0), isNull()))
.thenReturn(new NetworkInterfaceListResult(List.of(eni), null));
doThrow(new IllegalStateException("helper busy")).doNothing()
.when(firewallManager).removeSharedNamespaceStrict("abc123");
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 80)),
List.of(), "us-east-1");
assertThrows(IllegalStateException.class, () -> manager.stopTaskAndCollectExitCodes(handle));
assertTrue(handle.isNamespaceHelperPending(), "the handle keeps the helper's removal to retry");
// So the ENI address it holds there is free when the task's ENI is released.
verify(ec2Service).detachContainerFromVpc("000000000000", "us-east-1", "vpc-1", "floci-aws-netns-abc123");
verify(taskRoleCredentials).revoke(TASK_ARN);
assertEquals("169.254.170.3", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
"169.254.170.1 is still the helper's, and .2 is the endpoint's own");
linkLocalAddresses.releaseAll(OTHER_TASK);
manager.stopTaskAndCollectExitCodes(handle);
assertFalse(handle.isNamespaceHelperPending());
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
"the retried removal frees the helper's address");
}
@Test
void aHelperThatCannotStartFailsTheLaunchAndFreesItsAddressOnceItIsGone() {
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
when(firewallManager.createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("cannot start the helper"));
assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(),
taskDef(ROLE_ARN, container("app", 80)), List.of(), "us-east-1"));
verify(lifecycleManager, never()).createAndStartEphemeral(any(), any());
// Confirmed by name, since a failed start may have left the helper behind.
verify(firewallManager).removeSharedNamespaceStrict("abc123");
verify(taskRoleCredentials).revoke(TASK_ARN);
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, OTHER_TASK));
}
@Test
void aHelperAFailedStartLeftBehindKeepsItsAddressAndItsCleanup() {
when(config.services().ecs().taskRoleCredentials().enabled()).thenReturn(true);
when(firewallManager.createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("inspect failed after the helper started"));
doThrow(new IllegalStateException("helper busy")).when(firewallManager).removeSharedNamespaceStrict("abc123");
EcsTaskLaunchException failed = assertThrows(EcsTaskLaunchException.class, () -> manager.startTask(
awsvpcTask(), taskDef(ROLE_ARN, container("app", 80)), List.of(), "us-east-1"));
assertTrue(failed.getHandle().isNamespaceHelperPending(), "the service keeps the handle to retry");
assertEquals("169.254.170.3", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
"the helper Docker kept still holds 169.254.170.1");
}
@Test
void aFailedVpcAttachmentRemovesTheContainersAndTheHelper() {
Subnet subnet = new Subnet();
subnet.setVpcId("vpc-1");
when(ec2Service.describeSubnets(eq("us-east-1"), eq(List.of("subnet-1")), any())).thenReturn(List.of(subnet));
when(ec2Service.attachContainerToVpc(any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("VPC network is gone"));
assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(),
taskDef(null, container("web", 8081)), List.of(), "us-east-1"));
verify(lifecycleManager).stopAndRemoveStrict(eq("docker-id"), any(), anyInt(), anyBoolean());
verify(firewallManager).removeSharedNamespaceStrict("abc123");
}
@Test
void withTheSettingOffEachContainerKeepsANamespaceOfItsOwn() {
when(config.services().ecs().sharedTaskNetwork()).thenReturn(false);
manager.startTask(awsvpcTask(), taskDef(null, container("app", 80)), List.of(), "us-east-1");
verify(firewallManager, never()).createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(),
any());
verify(builder, never()).withNetworkMode(anyString());
verify(builder).withPortBinding(80, 0, "127.0.0.1");
}
@Test
void enforcementGivesTheTaskItsProtectedNamespaceInstead() {
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("stop once the protected path is taken"));
NetworkInterface eni = new NetworkInterface();
eni.setNetworkInterfaceId("eni-1");
eni.setGroups(List.of(new GroupIdentifier("sg-1", "default")));
when(ec2Service.createNetworkInterface(any(), eq("subnet-1"), any(), any(), any(), any(), any()))
.thenReturn(eni);
assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(),
taskDef(null, container("app", 80)), List.of(), "us-east-1"));
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any());
verify(firewallManager, never()).createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(),
any());
}
@Test
void aBridgeTaskKeepsANamespacePerContainer() {
TaskDefinition bridge = taskDef(null, container("app", 80));
bridge.setNetworkMode(NetworkMode.bridge);
manager.startTask(awsvpcTask(), bridge, List.of(), "us-east-1");
verify(firewallManager, never()).createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(),
any());
verify(builder, never()).withNetworkMode(anyString());
}
private static EcsTask awsvpcTask() {
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
awsvpc.setSubnets(List.of("subnet-1"));
awsvpc.setSecurityGroups(List.of("sg-1"));
NetworkConfiguration network = new NetworkConfiguration();
network.setAwsvpcConfiguration(awsvpc);
EcsTask task = new EcsTask();
task.setTaskArn(TASK_ARN);
task.setNetworkConfiguration(network);
// As attachTaskNetwork leaves it before the containers start.
task.setNetworkInterfaceId("eni-1");
task.setPrivateIpAddress("10.0.0.10");
return task;
}
private static ContainerDefinition container(String name, int port) {
ContainerDefinition container = new ContainerDefinition();
container.setName(name);
container.setImage(name + ":latest");
if (port > 0) {
container.setPortMappings(List.of(new PortMapping(port, port, "tcp")));
}
return container;
}
private static TaskDefinition taskDef(String taskRoleArn, ContainerDefinition... containers) {
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("shared-family");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setTaskRoleArn(taskRoleArn);
taskDef.setContainerDefinitions(List.of(containers));
return taskDef;
}
}