feat(ecs): vend task-role credentials to security-group protected tasks (#8721)

A task under security-group enforcement started without
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI and kept Floci's baseline
identity, because its containers share the firewall helper's namespace
and had no route to the proxy holding 169.254.170.2.

The helper already joins the ECS Docker network the proxy sits on. It
now takes the task's one link-local address, which every container in
the namespace shares, and the compiled nftables table allows TCP to
169.254.170.2:80. AWS security groups do not filter the ECS task
metadata endpoints, and the exception covers that one listener only.

The protected namespace is now built inside the launch cleanup, once the
credentials are issued, as a shared task network's is. Its helper is
removed by name, and confirmed gone, before the task's link-local
address goes back to the pool. A helper Docker keeps leaves the task's
cleanup pending, to be retried.

Closes #4503

Co-authored-by: lex00 <121451605+lex00@users.noreply.github.com>
This commit is contained in:
Priamo Germosenandlex00 authored and GitHub committed 2026-11-17 06:49:02 -04:00
1 parent b3582da1f5
commit 151cb586f9
12 files changed
+750 -132

No files matched your search

+7 -4
View File
@@ -1006,6 +1006,12 @@ so Floci runs a small proxy container that holds that address on the task's netw
in `169.254.0.0/16`, without which it would have no route to the endpoint at all. Docker only
allows both of those on a user-defined network.
A task under security-group enforcement gets its credentials the same way. Its containers share the
helper's protected namespace, so the helper takes the one link-local address for the whole task, and
the helper's ruleset always lets TCP to `169.254.170.2:80` through. AWS security groups do not
filter traffic to the ECS task metadata endpoints either. The exception covers that one listener
and nothing else on the network.
```bash
docker network create floci-net
@@ -1023,7 +1029,7 @@ Credentials a task sets for itself always win. Floci drops only the baseline `AW
environment credentials before the container endpoint and leaving them in place would silently
shadow the role. Anything the task definition sets explicitly is left alone.
In three cases a task that asks for a role gets none. It starts without the relative URI and keeps
In two cases a task that asks for a role gets none. It starts without the relative URI and keeps
whatever baseline credentials Floci would have injected anyway. Usually that is the emulator's
default account, but if Floci itself was started with AWS credentials in its environment those are
forwarded into the task instead, and Floci logs a warning once per process when it does that.
@@ -1036,9 +1042,6 @@ for reasons that have nothing to do with the role's policy.
names a different account: Floci looks the role up in the account the request authenticated as
and requires an exact ARN match, so a cross-account `taskRoleArn` never resolves.
- **No user-defined Docker network is configured.** The endpoint has nowhere to listen.
- **The task runs under security-group enforcement.** Its containers join an isolated helper
namespace rather than the shared network the proxy sits on, so the endpoint would not be
reachable.
Each of these logs a warning naming the task and the role it asked for.
@@ -117,6 +117,18 @@ public class SecurityGroupFirewallManager {
public Namespace createNamespace(String service, String resourceId, String accountId, String region,
Optional<String> dockerNetwork, Map<Integer, Integer> portBindings,
Map<String, String> extraLabels, String hostIp) {
return createNamespace(service, resourceId, accountId, region, dockerNetwork, portBindings, extraLabels,
hostIp, List.of());
}
/**
* {@link #createNamespace} with {@code linkLocalIps} on the helper's Docker network endpoint. Every workload
* shares the helper's namespace, so one address gives all of them a connected route into 169.254.0.0/16, which
* is what an ECS task needs to reach its credential endpoint at 169.254.170.2.
*/
public Namespace createNamespace(String service, String resourceId, String accountId, String region,
Optional<String> dockerNetwork, Map<Integer, Integer> portBindings,
Map<String, String> extraLabels, String hostIp, List<String> linkLocalIps) {
if (!enabled()) {
throw new IllegalStateException("Security-group enforcement is disabled");
}
@@ -133,6 +145,7 @@ public class SecurityGroupFirewallManager {
.withLabels(Map.of(ContainerStorageHelper.SECURITY_GROUP_HELPER_LABEL, "true",
ContainerStorageHelper.OWNER_LABEL, ContainerStorageHelper.ownerIdentity(config)))
.withLabels(extraLabels);
linkLocalIps.forEach(builder::withLinkLocalIp);
return startHelper(builder, resourceId, "protected",
helperId -> apply(helperId, SecurityGroupNftCompiler.initialRuleset()));
}
@@ -154,6 +167,16 @@ public class SecurityGroupFirewallManager {
return startHelper(builder, resourceId, "shared", helperId -> { });
}
/**
* Removes the helper {@link #createNamespace} 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. Found by its name, so this also
* removes a helper whose ENI was never registered, or was already forgotten, which {@link #removeNamespaceStrict}
* cannot find.
*/
public void removeProtectedNamespaceStrict(String resourceId) {
lifecycleManager.removeIfExistsStrict(helperName(PROTECTED_HELPER_PREFIX, resourceId));
}
/**
* 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.
@@ -16,6 +16,9 @@ import java.util.Set;
/** Builds only rules for an endpoint's private nftables table. Docker's tables are untouched. */
public final class SecurityGroupNftCompiler {
/** The ECS task metadata and credentials endpoint, which security groups do not filter on AWS. */
static final String ECS_TASK_METADATA_ADDRESS = "169.254.170.2";
private SecurityGroupNftCompiler() {}
/**
@@ -116,8 +119,10 @@ public final class SecurityGroupNftCompiler {
// Docker's embedded DNS listens on loopback but forwards from this namespace. Security
// groups never filter the VPC resolver on AWS. Only DNS is exempt, because the resolver
// address also serves Floci's API. DHCP and the link-local metadata endpoint are the
// other local infrastructure exceptions.
// address also serves Floci's API. DHCP, the link-local metadata endpoint and the ECS
// task metadata endpoint, where a task reads its role credentials, are the other local
// infrastructure exceptions. The ECS endpoint is opened for its one listener only, so a
// workload cannot use it to reach anything else on the Docker network.
for (String server : vpcResolvers) {
String family = server.contains(":") ? "ip6" : "ip";
rules.append("add rule inet floci_sg egress ").append(family).append(" daddr ").append(server)
@@ -128,7 +133,9 @@ public final class SecurityGroupNftCompiler {
rules.append("add rule inet floci_sg egress udp sport 68 udp dport 67 accept\n")
.append("add rule inet floci_sg ingress udp sport 67 udp dport 68 accept\n")
.append("add rule inet floci_sg egress ip daddr 169.254.169.254 accept\n")
.append("add rule inet floci_sg ingress ip saddr 169.254.169.254 accept\n");
.append("add rule inet floci_sg ingress ip saddr 169.254.169.254 accept\n")
.append("add rule inet floci_sg egress ip daddr ").append(ECS_TASK_METADATA_ADDRESS)
.append(" tcp dport 80 accept\n");
List<Endpoint> managed = peers == null ? List.of() : peers.stream()
.filter(peer -> !target.eniId().equals(peer.eniId()))
@@ -302,11 +302,10 @@ 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);
// 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.
TaskRoleCredentialEndpoint taskRoleEndpoint = prepareTaskRoleCredentials(task, taskDef);
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<>();
@@ -381,14 +380,21 @@ public class EcsContainerManager {
String networkModeName = taskDef.getNetworkMode() != null
? taskDef.getNetworkMode().name()
: NetworkMode.bridge.name();
PreparedNetwork protectedNetwork = null;
SecurityGroupFirewallManager.Namespace sharedNamespace = null;
SecurityGroupFirewallManager.Namespace namespace = protectedNetwork == null ? null : protectedNetwork.namespace();
SecurityGroupFirewallManager.Namespace namespace = null;
// The ENI a namespace helper is built around, which is how teardown finds the helper again.
String namespaceEniId = protectedNetwork == null ? null : protectedNetwork.eni().getNetworkInterfaceId();
String namespaceEniId = null;
try {
if (protectedNetwork == null && sharesTaskNetwork(task, taskDef)) {
// Set before the helper starts, so launch cleanup removes one a failed start left behind.
// Either helper is started inside the launch cleanup, with the ENI id set before it starts, so
// a helper a failed start left behind is removed before the link-local address it holds is freed.
if (protectsTaskNetwork(taskDef)) {
namespaceEniId = task.getNetworkInterfaceId();
protectedNetwork = prepareNetwork(task, taskDef, region, taskId, taskRoleEndpoint);
namespaceEniId = protectedNetwork.eni().getNetworkInterfaceId();
namespace = protectedNetwork.namespace();
} else if (sharesTaskNetwork(task, taskDef)) {
namespaceEniId = task.getNetworkInterfaceId();
sharedNamespace = prepareSharedNetwork(task, taskDef, region, taskId, taskRoleEndpoint);
namespace = sharedNamespace;
@@ -437,7 +443,7 @@ public class EcsContainerManager {
// 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. A task sharing one
// namespace has one address, which its helper holds.
// namespace, protected or not, has one address, which its helper holds.
if (taskRoleEndpoint.vending() && namespace == null) {
specBuilder.withLinkLocalIp(
linkLocalAddresses.allocate(taskRoleEndpoint.network(), task.getTaskArn()));
@@ -1347,11 +1353,18 @@ public class EcsContainerManager {
}
}
private PreparedNetwork prepareNetwork(EcsTask task, TaskDefinition definition, String region, String taskId) {
if (definition.getNetworkMode() != NetworkMode.awsvpc
|| firewallManager == null || !firewallManager.enabled()) {
return null;
}
/** Whether this task's containers share a security-group protected namespace: awsvpc under enforcement. */
private boolean protectsTaskNetwork(TaskDefinition definition) {
return definition.getNetworkMode() == NetworkMode.awsvpc && firewallManager != null && firewallManager.enabled();
}
/**
* Builds an awsvpc task's protected namespace around its ENI. The helper holds the task's one link-local
* address when it gets role credentials: every container shares the helper's namespace, and the helper's
* ruleset always lets 169.254.170.2:80 through, as AWS security groups never filter that endpoint.
*/
private PreparedNetwork prepareNetwork(EcsTask task, TaskDefinition definition, String region, String taskId,
TaskRoleCredentialEndpoint taskRoleEndpoint) {
AwsVpcConfiguration awsvpc = task.getNetworkConfiguration() == null ? null
: task.getNetworkConfiguration().getAwsvpcConfiguration();
if (awsvpc == null || awsvpc.getSubnets() == null || awsvpc.getSubnets().isEmpty()) {
@@ -1372,9 +1385,12 @@ public class EcsContainerManager {
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();
namespace = firewallManager.createNamespace("ecs", taskId, regionResolver.getAccountId(),
region, config.services().ecs().dockerNetwork(), bindings, Map.of(RUN_LABEL, runId),
hostPortBindAddress());
hostPortBindAddress(), linkLocalIps);
List<String> groupIds = eni.getGroups().stream().map(g -> g.getGroupId()).toList();
List<SecurityGroup> groups = ec2Service.describeSecurityGroups(region, groupIds, List.of(), Map.of());
if (groups.size() != groupIds.size()) {
@@ -1451,23 +1467,35 @@ public class EcsContainerManager {
}
/**
* 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.
* Removes the helper holding a task's one namespace, protected or shared, once its containers are
* gone. Throws when Docker keeps it: 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. A shared helper is also 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()) {
private void removeNamespaceHelper(EcsTaskHandle handle) {
if (handle.getNetworkInterfaceId() == null || firewallManager == null) {
return;
}
boolean shared = sharedTaskNetworkOn();
String taskId = extractTaskId(handle.getTaskArn());
try {
firewallManager.removeSharedNamespaceStrict(taskId);
if (shared) {
firewallManager.removeSharedNamespaceStrict(taskId);
} else {
// The registered helper first, keeping its identity if Docker fails, then by its name one whose
// ENI was never registered or was already forgotten.
firewallManager.removeNamespaceStrict(handle.getNetworkInterfaceId());
if (firewallManager.enabled()) {
firewallManager.removeProtectedNamespaceStrict(taskId);
}
}
handle.recordNamespaceHelperPending(false);
} catch (RuntimeException e) {
handle.recordNamespaceHelperPending(true);
detachFromTaskVpc(handle, firewallManager.sharedNamespaceName(taskId));
if (shared) {
detachFromTaskVpc(handle, firewallManager.sharedNamespaceName(taskId));
}
throw e;
}
}
@@ -1553,7 +1581,7 @@ public class EcsContainerManager {
if (allRemoved) {
removeTaskVolumes(handle);
try {
removeSharedNetwork(handle);
removeNamespaceHelper(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.
@@ -1650,11 +1678,9 @@ public class EcsContainerManager {
terminatedContainerIds.forEach(dockerId -> finalizeLogStream(handle, dockerId));
try {
if (handle.allContainersRemoved()) {
// Confirm the helper released its host ports before unregister forgets its identity.
if (firewallManager != null && handle.getNetworkInterfaceId() != null) {
firewallManager.removeNamespaceStrict(handle.getNetworkInterfaceId());
}
removeSharedNetwork(handle);
// Confirm the helper released its host ports and link-local address before unregister
// forgets its identity.
removeNamespaceHelper(handle);
cleanupProtectedNetwork(handle);
removeTaskVolumes(handle);
// Only now: a container that survived a failed removal still holds its address.
@@ -2020,15 +2046,13 @@ public class EcsContainerManager {
* 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.
* <p>Empty when the task asks for no role, when the feature is off, or when the role cannot be
* resolved. A security-group protected task is served too: its helper joins the network the
* proxy holds its address on and takes the task's link-local address (see
* {@link #prepareNetwork}). 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) {
private TaskRoleCredentialEndpoint prepareTaskRoleCredentials(EcsTask task, TaskDefinition taskDef) {
String taskRoleArn = taskDef.getTaskRoleArn();
if (taskRoleArn == null || taskRoleArn.isBlank()) {
return TaskRoleCredentialEndpoint.none();
@@ -2039,12 +2063,6 @@ public class EcsContainerManager {
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 "
@@ -74,6 +74,45 @@ class SecurityGroupFirewallManagerTest {
"the helper resolves host.docker.internal");
}
@Test
void aProtectedHelperTakesTheLinkLocalAddressItsWorkloadsShareAndIsRemovedByName() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.network().securityGroupEnforcement().enabled()).thenReturn(true);
when(config.network().securityGroupEnforcement().helperImage()).thenReturn("example/network-helper:test");
when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
when(config.docker().imageRegistryBase()).thenReturn(Optional.empty());
DockerClient dockerClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
Info linux = mock(Info.class);
when(linux.getOsType()).thenReturn("linux");
when(linux.getArchitecture()).thenReturn("amd64");
when(dockerClient.infoCmd().exec()).thenReturn(linux);
InspectImageResponse image = mock(InspectImageResponse.class);
when(image.getOs()).thenReturn("linux");
when(image.getArch()).thenReturn("amd64");
when(dockerClient.inspectImageCmd(anyString()).exec()).thenReturn(image);
DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
when(dockerHostResolver.isLinuxHost()).thenReturn(true);
EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.createAndStart(any())).thenThrow(new IllegalStateException("stop after the spec"));
SecurityGroupFirewallManager manager = new SecurityGroupFirewallManager(dockerClient,
new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer), lifecycleManager, config,
embeddedDnsServer);
assertThrows(IllegalStateException.class, () -> manager.createNamespace("ecs", "abc123", "000000000000",
"us-east-1", Optional.of("floci-net"), Map.of(), Map.of(), "127.0.0.1", List.of("169.254.170.1")));
ArgumentCaptor<ContainerSpec> helper = ArgumentCaptor.forClass(ContainerSpec.class);
verify(lifecycleManager).createAndStart(helper.capture());
assertEquals(List.of("169.254.170.1"), helper.getValue().linkLocalIps());
assertEquals("floci-net", helper.getValue().networkMode());
assertEquals("floci-aws-sg-abc123", helper.getValue().name());
manager.removeProtectedNamespaceStrict("abc123");
verify(lifecycleManager).removeIfExistsStrict("floci-aws-sg-abc123");
}
@Test
void aSharedHelperNeedsNeitherEnforcementNorRootfulDockerAndInstallsNoFirewall() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
@@ -89,6 +89,20 @@ class SecurityGroupNftCompilerTest {
assertFalse(nft.contains("daddr 172.18.0.2 accept"), "only DNS is allowed to the resolver");
}
@Test
void theEcsTaskMetadataEndpointStaysReachableOnItsOneListenerOnly() {
SecurityGroup group = new SecurityGroup();
group.setVpcId("vpc-1");
group.setOwnerId("000000000000");
String nft = SecurityGroupNftCompiler.compile(endpoint("eni-a", "10.0.0.2", "172.17.0.2", group),
List.of(), Map.of(), List.of());
assertTrue(nft.contains("add rule inet floci_sg egress ip daddr 169.254.170.2 tcp dport 80 accept\n"), nft);
assertFalse(nft.contains("daddr 169.254.170.2 accept"), "only the endpoint's listener is allowed");
assertFalse(nft.contains("saddr 169.254.170.2"), "replies ride the established rule; nothing opens ingress");
}
/** A group allowing tcp/443 from {@code cidrIpv6} only. */
private static SecurityGroup ipv6Group(String cidrIpv6) {
SecurityGroup group = new SecurityGroup();
@@ -0,0 +1,267 @@
package io.floci.aws.services.ecs;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.api.model.Network;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.SecurityGroupFirewallManager;
import io.floci.aws.services.ec2.model.IpPermission;
import io.floci.aws.services.ec2.model.IpRange;
import io.floci.aws.services.ec2.model.SecurityGroup;
import io.floci.aws.services.ecs.container.EcsCredentialsProxy;
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.KeyValuePair;
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.TaskDefinition;
import io.floci.aws.testing.TestImages;
import io.floci.aws.testutil.FreePorts;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import io.restassured.RestAssured;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
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 io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A task under security-group enforcement reads its role credentials from 169.254.170.2 and calls STS
* with them from inside its protected namespace, while its security group still drops a port it does
* not allow. That port is the credentials server's own port on the Floci host, so the test also shows
* that the endpoint's exception opens no path around the proxy.
*
* <p>Skipped without a Linux Docker daemon, which security-group enforcement requires.
*/
@QuarkusTest
@TestProfile(EcsSecurityGroupTaskRoleDockerIntegrationTest.ProtectedTaskRoleProfile.class)
class EcsSecurityGroupTaskRoleDockerIntegrationTest {
private static final Logger LOG = Logger.getLogger(EcsSecurityGroupTaskRoleDockerIntegrationTest.class);
private static final String REGION = "us-east-1";
private static final String SUBNET = Ec2Service.defaultSubnetId("us-east-1", "a");
private static final String NETWORK = "floci-ecs-sg-task-role-it";
private static final int CREDENTIALS_PORT = freePort();
/** STS GetCallerIdentity signed with the vended credentials, using only the Python standard library. */
private static final String TASK_SCRIPT = """
import datetime, hashlib, hmac, json, os, re, socket, time, urllib.parse, urllib.request
uri = os.environ["AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"]
creds = json.loads(urllib.request.urlopen("http://169.254.170.2" + uri, timeout=10).read())
print("CREDENTIALS " + creds["AccessKeyId"], flush=True)
endpoint = urllib.parse.urlparse(os.environ["FLOCI_URL"])
body = "Action=GetCallerIdentity&Version=2011-06-15"
now = datetime.datetime.now(datetime.timezone.utc)
amz_date, day = now.strftime("%Y%m%dT%H%M%SZ"), now.strftime("%Y%m%d")
region = os.environ.get("AWS_REGION", "us-east-1")
headers = {"content-type": "application/x-www-form-urlencoded; charset=utf-8",
"host": endpoint.netloc, "x-amz-date": amz_date, "x-amz-security-token": creds["Token"]}
signed = ";".join(sorted(headers))
canonical = "\\n".join(["POST", "/", "", "".join(k + ":" + headers[k] + "\\n" for k in sorted(headers)),
signed, hashlib.sha256(body.encode()).hexdigest()])
scope = day + "/" + region + "/sts/aws4_request"
to_sign = "\\n".join(["AWS4-HMAC-SHA256", amz_date, scope, hashlib.sha256(canonical.encode()).hexdigest()])
key = ("AWS4" + creds["SecretAccessKey"]).encode()
for part in (day, region, "sts", "aws4_request"):
key = hmac.new(key, part.encode(), hashlib.sha256).digest()
signature = hmac.new(key, to_sign.encode(), hashlib.sha256).hexdigest()
headers["authorization"] = ("AWS4-HMAC-SHA256 Credential=" + creds["AccessKeyId"] + "/" + scope
+ ", SignedHeaders=" + signed + ", Signature=" + signature)
request = urllib.request.Request(endpoint.geturl().rstrip("/") + "/", data=body.encode(),
headers=headers, method="POST")
reply = urllib.request.urlopen(request, timeout=10).read().decode()
print("IDENTITY " + re.search("<Arn>([^<]+)</Arn>", reply).group(1), flush=True)
probe = socket.socket()
probe.settimeout(3)
try:
probe.connect((endpoint.hostname, int(os.environ["DENIED_PORT"])))
print("DENIED_PORT open", flush=True)
except OSError as e:
print("DENIED_PORT blocked " + type(e).__name__, flush=True)
time.sleep(600)
""";
/**
* Real containers, task-role credentials on, and a user-defined network for the proxy. Security-group
* enforcement is already on in the test configuration.
*/
public static final class ProtectedTaskRoleProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.ecs.mock", "false",
"floci.services.ecs.docker-network", NETWORK,
"floci.services.ecs.task-role-credentials.enabled", "true",
"floci.services.ecs.task-role-credentials.port", String.valueOf(CREDENTIALS_PORT),
"floci.docker.resource-namespace", "ecs-sg-task-role-it");
}
}
@Inject
EcsService ecsService;
@Inject
Ec2Service ec2Service;
@Inject
SecurityGroupFirewallManager firewallManager;
@Inject
EcsCredentialsProxy credentialsProxy;
@Inject
DockerClient dockerClient;
@BeforeEach
void requireLinuxDockerWithEnforcement() {
Assumptions.assumeTrue(firewallManager.enabled());
try {
Assumptions.assumeTrue("linux".equalsIgnoreCase(dockerClient.infoCmd().exec().getOsType()));
} catch (RuntimeException e) {
Assumptions.abort("Docker daemon is unavailable");
}
}
@Test
void aProtectedTaskRunsAsItsRoleWhileItsGroupStillDropsOtherPorts() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String networkId = ensureNetwork();
String cluster = "ecs-protected-" + suffix;
String taskArn = null;
try {
String roleName = "ecs-protected-task-role-" + suffix;
given().contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateRole").formParam("RoleName", roleName)
.formParam("AssumeRolePolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":"
+ "[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"ecs-tasks.amazonaws.com\"},"
+ "\"Action\":\"sts:AssumeRole\"}]}")
.post("/").then().statusCode(200);
// Egress to Floci's API only: the credentials server's port stays closed to the task.
String vpcId = ec2Service.describeSubnets(REGION, List.of(SUBNET), Map.of()).getFirst().getVpcId();
SecurityGroup group = ec2Service.createSecurityGroup(REGION, "ecs-protected-" + suffix,
"egress to the Floci API only", vpcId);
ec2Service.revokeSecurityGroupEgress(REGION, group.getGroupId(), List.of(permission("-1", null)));
ec2Service.authorizeSecurityGroupEgress(REGION, group.getGroupId(),
List.of(permission("tcp", RestAssured.port)));
ecsService.createCluster(cluster, REGION);
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage(TestImages.PYTHON_ALPINE);
app.setEntryPoint(List.of("python3", "-u", "-c"));
app.setCommand(List.of(TASK_SCRIPT));
// The test listener is on a random port, unlike the base URL AWS_ENDPOINT_URL is built from.
app.setEnvironment(List.of(
new KeyValuePair("FLOCI_URL", "http://host.docker.internal:" + RestAssured.port),
new KeyValuePair("DENIED_PORT", String.valueOf(CREDENTIALS_PORT))));
TaskDefinition taskDef = ecsService.registerTaskDefinition("ecs-protected-" + suffix, List.of(app),
NetworkMode.awsvpc, null, null, "arn:aws:iam::000000000000:role/" + roleName, null, null,
REGION);
taskArn = ecsService.runTask(cluster, taskDef.getTaskDefinitionArn(), 1, LaunchType.FARGATE,
null, null, List.of(), awsvpcNetwork(group.getGroupId()), REGION).getFirst().getTaskArn();
String launched = taskArn;
EcsTask described = awaitLastStatus(
() -> ecsService.describeTasks(cluster, List.of(launched), REGION).getFirst(),
EcsTask::getLastStatus, Duration.ofMinutes(2), "RUNNING", "STOPPED");
assertEquals("RUNNING", described.getLastStatus(), "the task must start: " + described.getStoppedReason());
String dockerId = described.getContainers().getFirst().getDockerId();
String helper = dockerClient.inspectContainerCmd(dockerId).exec().getHostConfig().getNetworkMode()
.substring("container:".length());
String logs = await("the task's probe of the denied port").atMost(Duration.ofSeconds(90))
.pollInterval(Duration.ofMillis(500))
.until(() -> logs(dockerId), output -> output.contains("DENIED_PORT "));
assertTrue(logs.contains("CREDENTIALS ASIA"), logs);
assertTrue(logs.contains("IDENTITY arn:aws:sts::000000000000:assumed-role/" + roleName + "/"), logs);
assertTrue(logs.contains("DENIED_PORT blocked"), logs);
ecsService.stopTask(cluster, taskArn, "protected task role test", REGION);
taskArn = null;
assertThrows(NotFoundException.class, () -> dockerClient.inspectContainerCmd(helper).exec(),
"a stopped task's protected helper, which held its link-local address, must be removed");
} finally {
if (taskArn != null) {
ecsService.stopTask(cluster, taskArn, "test teardown", REGION);
}
credentialsProxy.stopManagedContainers();
try {
dockerClient.removeNetworkCmd(networkId).exec();
} catch (RuntimeException e) {
LOG.warnv("Could not remove test network {0}: {1}", NETWORK, e.getMessage());
}
}
}
private String ensureNetwork() {
List<Network> existing = dockerClient.listNetworksCmd().withNameFilter(NETWORK).exec().stream()
.filter(network -> NETWORK.equals(network.getName())).toList();
return existing.isEmpty()
? dockerClient.createNetworkCmd().withName(NETWORK).exec().getId()
: existing.getFirst().getId();
}
private String logs(String containerId) throws InterruptedException {
StringBuilder out = new StringBuilder();
dockerClient.logContainerCmd(containerId).withStdOut(true).withStdErr(true)
.exec(new ResultCallback.Adapter<Frame>() {
@Override
public void onNext(Frame frame) {
out.append(new String(frame.getPayload(), StandardCharsets.UTF_8));
}
}).awaitCompletion(10, TimeUnit.SECONDS);
return out.toString();
}
private static NetworkConfiguration awsvpcNetwork(String groupId) {
AwsVpcConfiguration awsvpc = new AwsVpcConfiguration();
awsvpc.setSubnets(List.of(SUBNET));
awsvpc.setSecurityGroups(List.of(groupId));
NetworkConfiguration networkConfiguration = new NetworkConfiguration();
networkConfiguration.setAwsvpcConfiguration(awsvpc);
return networkConfiguration;
}
private static IpPermission permission(String protocol, Integer port) {
IpPermission permission = new IpPermission();
permission.setIpProtocol(protocol);
if (port != null) {
permission.setFromPort(port);
permission.setToPort(port);
}
IpRange anywhere = new IpRange();
anywhere.setCidrIp("0.0.0.0/0");
permission.getIpRanges().add(anywhere);
return permission;
}
private static int freePort() {
try {
return FreePorts.anyInterfacePort();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
@@ -0,0 +1,63 @@
package io.floci.aws.services.ecs.container;
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.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 java.util.List;
/** The awsvpc task, containers and task definition the {@link EcsContainerManager} network tests launch. */
final class AwsvpcTaskFixtures {
static final String TASK_ARN = "arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123";
private AwsvpcTaskFixtures() {
}
/** Task {@code abc123} in {@code subnet-1} behind {@code sg-1}, before it has an ENI. */
static EcsTask awsvpcTaskWithoutEni() {
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);
return task;
}
/** {@link #awsvpcTaskWithoutEni()} as attachTaskNetwork leaves it for its containers: ENI {@code eni-1}. */
static EcsTask awsvpcTask() {
EcsTask task = awsvpcTaskWithoutEni();
task.setNetworkInterfaceId("eni-1");
task.setPrivateIpAddress("10.0.0.10");
return task;
}
/** Container {@code name} running {@code name:latest}, mapping TCP {@code port} unless it is 0. */
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;
}
/** Revision 1 of an awsvpc task definition of {@code containers}, with {@code taskRoleArn} or none when null. */
static TaskDefinition taskDef(String taskRoleArn, ContainerDefinition... containers) {
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("awsvpc-family");
taskDef.setRevision(1);
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setTaskRoleArn(taskRoleArn);
taskDef.setContainerDefinitions(List.of(containers));
return taskDef;
}
}
@@ -0,0 +1,244 @@
package io.floci.aws.services.ecs.container;
import com.github.dockerjava.api.DockerClient;
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.SecurityGroup;
import io.floci.aws.services.ecr.registry.EcrRegistryManager;
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.List;
import java.util.Map;
import java.util.Optional;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.TASK_ARN;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.awsvpcTask;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.container;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.taskDef;
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.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.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;
/**
* Task-role credentials for an awsvpc task under security-group enforcement: its containers share the
* protected helper's namespace, so the helper holds the task's one link-local address, and that address
* is handed on only once the helper is confirmed gone.
*/
class EcsContainerManagerProtectedTaskRoleTest {
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 EmulatorConfig config;
private SecurityGroupFirewallManager firewallManager;
private EcsTaskRoleCredentials taskRoleCredentials;
private EcsCredentialsProxy credentialsProxy;
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()));
when(lifecycleManager.getDockerClient()).thenReturn(mock(DockerClient.class, RETURNS_DEEP_STUBS));
config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().taskRoleCredentials().enabled()).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 ec2Service = mock(Ec2Service.class);
NetworkInterface eni = new NetworkInterface();
eni.setNetworkInterfaceId("eni-1");
eni.setVpcId("vpc-1");
eni.setPrivateIpAddress("10.0.0.10");
eni.setGroups(List.of(new GroupIdentifier("sg-1", "default")));
when(ec2Service.describeNetworkInterfaces(eq("us-east-1"), eq(List.of("eni-1")), anyMap(), eq(0), isNull()))
.thenReturn(new NetworkInterfaceListResult(List.of(eni), null));
SecurityGroup group = new SecurityGroup();
group.setGroupId("sg-1");
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any())).thenReturn(List.of(group));
firewallManager = mock(SecurityGroupFirewallManager.class);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(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));
credentialsProxy = mock(EcsCredentialsProxy.class);
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, credentialsProxy, linkLocalAddresses);
}
@Test
void theProtectedHelperHoldsTheTasksOneCredentialAddress() {
manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 0), container("sidecar", 0)),
List.of(), "us-east-1");
verify(credentialsProxy).ensureProxyOn(NETWORK);
verify(firewallManager).createNamespace(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 aProtectedTaskWithNoRoleGivesItsHelperNoAddress() {
manager.startTask(awsvpcTask(), taskDef(null, container("app", 0)), List.of(), "us-east-1");
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(),
eq(List.of()));
verify(taskRoleCredentials, never()).issue(any(), any(), any(), any());
}
@Test
void aLaunchThatFailsBeforeTheNamespaceIsNeededStartsNoHelper() {
when(lifecycleManager.resolveImageForLaunch(any(), any(), any()))
.thenThrow(new IllegalStateException("pull failed"));
assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(),
taskDef(ROLE_ARN, container("app", 0)), List.of(), "us-east-1"));
verify(firewallManager, never()).createNamespace(any(), any(), any(), any(), any(), any(), any(), any(), any());
verify(taskRoleCredentials).revoke(TASK_ARN);
}
@Test
void stoppingRemovesTheHelperByNameBeforeItsAddressIsFreed() {
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 0)),
List.of(), "us-east-1");
manager.stopTaskAndCollectExitCodes(handle);
verify(firewallManager).removeProtectedNamespaceStrict("abc123");
verify(firewallManager).unregister("eni-1");
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, OTHER_TASK),
"the stopped task's address is free again");
}
@Test
void aHelperDockerKeepsIsRetriedBeforeItsAddressIsFreed() {
doThrow(new IllegalStateException("helper busy")).doNothing()
.when(firewallManager).removeProtectedNamespaceStrict("abc123");
EcsTaskHandle handle = manager.startTask(awsvpcTask(), taskDef(ROLE_ARN, container("app", 0)),
List.of(), "us-east-1");
assertThrows(IllegalStateException.class, () -> manager.stopTaskAndCollectExitCodes(handle));
assertTrue(handle.isNamespaceHelperPending(), "the handle keeps the helper's removal to retry");
verify(firewallManager, never()).unregister(anyString());
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 aNamespaceThatCannotBeBuiltFreesItsAddressOnceTheHelperIsGone() {
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("cannot prepare the protected namespace"));
assertThrows(IllegalStateException.class, () -> manager.startTask(awsvpcTask(),
taskDef(ROLE_ARN, container("app", 0)), 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).removeProtectedNamespaceStrict("abc123");
verify(taskRoleCredentials).revoke(TASK_ARN);
assertEquals("169.254.170.1", linkLocalAddresses.allocate(NETWORK, OTHER_TASK));
}
@Test
void aHelperAFailedStartLeftBehindKeepsItsAddressAndItsCleanup() {
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("inspect failed after the helper started"));
doThrow(new IllegalStateException("helper busy")).when(firewallManager).removeProtectedNamespaceStrict("abc123");
EcsTaskLaunchException failed = assertThrows(EcsTaskLaunchException.class, () -> manager.startTask(
awsvpcTask(), taskDef(ROLE_ARN, container("app", 0)), 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 aContainerThatCannotStartLeavesTheAddressWithAHelperDockerKeeps() {
when(lifecycleManager.createAndStartEphemeral(any(), any()))
.thenThrow(new IllegalStateException("container failed to start"));
doThrow(new IllegalStateException("helper busy")).when(firewallManager).removeProtectedNamespaceStrict("abc123");
EcsTaskLaunchException failed = assertThrows(EcsTaskLaunchException.class, () -> manager.startTask(
awsvpcTask(), taskDef(ROLE_ARN, container("app", 0)), 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 unregistered helper may still hold 169.254.170.1");
}
}
@@ -18,14 +18,11 @@ import io.floci.aws.services.ec2.model.GroupIdentifier;
import io.floci.aws.services.ec2.model.NetworkInterface;
import io.floci.aws.services.ec2.model.SecurityGroup;
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;
@@ -37,6 +34,9 @@ import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.awsvpcTaskWithoutEni;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.container;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.taskDef;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -107,7 +107,7 @@ class EcsContainerManagerSecurityGroupTest {
void awsvpcTaskWithFirewallJoinsHelperNamespaceAndSkipsHostPorts() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any()))
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
@@ -123,7 +123,7 @@ class EcsContainerManagerSecurityGroupTest {
when(ec2Service.describeSecurityGroups(any(), eq(List.of("sg-1")), any(), any()))
.thenReturn(List.of(sg));
EcsTaskHandle handle = manager.startTask(awsvpcTask(), awsvpcTaskDef(List.of(new PortMapping(80, 80, "tcp"))),
EcsTaskHandle handle = manager.startTask(awsvpcTaskWithoutEni(), taskDef(null, container("app", 80)),
List.of(), "us-east-1");
verify(builder).withNetworkMode("container:helper-id");
@@ -145,7 +145,7 @@ class EcsContainerManagerSecurityGroupTest {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(false);
manager.startTask(awsvpcTask(), awsvpcTaskDef(List.of(new PortMapping(80, 80, "tcp"))),
manager.startTask(awsvpcTaskWithoutEni(), taskDef(null, container("app", 80)),
List.of(), "us-east-1");
verify(builder, never()).withNetworkMode(anyString());
@@ -158,7 +158,7 @@ class EcsContainerManagerSecurityGroupTest {
void stopTaskUnregistersEniAndReleasingTheTaskNetworkDeletesIt() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any()))
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
@@ -176,8 +176,8 @@ class EcsContainerManagerSecurityGroupTest {
DockerClient stopClient = mock(DockerClient.class, RETURNS_DEEP_STUBS);
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient, dockerClient, stopClient);
EcsTask task = awsvpcTask();
EcsTaskHandle handle = manager.startTask(task, awsvpcTaskDef(List.of()),
EcsTask task = awsvpcTaskWithoutEni();
EcsTaskHandle handle = manager.startTask(task, taskDef(null, container("app", 0)),
List.of(), "us-east-1");
manager.stopTaskAndCollectExitCodes(handle);
@@ -194,7 +194,7 @@ class EcsContainerManagerSecurityGroupTest {
void firelensRouterAndAppBothJoinTheHelperNamespace() {
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any()))
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
@@ -237,38 +237,14 @@ class EcsContainerManagerSecurityGroupTest {
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(app, router));
manager.startTask(awsvpcTask(), taskDef, List.of(), "us-east-1");
manager.startTask(awsvpcTaskWithoutEni(), taskDef, List.of(), "us-east-1");
verify(builder, times(2)).withNetworkMode("container:helper-id");
verify(builder, times(2)).withLabels(Map.of("io.floci.security-group.workload", "true"));
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any());
verify(firewallManager).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any());
verify(lifecycleManager).create(any(), any());
verify(lifecycleManager).startCreated(eq("router-id"), any());
verify(lifecycleManager).createAndStartEphemeral(any(), any());
}
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("arn:aws:ecs:us-east-1:000000000000:task/test-cluster/abc123");
task.setNetworkConfiguration(network);
return task;
}
private static TaskDefinition awsvpcTaskDef(List<PortMapping> ports) {
ContainerDefinition app = new ContainerDefinition();
app.setName("app");
app.setImage("app:latest");
app.setPortMappings(ports);
TaskDefinition taskDef = new TaskDefinition();
taskDef.setFamily("test-family");
taskDef.setNetworkMode(NetworkMode.awsvpc);
taskDef.setContainerDefinitions(List.of(app));
return taskDef;
}
}
@@ -20,14 +20,10 @@ 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;
@@ -42,6 +38,10 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.TASK_ARN;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.awsvpcTask;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.container;
import static io.floci.aws.services.ecs.container.AwsvpcTaskFixtures.taskDef;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -69,7 +69,6 @@ import static org.mockito.Mockito.when;
*/
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";
@@ -148,7 +147,7 @@ class EcsContainerManagerSharedTaskNetworkTest {
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()).createNamespace(any(), 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());
@@ -331,7 +330,7 @@ class EcsContainerManagerSharedTaskNetworkTest {
@Test
void enforcementGivesTheTaskItsProtectedNamespaceInstead() {
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any()))
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any()))
.thenThrow(new IllegalStateException("stop once the protected path is taken"));
NetworkInterface eni = new NetworkInterface();
eni.setNetworkInterfaceId("eni-1");
@@ -342,7 +341,7 @@ class EcsContainerManagerSharedTaskNetworkTest {
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).createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any());
verify(firewallManager, never()).createSharedNamespace(any(), any(), any(), any(), any(), any(), any(), any(),
any());
}
@@ -358,39 +357,4 @@ class EcsContainerManagerSharedTaskNetworkTest {
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;
}
}
@@ -140,7 +140,7 @@ class EcsContainerManagerTaskAddressTest {
@Test
void securityGroupProtectedTaskKeepsItsOwnNamespace() {
when(firewallManager.enabled()).thenReturn(true);
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any()))
when(firewallManager.createNamespace(eq("ecs"), eq("abc123"), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(new SecurityGroupFirewallManager.Namespace("helper-id", "10.0.0.5"));
NetworkInterface eni = new NetworkInterface();
eni.setNetworkInterfaceId("eni-1");