fix(ecs): give resource-tag conditions the tags of the resource a request names (#8732)

The generated request resources give ECS's cluster, task-definition,
service, capacity-provider, task and container-instance types the
aws:ResourceTag/ and ecs:ResourceTag/ keys, but EcsService answered no
tags, so a condition on an ECS resource's tags saw none. Its storedTags
now reads the resource the ARN names in the request's account, where
every ECS handler reads: a stored one in place under the key its ARN
gives, a record saved before storage was account-aware or before a task
definition's key named its Region included, matched on the whole ARN,
and a task or a container instance from memory. TagResource and
UntagResource changed the resource's map in place without a lock; they
now give it a new map under the service's lock, and the tags fields are
volatile.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-17 08:22:39 -04:00
1 parent 50276fa533
commit 83c64f5d91
11 files changed
+210 -28

No files matched your search

+3 -2
View File
@@ -3201,8 +3201,9 @@ floci populates:
snapshot schedules, event subscriptions and integrations, SSM for its parameters, documents and associations,
EMR for its clusters, CloudFront for every resource it tags, by its ARN, IAM Identity Center for its instances,
permission sets, applications and trusted token issuers, OAM for its sinks and links, RAM for its resource shares,
Payment Cryptography for its keys, Resource Explorer for its indexes and views, and Application Auto Scaling for
its scalable targets. Tag keys differing only in case are one condition key holding every value.
Payment Cryptography for its keys, Resource Explorer for its indexes and views, Application Auto Scaling for its
scalable targets, and ECS for its clusters, task definitions, services, capacity providers, tasks and container
instances. Tag keys differing only in case are one condition key holding every value.
- EC2 resource keys such as a network interface's `ec2:Vpc`, `ec2:Subnet`, `ec2:AvailabilityZone` and
`ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the
key names, an ARN for a key the Service Reference types as one. `resourceKeys` in
@@ -42,9 +42,11 @@ import java.util.Optional;
* and the tags of a cluster, a snapshot, a parameter group, a subnet group, a snapshot copy grant, a snapshot
* schedule, an event subscription or an integration; SSM, for the parameter a legacy ARN names, the document of
* another account an association runs and the tags of a parameter, a document or an association; CloudFront, for the
* key value store a name names and the tags of any resource it tags); looked up lazily by {@code ResourceArnBuilder}
* and {@code IamConditionContextResolver} through {@code Instance<StoredResourceArns>} for the namespace a request or
* an ARN is of, so IAM never depends on that service directly.</p>
* key value store a name names and the tags of any resource it tags; ECS, for the revision a task definition
* reference resolves to, its default cluster and the tags of a cluster, a task definition, a service, a capacity
* provider, a task or a container instance); looked up lazily by {@code ResourceArnBuilder} and
* {@code IamConditionContextResolver} through {@code Instance<StoredResourceArns>} for the namespace a request or an
* ARN is of, so IAM never depends on that service directly.</p>
*
* <p>Each answer is a lookup of what the service holds, asked for by an entry of the generated table ({@code find},
* {@code through}, a default, {@code forwarded}, a type's {@code resourceTagKeys}): never a fact about what an operation acts on, which the table alone
@@ -15,6 +15,7 @@ import io.floci.aws.core.resource.ResourceProvider;
import io.floci.aws.core.resource.SupportedResourceType;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.StorageBackedMap;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.floci.aws.services.cloudwatch.metrics.model.Dimension;
@@ -171,8 +172,10 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// region::clusterName → EcsCluster
private Map<String, EcsCluster> clusters = new ConcurrentHashMap<>();
private AccountAwareStorageBackend<EcsCluster> clustersStore;
// region::family:revision → TaskDefinition (entries persisted before regions were keyed: family:revision)
private Map<String, TaskDefinition> taskDefinitions = new ConcurrentHashMap<>();
private AccountAwareStorageBackend<TaskDefinition> taskDefinitionsStore;
// region::family → latest revision number
private Map<String, Integer> latestRevisions = new ConcurrentHashMap<>();
// taskArn → EcsTask
@@ -257,6 +260,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
private final Map<String, ContainerInstance> containerInstances = new ConcurrentHashMap<>();
// name → CapacityProvider (excludes built-ins FARGATE, FARGATE_SPOT)
private Map<String, CapacityProvider> capacityProviders = new ConcurrentHashMap<>();
private AccountAwareStorageBackend<CapacityProvider> capacityProvidersStore;
// taskSetArn → TaskSet
private final Map<String, TaskSet> taskSets = new ConcurrentHashMap<>();
// Serializes create/update/delete of one service key (region, cluster, name). A fixed set of
@@ -414,17 +418,20 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
if (storageFactory == null) {
return; // keeps non-CDI unit tests working
}
this.clusters = storageBacked("ecs-clusters.json",
this.clustersStore = storageFactory.create("ecs", "ecs-clusters.json",
new TypeReference<Map<String, EcsCluster>>() {});
this.taskDefinitions = storageBacked("ecs-task-definitions.json",
this.clusters = new StorageBackedMap<>(this.clustersStore);
this.taskDefinitionsStore = storageFactory.create("ecs", "ecs-task-definitions.json",
new TypeReference<Map<String, TaskDefinition>>() {});
this.taskDefinitions = new StorageBackedMap<>(this.taskDefinitionsStore);
this.latestRevisions = storageBacked("ecs-latest-revisions.json",
new TypeReference<Map<String, Integer>>() {});
this.servicesStore = storageFactory.create("ecs", "ecs-services.json",
new TypeReference<Map<String, EcsServiceModel>>() {});
this.services = new StorageBackedMap<>(this.servicesStore);
this.capacityProviders = storageBacked("ecs-capacity-providers.json",
this.capacityProvidersStore = storageFactory.create("ecs", "ecs-capacity-providers.json",
new TypeReference<Map<String, CapacityProvider>>() {});
this.capacityProviders = new StorageBackedMap<>(this.capacityProvidersStore);
this.attributes = storageBacked("ecs-attributes.json",
new TypeReference<Map<String, List<Attribute>>>() {});
this.accountSettings = storageBacked("ecs-account-settings.json",
@@ -3572,7 +3579,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
// ── Tags ──────────────────────────────────────────────────────────────────
public void tagResource(String resourceArn, Map<String, String> tags) {
public synchronized void tagResource(String resourceArn, Map<String, String> tags) {
Object resource = findByArn(resourceArn);
if (resource == null) {
throw new AwsException("InvalidParameterException", "Resource not found: " + resourceArn, 400);
@@ -3580,7 +3587,7 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
mergeTagsOnResource(resource, tags);
}
public void untagResource(String resourceArn, List<String> tagKeys) {
public synchronized void untagResource(String resourceArn, List<String> tagKeys) {
Object resource = findByArn(resourceArn);
if (resource == null) {
throw new AwsException("InvalidParameterException", "Resource not found: " + resourceArn, 400);
@@ -3596,6 +3603,63 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
return getTagsFromResource(resource);
}
/**
* The tags of the cluster, task definition, service, capacity provider, task or container instance whose ARN is
* {@code arn}, among the resources of the request's account, where every ECS handler reads: an ARN of another
* account names none of them. Each is read under the key its ARN gives: a stored one in place, one saved before
* storage was account-aware or before a definition's key named its Region included, and matched on the whole
* ARN. Reads only.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, "ecs")) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String account = parsed.accountId();
String resource = parsed.resource();
int slash = resource.indexOf('/');
if (!account.equals(regionResolver.getAccountId()) || slash < 0) {
return Map.of();
}
String region = parsed.region();
String id = resource.substring(slash + 1);
int idSlash = id.indexOf('/');
Optional<Map<String, String>> tags = switch (resource.substring(0, slash)) {
case "cluster" -> readStored(clustersStore, clusters, account, clusterKey(region, id))
.filter(c -> arn.equals(c.getClusterArn())).map(EcsCluster::getTags);
// The key taskDefinitionKey builds from the family and revision the ARN ends in, then the one without the
// Region a definition was saved under before.
case "task-definition" -> readStored(taskDefinitionsStore, taskDefinitions, account, region + "::" + id)
.or(() -> readStored(taskDefinitionsStore, taskDefinitions, account, id))
.filter(td -> arn.equals(td.getTaskDefinitionArn())).map(TaskDefinition::getTags);
case "service" -> idSlash < 0 ? Optional.empty()
: readStored(servicesStore, services, account,
serviceKey(region, id.substring(0, idSlash), id.substring(idSlash + 1)))
.filter(s -> arn.equals(s.getServiceArn())).map(EcsServiceModel::getTags);
case "capacity-provider" -> readStored(capacityProvidersStore, capacityProviders, account, id)
.filter(cp -> arn.equals(cp.getCapacityProviderArn())).map(CapacityProvider::getTags);
case "task" -> Optional.ofNullable(tasks.get(arn)).map(EcsTask::getTags);
// Kept under its cluster's ARN, which the instance's names: the cluster's name, in the same coordinates.
case "container-instance" -> idSlash < 0 ? Optional.empty()
: Optional.ofNullable(containerInstances.get(containerInstanceKey(new AwsArnUtils.Arn(
parsed.partition(), "ecs", region, account, "cluster/" + id.substring(0, idSlash))
.toString(), arn))).map(ContainerInstance::getTags);
default -> Optional.empty();
};
return new LinkedHashMap<>(tags.orElse(Map.of()));
}
/**
* The value under {@code key} in {@code account}, a pre-account-aware one of the default account included, read
* in place; the map's when the service runs without storage.
*/
private static <V> Optional<V> readStored(StorageBackend<String, V> store, Map<String, V> map, String account,
String key) {
return store == null ? Optional.ofNullable(map.get(key))
: AccountAwareStorageBackend.readInAccount(store, account, key);
}
private Object findByArn(String arn) {
for (EcsCluster c : clusters.values()) {
if (arn.equals(c.getClusterArn())) { return c; }
@@ -3618,26 +3682,40 @@ public class EcsService implements ContainerTeardown, ResourceProvider, Resettab
return null;
}
/** Gives the resource a new map, its tags with {@code tags} added, so a reader holds one whole set of tags. */
private void mergeTagsOnResource(Object resource, Map<String, String> tags) {
if (resource instanceof EcsCluster c) { c.getTags().putAll(tags); }
else if (resource instanceof TaskDefinition td) { td.getTags().putAll(tags); }
else if (resource instanceof EcsTask t) { t.getTags().putAll(tags); }
else if (resource instanceof EcsServiceModel s) { s.getTags().putAll(tags); }
else if (resource instanceof ContainerInstance ci) { ci.getTags().putAll(tags); }
else if (resource instanceof CapacityProvider cp) { cp.getTags().putAll(tags); }
Map<String, String> merged = new LinkedHashMap<>(tagsOf(resource));
merged.putAll(tags);
setTagsOnResource(resource, merged);
persistTaggedResource(resource);
}
/** Gives the resource a new map, its tags without {@code tagKeys}, so a reader holds one whole set of tags. */
private void removeTagsFromResource(Object resource, List<String> tagKeys) {
if (resource instanceof EcsCluster c) { tagKeys.forEach(c.getTags()::remove); }
else if (resource instanceof TaskDefinition td) { tagKeys.forEach(td.getTags()::remove); }
else if (resource instanceof EcsTask t) { tagKeys.forEach(t.getTags()::remove); }
else if (resource instanceof EcsServiceModel s) { tagKeys.forEach(s.getTags()::remove); }
else if (resource instanceof ContainerInstance ci) { tagKeys.forEach(ci.getTags()::remove); }
else if (resource instanceof CapacityProvider cp) { tagKeys.forEach(cp.getTags()::remove); }
Map<String, String> kept = new LinkedHashMap<>(tagsOf(resource));
tagKeys.forEach(kept::remove);
setTagsOnResource(resource, kept);
persistTaggedResource(resource);
}
private static void setTagsOnResource(Object resource, Map<String, String> tags) {
switch (resource) {
case EcsCluster c -> c.setTags(tags);
case TaskDefinition td -> td.setTags(tags);
case EcsTask t -> t.setTags(tags);
case EcsServiceModel s -> s.setTags(tags);
case ContainerInstance ci -> ci.setTags(tags);
case CapacityProvider cp -> cp.setTags(tags);
default -> throw new IllegalArgumentException("Not a taggable ECS resource: " + resource);
}
}
/** The resource's tags, none when a stored record holds no map. */
private Map<String, String> tagsOf(Object resource) {
Map<String, String> tags = getTagsFromResource(resource);
return tags == null ? Map.of() : tags;
}
/** Writes back a tag mutation to the owning durable map. Tasks and container instances are
* transient (not persisted), so they need no write-back. */
private void persistTaggedResource(Object resource) {
@@ -19,7 +19,7 @@ public class CapacityProvider {
private String updateStatus;
private String type;
private Map<String, Object> autoScalingGroupProvider;
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
public String getCapacityProviderArn() { return capacityProviderArn; }
public void setCapacityProviderArn(String capacityProviderArn) { this.capacityProviderArn = capacityProviderArn; }
@@ -28,7 +28,7 @@ public class ContainerInstance {
private List<Map<String, Object>> registeredResources;
private List<Map<String, Object>> remainingResources;
private List<Attribute> attributes = new ArrayList<>();
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
public String getContainerInstanceArn() { return containerInstanceArn; }
public void setContainerInstanceArn(String containerInstanceArn) { this.containerInstanceArn = containerInstanceArn; }
@@ -21,7 +21,7 @@ public class EcsCluster {
private List<Map<String, Object>> defaultCapacityProviderStrategy;
private Map<String, Object> configuration;
private Map<String, Object> serviceConnectDefaults;
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
public String getClusterArn() { return clusterArn; }
public void setClusterArn(String clusterArn) { this.clusterArn = clusterArn; }
@@ -38,7 +38,7 @@ public class EcsServiceModel {
private String deploymentController;
private String schedulingStrategy;
private String availabilityZoneRebalancing;
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
private List<EcsLoadBalancer> loadBalancers = new ArrayList<>();
private NetworkConfiguration networkConfiguration;
/**
@@ -39,7 +39,7 @@ public class EcsTask {
private String containerInstanceArn;
private boolean protectionEnabled;
private Instant protectedUntil;
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
private NetworkConfiguration networkConfiguration;
private String networkInterfaceId;
private String privateIpAddress;
@@ -34,7 +34,7 @@ public class TaskDefinition {
private String registeredBy;
private Instant deregisteredAt;
private Instant deleteRequestedAt;
private Map<String, String> tags = new HashMap<>();
private volatile Map<String, String> tags = new HashMap<>();
/** Members Floci does not act on, kept verbatim so DescribeTaskDefinition round-trips. */
private Map<String, Object> unparsed;
@@ -106,6 +106,71 @@ class EcsServicePersistenceTest {
"deleted attribute must not reappear after restart");
}
/**
* IAM's tag lookup reads the tags of the cluster, task definition or container instance whose ARN it is given, as
* tag calls leave them and a restart keeps them. A tag call gives the resource a new map rather than changing the
* one a reader already holds, and an ARN of another account or of no resource reads nothing.
*/
@Test
void storedTagsAreTheTagsOfTheResourceTheArnNamesAndTaggingPutsANewMap() {
SharedStorageFactory storage = new SharedStorageFactory();
EcsService first = serviceWithStorage(storage);
String cluster = first.createCluster("tagged", Map.of("team", "web"), REGION).getClusterArn();
String td = first.registerTaskDefinition("tagged", List.of(container("app", "nginx:latest")),
NetworkMode.awsvpc, "256", "512", null, null, List.of("FARGATE"), Map.of("tier", "web"), REGION)
.getTaskDefinitionArn();
String instance = first.registerContainerInstance("tagged", null, List.of(), REGION).getContainerInstanceArn();
Map<String, String> held = first.listTagsForResource(cluster);
first.tagResource(cluster, Map.of("team", "data"));
first.untagResource(td, List.of("tier"));
first.tagResource(instance, Map.of("rack", "a"));
assertEquals(Map.of("team", "web"), held);
assertEquals(Map.of("team", "data"), first.storedTags(cluster));
assertEquals(Map.of(), first.storedTags(td));
assertEquals(Map.of("rack", "a"), first.storedTags(instance));
assertEquals(Map.of("team", "data"), serviceWithStorage(storage).storedTags(cluster));
assertEquals(Map.of(), first.storedTags(cluster.replace(":000000000000:", ":111122223333:")));
assertEquals(Map.of(), first.storedTags(cluster + "0"));
assertEquals(Map.of(), first.storedTags("arn:aws:s3:::tagged"));
}
/**
* A cluster saved before storage was account-aware, and a task definition saved before that and before its key
* named its Region, are read in place for the default account and never migrated; another account's ARN reads
* nothing.
*/
@Test
void storedTagsReadsPreAccountAwareResourcesOfTheDefaultAccountInPlace() {
InMemoryStorage<String, EcsCluster> rawClusters = new InMemoryStorage<>();
InMemoryStorage<String, TaskDefinition> rawDefinitions = new InMemoryStorage<>();
SharedStorageFactory storage = new SharedStorageFactory();
storage.stores.put("ecs-clusters.json", new AccountAwareStorageBackend<>(rawClusters, null, "000000000000"));
storage.stores.put("ecs-task-definitions.json",
new AccountAwareStorageBackend<>(rawDefinitions, null, "000000000000"));
String clusterArn = "arn:aws:ecs:" + REGION + ":000000000000:cluster/legacy";
EcsCluster cluster = new EcsCluster();
cluster.setClusterName("legacy");
cluster.setClusterArn(clusterArn);
cluster.setTags(Map.of("team", "data"));
rawClusters.put(REGION + "::legacy", cluster);
String definitionArn = "arn:aws:ecs:" + REGION + ":000000000000:task-definition/legacy:1";
TaskDefinition definition = new TaskDefinition();
definition.setFamily("legacy");
definition.setRevision(1);
definition.setTaskDefinitionArn(definitionArn);
definition.setTags(Map.of("tier", "web"));
rawDefinitions.put("legacy:1", definition);
EcsService service = serviceWithStorage(storage);
assertEquals(Map.of("team", "data"), service.storedTags(clusterArn));
assertEquals(Map.of("tier", "web"), service.storedTags(definitionArn));
assertEquals(Map.of(), service.storedTags(clusterArn.replace(":000000000000:", ":111122223333:")));
assertTrue(rawClusters.get(REGION + "::legacy").isPresent());
assertTrue(rawDefinitions.get("legacy:1").isPresent());
}
@Test
void persistedServiceGetsItsTasksBackAfterRestartWithoutAnEcsRequest() {
SharedStorageFactory storage = new SharedStorageFactory();
@@ -65,6 +65,8 @@ class IamRequestResourceEnforcementIntegrationTest {
private static final String EVENTS = "arn:aws:events:" + REGION + ":" + ACCOUNT + ":";
private static final String TARGETS = "arn:aws:application-autoscaling:" + REGION + ":" + ACCOUNT + ":scalable-target/";
private static final String REDSHIFT = "arn:aws:redshift:" + REGION + ":" + ACCOUNT + ":";
/** The X-Amz-Target prefix of ECS operations. */
private static final String ECS_API = "AmazonEC2ContainerServiceV20141113.";
private static final String WORKGROUPS = "arn:aws:redshift-serverless:" + REGION + ":" + ACCOUNT + ":workgroup/";
/** The AWS Load Balancer Controller's create, tag-on-create and listener statements (its policy v2.14.0). */
private static final String CONTROLLER_CREATE = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:CreateLoadBalancer\","
@@ -690,6 +692,33 @@ class IamRequestResourceEnforcementIntegrationTest {
"{\"resourceArn\":\"" + arns + other + "\"}"), "ecr:ListTagsForResource");
}
/**
* An {@code ecs:ResourceTag} or {@code aws:ResourceTag} condition reads the tags ECS holds on the cluster a request
* names, by its name or by its ARN, as a tag call leaves them, so an allow on one team's tag lets the caller read
* that team's cluster and not another's.
*/
@Test
void anEcsResourceTagConditionReadsTheTagsOfTheCluster() {
String tagged = ecsCluster("res-tag-cluster-" + suffix(), "web");
String other = ecsCluster("res-tag-cluster-" + suffix(), "web");
String arns = "arn:aws:ecs:" + REGION + ":" + ACCOUNT + ":cluster/";
adminJson("ecs", ECS_API + "TagResource").body("{\"resourceArn\":\"" + arns + tagged
+ "\",\"tags\":[{\"key\":\"team\",\"value\":\"data\"}]}").post("/").then().statusCode(200);
User user = user("res-ecs-tags");
user.policy("{\"Effect\":\"Allow\",\"Action\":\"ecs:DescribeClusters\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"ecs:ResourceTag/team\":\"data\"}}},"
+ "{\"Effect\":\"Allow\",\"Action\":\"ecs:ListTagsForResource\",\"Resource\":\"*\","
+ "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}");
send(user, "ecs", ECS_API + "DescribeClusters", "1.1", "{\"clusters\":[\"" + tagged + "\"]}").statusCode(200);
refusedJson(send(user, "ecs", ECS_API + "DescribeClusters", "1.1", "{\"clusters\":[\"" + other + "\"]}"),
"ecs:DescribeClusters");
send(user, "ecs", ECS_API + "ListTagsForResource", "1.1", "{\"resourceArn\":\"" + arns + tagged + "\"}")
.statusCode(200);
refusedJson(send(user, "ecs", ECS_API + "ListTagsForResource", "1.1", "{\"resourceArn\":\"" + arns + other
+ "\"}"), "ecs:ListTagsForResource");
}
/**
* An {@code ssm:resourceTag} or {@code aws:ResourceTag} condition reads the tags SSM holds on the parameter or the
* document a request names, so an allow on one team's tag lets the caller read that team's and not another's.
@@ -736,6 +765,13 @@ class IamRequestResourceEnforcementIntegrationTest {
"{\"repositoryName\":\"" + name + "\",\"force\":true}", name);
}
/** An ECS cluster of the name, tagged with the team, deleted afterwards. */
private String ecsCluster(String name, String team) {
return created("ecs", ECS_API + "CreateCluster", "{\"clusterName\":\"" + name + "\",\"tags\":[{\"key\":"
+ "\"team\",\"value\":\"" + team + "\"}]}", ECS_API + "DeleteCluster", "{\"cluster\":\"" + name + "\"}",
name);
}
/**
* {@code name}, after an administrator creates the resource with the JSON 1.1 {@code create} call and registers
* the {@code delete} call that removes it after the test.