mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
b3582da1f5
commit
151cb586f9
12 files changed
+750
-132
No files matched your search
@@ -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();
|
||||
|
||||
+267
@@ -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;
|
||||
}
|
||||
}
|
||||
+244
@@ -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");
|
||||
}
|
||||
}
|
||||
+12
-36
@@ -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;
|
||||
}
|
||||
}
|
||||
+7
-43
@@ -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;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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");
|
||||
|
||||
Reference in new issue
Block a user