fix(ecs): scope service tasks by owning service, not by caller-supplied group (#2731)

RunTask/StartTask let a caller set any group, so matching it against a service's
name or ARN let an unrelated task be counted, stopped or registered as
service-owned. Tasks now carry a reconciler-stamped owningServiceArn.

Fixes #2716

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-08-29 23:21:13 -04:00
1 parent 47e064786f
commit c6b9e4c34e
3 files changed
+339 -32

No files matched your search

@@ -374,7 +374,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
if (cpu == 4096) return memory >= 8192 && memory <= 30720 && memory % 1024 == 0;
if (cpu == 8192) return memory >= 16384 && memory <= 61440 && memory % 4096 == 0;
if (cpu == 16384) return memory >= 32768 && memory <= 122880 && memory % 8192 == 0;
return false;
}
@@ -477,7 +477,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
EcsCluster cluster = resolveClusterOrDefault(clusterRef, region);
TaskDefinition taskDef = resolveTaskDefinitionOrThrow(taskDefinitionRef, region);
return launchTasks(cluster, taskDef, count, launchType, group, startedBy, null,
containerOverrides, networkConfiguration, region);
containerOverrides, networkConfiguration, null, region);
}
public List<EcsTask> startTask(String clusterRef, List<String> containerInstanceRefs,
@@ -488,17 +488,25 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
for (String instanceRef : containerInstanceRefs) {
ContainerInstance instance = resolveContainerInstanceOrThrow(cluster.getClusterArn(), instanceRef);
List<EcsTask> launched = launchTasks(cluster, taskDef, 1, LaunchType.EC2,
group, startedBy, instance.getContainerInstanceArn(), null, null, region);
group, startedBy, instance.getContainerInstanceArn(), null, null, null, region);
result.addAll(launched);
}
return result;
}
/**
* @param owningServiceArn ARN of the service this task is being launched for, or {@code null}
* for a caller-driven {@code RunTask}/{@code StartTask}. Only the
* service reconciler supplies it; it is what later identifies the
* task as service-owned, since the caller-supplied {@code group}
* cannot be trusted for that.
*/
private List<EcsTask> launchTasks(EcsCluster cluster, TaskDefinition taskDef, int count,
LaunchType launchType, String group, String startedBy,
String containerInstanceArn,
List<ContainerOverride> containerOverrides,
NetworkConfiguration networkConfiguration, String region) {
NetworkConfiguration networkConfiguration,
String owningServiceArn, String region) {
// Fail loudly instead of silently launching zero containers and leaving
// a task that looks RUNNING with nothing behind it.
if (taskDef.getContainerDefinitions() == null || taskDef.getContainerDefinitions().isEmpty()) {
@@ -520,6 +528,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
task.setLaunchType(launchType != null ? launchType : LaunchType.FARGATE);
task.setGroup(group);
task.setStartedBy(startedBy);
task.setOwningServiceArn(owningServiceArn);
task.setLastStatus(TaskStatus.PENDING.name());
task.setDesiredStatus(TaskStatus.RUNNING.name());
task.setCpu(taskDef.getCpu());
@@ -537,7 +546,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
taskHandles.put(taskArn, handle);
cluster.setRunningTasksCount(cluster.getRunningTasksCount() + 1);
LOG.infov("Started ECS task (docker): {0}", taskArn);
registerTaskWithLoadBalancers(task, cluster, group, region);
registerTaskWithLoadBalancers(task, cluster, region);
} catch (Exception e) {
LOG.errorv("Failed to start ECS task {0}: {1}", taskArn, e.getMessage());
task.setLastStatus(TaskStatus.STOPPED.name());
@@ -565,6 +574,19 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
return launched;
}
/**
* Launches one task on behalf of a service, stamping it with the service's ARN so later
* reconciliation can recognize it as service-owned without trusting the caller-settable
* {@code group}. This is the only path that sets {@code owningServiceArn}.
*/
private EcsTask launchServiceTask(EcsCluster cluster, EcsServiceModel svc, LaunchType launchType,
String containerInstanceArn, String region) {
TaskDefinition taskDef = resolveTaskDefinitionOrThrow(svc.getTaskDefinition(), region);
return launchTasks(cluster, taskDef, 1, launchType, svc.getServiceName(), "ecs-svc",
containerInstanceArn, null, svc.getNetworkConfiguration(),
svc.getServiceArn(), region).getFirst();
}
public EcsTask stopTask(String clusterRef, String taskRef, String reason, String region) {
EcsTask task = resolveTaskOrThrow(taskRef, region);
if (TaskStatus.STOPPED.name().equals(task.getLastStatus())) {
@@ -610,28 +632,41 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
}
/** Registers a freshly-started task's containers as ELBv2 targets if its service is load-balanced. */
private void registerTaskWithLoadBalancers(EcsTask task, EcsCluster cluster, String group, String region) {
if (group == null) {
return;
}
EcsServiceModel svc = services.get(serviceKey(region, cluster.getClusterName(), group));
private void registerTaskWithLoadBalancers(EcsTask task, EcsCluster cluster, String region) {
EcsServiceModel svc = owningService(task, cluster);
if (svc != null && !svc.getLoadBalancers().isEmpty()) {
lbRegistrar.registerTask(task, svc, region);
}
}
/**
* Resolves the service that actually launched {@code task}, or {@code null} for a
* caller-driven task. Keyed off the reconciler-stamped {@code owningServiceArn} rather than
* the caller-supplied {@code group}, so a {@code RunTask} cannot name an unrelated service
* and have its containers registered into that service's target groups.
*/
private EcsServiceModel owningService(EcsTask task, EcsCluster cluster) {
if (task.getOwningServiceArn() == null) {
return null;
}
return services.values().stream()
.filter(svc -> ownedBy(task, svc, cluster))
.findFirst()
.orElse(null);
}
/** Deregisters a stopping task's containers from any ELBv2 target groups its service declared. */
private void deregisterTaskFromLoadBalancers(EcsTask task, String region) {
// Gated on dockerMode for symmetry with the register hook (inside launchTasks'
// dockerMode branch): mock-mode tasks have no containers and never registered.
if (!dockerMode || task.getGroup() == null) {
if (!dockerMode || task.getOwningServiceArn() == null) {
return;
}
EcsCluster cluster = resolveClusterByArn(task.getClusterArn());
if (cluster == null) {
return;
}
EcsServiceModel svc = services.get(serviceKey(region, cluster.getClusterName(), task.getGroup()));
EcsServiceModel svc = owningService(task, cluster);
if (svc != null && !svc.getLoadBalancers().isEmpty()) {
lbRegistrar.deregisterTask(task, svc, region);
}
@@ -650,15 +685,24 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
public List<String> listTasks(String clusterRef, String family, String desiredStatus,
String serviceName, String region) {
String clusterArn = clusterRef != null
? resolveClusterOrDefault(clusterRef, region).getClusterArn()
// Resolving the default cluster also creates and persists it, and ListTasks is a read:
// when no cluster is named, look the default up without materializing it. A service
// filter then simply matches nothing if that cluster does not exist yet.
EcsCluster cluster = clusterRef != null
? resolveClusterOrDefault(clusterRef, region)
: (serviceName != null ? clusters.get(clusterKey(region, DEFAULT_CLUSTER)) : null);
String clusterArn = clusterRef != null ? cluster.getClusterArn() : null;
// A serviceName filter selects the service's own tasks, so it resolves through the
// reconciler-stamped ownership rather than the caller-supplied group.
EcsServiceModel svc = serviceName != null && cluster != null
? services.get(serviceKey(region, cluster.getClusterName(), serviceName))
: null;
return tasks.values().stream()
.filter(t -> clusterArn == null || t.getClusterArn().equals(clusterArn))
.filter(t -> family == null || t.getTaskDefinitionArn().contains("/" + family + ":"))
.filter(t -> desiredStatus == null || desiredStatus.equals(t.getDesiredStatus()))
.filter(t -> serviceName == null || serviceName.equals(t.getGroup()))
.filter(t -> serviceName == null || (svc != null && ownedBy(t, svc, cluster)))
.map(EcsTask::getTaskArn)
.toList();
}
@@ -853,9 +897,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
// Stop tasks before removing the service from the map, so the per-task
// ELBv2 deregistration hook can still resolve the service's loadBalancers.
tasks.values().stream()
.filter(t -> t.getClusterArn().equals(cluster.getClusterArn()))
.filter(t -> svc.getServiceArn().equals(t.getGroup())
|| svc.getServiceName().equals(t.getGroup()))
.filter(t -> ownedBy(t, svc, cluster))
.filter(t -> !TaskStatus.STOPPED.name().equals(t.getLastStatus()))
.forEach(t -> {
try {
@@ -1589,9 +1631,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
// slot — otherwise a stranded STOPPING task would get a duplicate next to it.
// RUNNING tasks are preferred as the instance's daemon when there are several.
List<EcsTask> liveTasks = tasks.values().stream()
.filter(t -> t.getClusterArn().endsWith(":cluster/" + clusterName))
.filter(t -> svc.getServiceArn().equals(t.getGroup())
|| svc.getServiceName().equals(t.getGroup()))
.filter(t -> ownedBy(t, svc, cluster))
.filter(t -> !TaskStatus.STOPPED.name().equals(t.getLastStatus()))
.sorted(Comparator.comparingInt(t -> daemonTaskRank(t.getLastStatus())))
.toList();
@@ -1623,10 +1663,8 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
continue;
}
try {
TaskDefinition taskDef = resolveTaskDefinitionOrThrow(svc.getTaskDefinition(), region);
EcsTask launched = launchTasks(cluster, taskDef, 1, LaunchType.EC2,
svc.getServiceName(), "ecs-svc", ci.getContainerInstanceArn(), null,
svc.getNetworkConfiguration(), region).getFirst();
EcsTask launched = launchServiceTask(cluster, svc, LaunchType.EC2,
ci.getContainerInstanceArn(), region);
// A Docker start failure comes back already STOPPED: the slot stays uncovered and
// the next tick retries, and it must not count towards runningCount.
if (!TaskStatus.STOPPED.name().equals(launched.getLastStatus())) {
@@ -1689,6 +1727,19 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
}
}
/**
* Whether a task is genuinely owned by {@code svc}. Both halves matter: {@code
* owningServiceArn} is stamped only by {@link #launchServiceTask} and so cannot be forged
* through a {@code RunTask} {@code group}, and the cluster is compared by full ARN rather
* than by a name suffix, which would otherwise conflate same-named clusters across regions
* or accounts.
*/
private static boolean ownedBy(EcsTask task, EcsServiceModel svc, EcsCluster cluster) {
return svc.getServiceArn() != null
&& svc.getServiceArn().equals(task.getOwningServiceArn())
&& cluster.getClusterArn().equals(task.getClusterArn());
}
private void reconcileService(String key, EcsServiceModel svc) {
if (!"ACTIVE".equals(svc.getStatus())) {
return;
@@ -1702,10 +1753,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
return;
}
EcsCluster cluster = resolveClusterOrDefault(clusterName, region);
List<EcsTask> runningTasks = tasks.values().stream()
.filter(t -> t.getClusterArn().endsWith(":cluster/" + clusterName))
.filter(t -> svc.getServiceArn().equals(t.getGroup())
|| svc.getServiceName().equals(t.getGroup()))
.filter(t -> ownedBy(t, svc, cluster))
.filter(t -> TaskStatus.RUNNING.name().equals(t.getLastStatus()))
.toList();
long running = runningTasks.size();
@@ -1726,11 +1776,9 @@ public class EcsService implements ContainerTeardown, ResourceProvider {
int toStart = svc.getDesiredCount() - (int) current;
for (int i = 0; i < toStart; i++) {
try {
List<EcsTask> launched = runTask(clusterName, svc.getTaskDefinition(), 1,
svc.getLaunchType(), svc.getServiceName(), "ecs-svc", null,
svc.getNetworkConfiguration(), region);
EcsTask launched = launchServiceTask(cluster, svc, svc.getLaunchType(), null, region);
LOG.infov("Service reconciler started task {0} for service {1}",
launched.getFirst().getTaskArn(), svc.getServiceName());
launched.getTaskArn(), svc.getServiceName());
} catch (Exception e) {
LOG.warnv("Service reconciler failed to start task for {0}: {1}",
svc.getServiceName(), e.getMessage());
@@ -14,6 +14,13 @@ public class EcsTask {
private String clusterArn;
private String taskDefinitionArn;
private String group;
/**
* ARN of the service that launched this task, assigned by the service reconciler at launch
* time. Internal to the emulator: it is never read from a {@code RunTask}/{@code StartTask}
* request and never serialized onto the wire, unlike {@link #group}, which is a free-form
* caller-supplied label and therefore cannot be trusted to establish ownership.
*/
private String owningServiceArn;
private LaunchType launchType;
private String lastStatus;
private String desiredStatus;
@@ -43,6 +50,9 @@ public class EcsTask {
public String getGroup() { return group; }
public void setGroup(String group) { this.group = group; }
public String getOwningServiceArn() { return owningServiceArn; }
public void setOwningServiceArn(String owningServiceArn) { this.owningServiceArn = owningServiceArn; }
public LaunchType getLaunchType() { return launchType; }
public void setLaunchType(LaunchType launchType) { this.launchType = launchType; }
@@ -0,0 +1,249 @@
package io.github.hectorvent.floci.services.ecs;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ecs.container.EcsContainerManager;
import io.github.hectorvent.floci.services.ecs.model.ContainerDefinition;
import io.github.hectorvent.floci.services.ecs.model.ContainerInstance;
import io.github.hectorvent.floci.services.ecs.model.EcsTask;
import io.github.hectorvent.floci.services.ecs.model.LaunchType;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* A task's service ownership comes from the reconciler-stamped {@code owningServiceArn}, never
* from the caller-supplied {@code group}: {@code RunTask}/{@code StartTask} let a caller pass any
* group they like, so treating it as an ownership claim let an unrelated task be counted toward a
* service's {@code runningCount} and stopped as a duplicate or a scale-in. Cluster scoping is
* likewise by full ARN, not by a {@code :cluster/<name>} suffix that same-named clusters in other
* regions or accounts also match.
*/
class EcsServiceTaskOwnershipTest {
private static final String REGION = "us-east-1";
private static final String OTHER_REGION = "us-west-2";
@Test
void spoofedGroupIsNotCountedTowardTheServiceAndIsNotStopped() {
EcsService service = newMockModeService();
service.createCluster("own-cluster", REGION);
registerTaskDef(service);
service.createService("own-cluster", "web", "own-fam", 1, LaunchType.FARGATE,
List.of(), null, REGION);
EcsTask intruder = service.runTask("own-cluster", "own-fam", 1, LaunchType.FARGATE,
"web", "me", null, null, REGION).getFirst();
// Two ticks: the first launches the service's own task, the second publishes the
// resulting runningCount (the reconciler counts before it launches).
service.reconcileServices();
service.reconcileServices();
assertEquals(2, allTasks(service).size(),
"the service launches its own task rather than adopting the impostor as its one replica");
List<EcsTask> owned = ownedTasks(service, "own-cluster", "web");
assertEquals(1, owned.size(), "exactly one task is genuinely service-owned");
assertNotEquals(intruder.getTaskArn(), owned.getFirst().getTaskArn(),
"the service-owned task is the one the reconciler launched, not the impostor");
assertEquals(1, service.describeServices("own-cluster", List.of("web"), REGION)
.getFirst().getRunningCount(),
"runningCount counts only genuinely service-owned tasks");
assertEquals("RUNNING", reload(service, intruder).getLastStatus(),
"the unrelated task is left alone, not stopped as a duplicate");
}
@Test
void scaleInDoesNotStopATaskThatMerelyNamesTheServiceAsItsGroup() {
EcsService service = newMockModeService();
service.createCluster("scale-cluster", REGION);
registerTaskDef(service);
service.createService("scale-cluster", "api", "own-fam", 1, LaunchType.FARGATE,
List.of(), null, REGION);
service.reconcileServices();
EcsTask intruder = service.runTask("scale-cluster", "own-fam", 1, LaunchType.FARGATE,
"api", "me", null, null, REGION).getFirst();
service.updateService("scale-cluster", "api", null, 0, null, REGION);
service.reconcileServices();
assertEquals(0, ownedTasks(service, "scale-cluster", "api").size(),
"the service drains its own task down to the new desired count");
assertEquals("RUNNING", reload(service, intruder).getLastStatus(),
"scale-in must not reach a task the service never launched");
}
@Test
void daemonSchedulingIgnoresASpoofedGroupWhenCoveringInstances() {
EcsService service = newMockModeService();
service.createCluster("daemon-own", REGION);
ContainerInstance instance = service.registerContainerInstance("daemon-own", null, List.of(), REGION);
registerTaskDef(service);
service.createService("daemon-own", "agent", "own-fam", 1, LaunchType.EC2,
List.of(), null, null, "DAEMON", null, null, REGION);
EcsTask intruder = service.startTask("daemon-own", List.of(instance.getContainerInstanceArn()),
"own-fam", "agent", "me", REGION).getFirst();
service.reconcileServices();
assertEquals(2, allTasks(service).size(),
"the daemon still places its own task on the instance the impostor sits on");
List<EcsTask> owned = ownedTasks(service, "daemon-own", "agent");
assertEquals(1, owned.size(), "the impostor does not count as covering the instance");
assertNotEquals(intruder.getTaskArn(), owned.getFirst().getTaskArn(),
"the covering task is the reconciler's own, not the impostor");
assertEquals("RUNNING", reload(service, intruder).getLastStatus(),
"nor is it stopped as a duplicate daemon task");
}
@Test
void deletingAServiceDoesNotStopTasksItNeverLaunched() {
EcsService service = newMockModeService();
service.createCluster("delete-cluster", REGION);
registerTaskDef(service);
service.createService("delete-cluster", "worker", "own-fam", 1, LaunchType.FARGATE,
List.of(), null, REGION);
service.reconcileServices();
EcsTask intruder = service.runTask("delete-cluster", "own-fam", 1, LaunchType.FARGATE,
"worker", "me", null, null, REGION).getFirst();
service.deleteService("delete-cluster", "worker", true, REGION);
assertEquals("RUNNING", reload(service, intruder).getLastStatus(),
"service teardown stops only the service's own tasks");
}
@Test
void listTasksByServiceNameReturnsOnlyTasksTheServiceLaunched() {
EcsService service = newMockModeService();
service.createCluster("list-cluster", REGION);
registerTaskDef(service);
service.createService("list-cluster", "svc", "own-fam", 1, LaunchType.FARGATE,
List.of(), null, REGION);
service.reconcileServices();
EcsTask intruder = service.runTask("list-cluster", "own-fam", 1, LaunchType.FARGATE,
"svc", "me", null, null, REGION).getFirst();
List<String> listed = service.listTasks("list-cluster", null, null, "svc", REGION);
assertEquals(1, listed.size(), "only the service's own task is listed");
assertTrue(listed.stream().noneMatch(arn -> arn.equals(intruder.getTaskArn())),
"a task that merely names the service as its group is not service-owned");
}
@Test
void aSameNamedClusterInAnotherRegionIsNotSweptIntoReconciliation() {
EcsService service = newMockModeService();
service.createCluster("shared-name", REGION);
service.createCluster("shared-name", OTHER_REGION);
registerTaskDef(service);
registerTaskDef(service, OTHER_REGION);
service.createService("shared-name", "svc", "own-fam", 1, LaunchType.FARGATE,
List.of(), null, REGION);
service.createService("shared-name", "svc", "own-fam", 1, LaunchType.FARGATE,
List.of(), null, OTHER_REGION);
service.reconcileServices();
service.reconcileServices();
// Each region's service owns exactly one task and neither reaches across into the
// other's identically-named cluster: a suffix match on ":cluster/shared-name" would let
// each service see two "running" tasks and stop the other region's as a scale-in.
assertEquals(2, allTasks(service).size(),
"both same-named clusters keep their own task");
assertTrue(allTasks(service).stream().map(EcsTask::getClusterArn).distinct().count() == 2,
"the two surviving tasks live in different cluster ARNs, one per region");
assertEquals(1, ownedTasks(service, "shared-name", "svc").size(),
"the us-east-1 service keeps exactly one task of its own");
}
@Test
void listTasksByServiceNameWithoutAClusterDoesNotMaterializeTheDefaultCluster() {
EcsService service = newMockModeService();
List<String> listed = service.listTasks(null, null, null, "ghost-svc", REGION);
assertEquals(List.of(), listed, "no cluster, so no service, so nothing to list");
assertEquals(List.of(), service.listClusters(REGION),
"ListTasks is a read and must not create the default cluster as a side effect");
}
private static List<EcsTask> allTasks(EcsService service) {
return service.describeTasks(null, service.listTasks(null, null, null, null, REGION), REGION).stream()
.filter(t -> "RUNNING".equals(t.getLastStatus()))
.toList();
}
private static List<EcsTask> ownedTasks(EcsService service, String cluster, String serviceName) {
return service.describeTasks(cluster,
service.listTasks(cluster, null, null, serviceName, REGION), REGION).stream()
.filter(t -> "RUNNING".equals(t.getLastStatus()))
.toList();
}
private static EcsTask reload(EcsService service, EcsTask task) {
EcsTask found = service.describeTasks(null, List.of(task.getTaskArn()), REGION).getFirst();
assertNotNull(found);
return found;
}
private static void registerTaskDef(EcsService service) {
registerTaskDef(service, REGION);
}
private static void registerTaskDef(EcsService service, String region) {
ContainerDefinition cd = new ContainerDefinition();
cd.setName("app");
cd.setImage("app:1");
service.registerTaskDefinition("own-fam", List.of(cd), null, null, null, null, null, List.of(), region);
}
private static EcsService newMockModeService() {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().ecs().mock()).thenReturn(true);
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
EcsService service = new EcsService(
new RegionResolver(REGION, "000000000000"),
mock(EcsContainerManager.class),
config,
mock(EcsLoadBalancerRegistrar.class),
new InMemoryStorageFactory());
service.initializeStorage();
return service;
}
private static final class InMemoryStorageFactory extends StorageFactory {
private final Map<String, StorageBackend<String, ?>> stores = new HashMap<>();
private InMemoryStorageFactory() {
super(null, null);
}
@Override
@SuppressWarnings("unchecked")
public <V> AccountAwareStorageBackend<V> create(String serviceName,
String fileName,
TypeReference<Map<String, V>> typeReference) {
return (AccountAwareStorageBackend<V>) stores.computeIfAbsent(fileName,
ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
}
}
}