fix(elbv2): give resource-tag conditions the tags of the load balancer, target group, listener or rule a request names (#8937)

The generated request resources give Elastic Load Balancing's load
balancer, target group, listener and rule types, and the Classic Load
Balancer's, the aws:ResourceTag/ and elasticloadbalancing:ResourceTag/
keys, but no service answered the elasticloadbalancing namespace's
stored tags, so a condition on their tags saw none.
ElbStoredResourceArns now answers it for both versions: a version 2 ARN
reads the tags version 2 keeps under it, in the request's account, in
place; a Classic Load Balancer's ARN, the one Floci gives it, reads the
load balancer of its name in its Region. Both versions' AddTags and
RemoveTags changed the tag map in place with no lock; they now give the
resource a new map one call at a time, and the Classic Load Balancer's
tags field is volatile.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 22:09:21 -04:00
1 parent f383d774c5
commit f3b8b12777
9 files changed
+283 -19

No files matched your search

+2 -1
View File
@@ -3526,7 +3526,8 @@ floci populates:
and endpoint groups, EMR Serverless for its applications, job runs and sessions, EMR on EKS for its virtual clusters,
job runs, managed endpoints, job templates and security configurations, Cost Explorer for its anomaly monitors and
subscriptions, Security Hub for its hubs and configuration policies, Control Tower for its landing zones and enabled
controls, GuardDuty for its detectors and Malware Protection plans, and Cloud Map for its namespaces and services. Tag
controls, GuardDuty for its detectors and Malware Protection plans, Cloud Map for its namespaces and services, and
Elastic Load Balancing for its load balancers, target groups, listeners and rules and its Classic Load Balancers. 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
@@ -56,7 +56,8 @@ import java.util.Optional;
* job run, a managed endpoint, a job template or a security configuration; Cost Explorer, for the tags of an anomaly
* monitor or subscription; Security Hub, for the tags of a hub or a configuration policy; Control Tower, for the tags
* of a landing zone or an enabled control; GuardDuty, for the tags of a detector or a Malware Protection plan; Cloud
* Map, for the tags of a namespace or a service); looked up lazily by {@code ResourceArnBuilder} and
* Map, for the tags of a namespace or a service; Elastic Load Balancing, for the tags of a load balancer, a target
* group, a listener, a rule or a Classic Load Balancer); 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>
*
@@ -520,20 +520,44 @@ public class ElbClassicService implements ServerCertificateReferenceProvider {
// ── Tags ──────────────────────────────────────────────────────────────────
public void addTags(String region, List<String> names, Map<String, String> tags) {
/**
* Gives each load balancer a new map holding its tags and {@code tags}. Tag calls run one at a time, so two of them
* never lose one's tags, and a lookup reads one whole set.
*/
public synchronized void addTags(String region, List<String> names, Map<String, String> tags) {
for (String name : names) {
requireLoadBalancer(region, name).getTags().putAll(tags);
ClassicLoadBalancer lb = requireLoadBalancer(region, name);
Map<String, String> merged = new LinkedHashMap<>(lb.getTags());
merged.putAll(tags);
lb.setTags(merged);
}
persist(region);
}
public void removeTags(String region, List<String> names, Collection<String> tagKeys) {
/** Gives each load balancer a new map without {@code tagKeys}, one tag call at a time. */
public synchronized void removeTags(String region, List<String> names, Collection<String> tagKeys) {
for (String name : names) {
requireLoadBalancer(region, name).getTags().keySet().removeAll(tagKeys);
ClassicLoadBalancer lb = requireLoadBalancer(region, name);
Map<String, String> remaining = new LinkedHashMap<>(lb.getTags());
remaining.keySet().removeAll(tagKeys);
lb.setTags(remaining);
}
persist(region);
}
/**
* The tags of the load balancer {@code name} in {@code account} and {@code region}, read in place, for IAM's
* lookup of stored tags; none when there is no such load balancer, or the one of that name records another
* account, which a service without storage keeps beside every account's in one map.
*/
public Map<String, String> tagsInAccount(String account, String region, String name) {
Map<String, ClassicLoadBalancer> regionLbs = loadBalancerStore != null
? AccountAwareStorageBackend.readInAccount(loadBalancerStore, account, region).orElse(Map.of())
: loadBalancers.getOrDefault(region, Map.of());
ClassicLoadBalancer lb = regionLbs.get(name);
return lb == null || lb.getAccountId() != null && !lb.getAccountId().equals(account) ? Map.of() : lb.getTags();
}
public Map<String, Map<String, String>> describeTags(String region, List<String> names) {
Map<String, Map<String, String>> result = new LinkedHashMap<>();
for (String name : names) {
@@ -50,7 +50,7 @@ public class ClassicLoadBalancer {
private ClassicHealthCheck healthCheck = ClassicHealthCheck.defaults();
private ClassicLoadBalancerAttributes attributes = new ClassicLoadBalancerAttributes();
private Map<String, String> tags = new LinkedHashMap<>();
private volatile Map<String, String> tags = new LinkedHashMap<>();
public ClassicLoadBalancer() {}
@@ -0,0 +1,80 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.elb.ElbClassicService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* IAM's lookup of the tags Elastic Load Balancing holds, for the {@code elasticloadbalancing} namespace its two
* versions share: a load balancer, target group, listener or rule of version 2 by the ARN version 2 keeps its tags
* under, and a Classic Load Balancer, {@code loadbalancer/<name>}, by its name.
*/
@ApplicationScoped
public class ElbStoredResourceArns implements StoredResourceArns {
private static final String NAMESPACE = "elasticloadbalancing";
private static final String CLASSIC = "loadbalancer/";
private final ElbV2Service elbV2;
private final ElbClassicService classic;
private final RegionResolver regionResolver;
@Inject
public ElbStoredResourceArns(ElbV2Service elbV2, ElbClassicService classic, RegionResolver regionResolver) {
this.elbV2 = elbV2;
this.classic = classic;
this.regionResolver = regionResolver;
}
@Override
public String namespace() {
return NAMESPACE;
}
/** A request names these resources by their ARNs, or a Classic Load Balancer by its name: nothing to find. */
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
/**
* The tags of the resource whose ARN is {@code arn}, in the request's account, where the tag handlers read: an
* ARN of another account names none. A Classic Load Balancer's ARN, the only one whose resource is
* {@code loadbalancer/} and a name alone, reads the load balancer of that name in the ARN's Region when the ARN is
* the one Floci gives it, so one without a Region reads none; any other reads the tags version 2 keeps under that
* ARN. A tag without a value reads as
* an empty one. Tag calls give the resource a new map, so the read is of one whole set.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, NAMESPACE)) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
String account = regionResolver.getAccountId();
if (!parsed.accountId().equals(account)) {
return Map.of();
}
String resource = parsed.resource();
Map<String, String> tags;
if (resource.startsWith(CLASSIC) && resource.indexOf('/', CLASSIC.length()) < 0) {
tags = !parsed.region().isBlank()
&& arn.equals(AwsArnUtils.Arn.of(NAMESPACE, parsed.region(), account, resource).toString())
? classic.tagsInAccount(account, parsed.region(), resource.substring(CLASSIC.length()))
: Map.of();
} else {
tags = elbV2.tagsInAccount(account, arn);
}
Map<String, String> copy = new LinkedHashMap<>();
tags.forEach((key, value) -> copy.put(key, value == null ? "" : value));
return copy;
}
}
@@ -94,6 +94,7 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
private AccountAwareStorageBackend<Map<String, TargetGroup>> targetGroupStore;
private AccountAwareStorageBackend<Map<String, Listener>> listenerStore;
private AccountAwareStorageBackend<Map<String, Rule>> ruleStore;
private AccountAwareStorageBackend<Map<String, String>> tagStore;
// indexes
private final Map<String, List<String>> lbToListeners = new ConcurrentHashMap<>(); // LB-ARN → listener ARNs
@@ -121,8 +122,9 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
this.targetGroups = new StorageBackedMap<>(targetGroupStore);
this.listeners = new StorageBackedMap<>(listenerStore);
this.rules = new StorageBackedMap<>(ruleStore);
this.tags = storageBacked("elbv2-tags.json",
this.tagStore = storageFactory.create("elbv2", "elbv2-tags.json",
new TypeReference<Map<String, Map<String, String>>>() {});
this.tags = new StorageBackedMap<>(tagStore);
normalizeRegionMaps(loadBalancers);
normalizeRegionMaps(targetGroups);
normalizeRegionMaps(listeners);
@@ -131,11 +133,6 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
rebuildIndexes();
}
private <V> Map<String, V> storageBacked(String fileName, TypeReference<Map<String, V>> typeReference)
{
return new StorageBackedMap<>(storageFactory.create("elbv2", fileName, typeReference));
}
private <V> void normalizeRegionMaps(Map<String, Map<String, V>> resources) {
for (Map.Entry<String, Map<String, V>> entry : new ArrayList<>(resources.entrySet())) {
if (!(entry.getValue() instanceof ConcurrentHashMap)) {
@@ -1254,23 +1251,42 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
// ── Tags ──────────────────────────────────────────────────────────────────
public void addTags(List<String> resourceArns, Map<String, String> newTags) {
/**
* Gives each resource a new map holding its tags and {@code newTags}. Tag calls run one at a time, so two of them
* never lose one's tags, and a lookup reads one whole set.
*/
public synchronized void addTags(List<String> resourceArns, Map<String, String> newTags) {
for (String arn : resourceArns) {
tags.computeIfAbsent(arn, k -> new LinkedHashMap<>()).putAll(newTags);
tags.put(arn, tags.get(arn));
Map<String, String> merged = new LinkedHashMap<>(tags.getOrDefault(arn, Map.of()));
merged.putAll(newTags);
tags.put(arn, merged);
}
}
public void removeTags(List<String> resourceArns, List<String> tagKeys) {
/** Gives each resource holding tags a new map without {@code tagKeys}, one tag call at a time. */
public synchronized void removeTags(List<String> resourceArns, List<String> tagKeys) {
for (String arn : resourceArns) {
Map<String, String> resourceTags = tags.get(arn);
if (resourceTags != null) {
tagKeys.forEach(resourceTags::remove);
tags.put(arn, resourceTags);
Map<String, String> remaining = new LinkedHashMap<>(resourceTags);
tagKeys.forEach(remaining::remove);
tags.put(arn, remaining);
}
}
}
/**
* The tags of the load balancer, target group, listener or rule whose ARN is {@code arn}, in {@code account}, read
* in place under the ARN they are kept under, for IAM's lookup of stored tags. A resource's tags go with it when it
* is deleted, so a deleted resource's ARN reads none.
*/
public Map<String, String> tagsInAccount(String account, String arn) {
if (tagStore == null) {
return tags.getOrDefault(arn, Map.of());
}
return AccountAwareStorageBackend.readInAccount(tagStore, account, arn).orElse(Map.of());
}
public Map<String, Map<String, String>> describeTags(List<String> resourceArns) {
Map<String, Map<String, String>> result = new LinkedHashMap<>();
for (String arn : resourceArns) {
@@ -96,6 +96,21 @@ class ElbClassicServiceTest {
List.of(), List.of("subnet-a"), List.of("sg-1"), null, Map.of());
}
/**
* IAM's lookup reads the tags of the load balancer of that name only when it records the account asked for, as a
* service without storage holds every account's load balancers in one map.
*/
@Test
void tagsInAccountReadOnlyTheLoadBalancerOfThatAccount() {
ClassicLoadBalancer lb = service.createLoadBalancer(REGION, "tagged", List.of(httpListener()),
List.of(), List.of("subnet-a"), List.of("sg-1"), null, Map.of("team", "data"));
lb.setAccountId("111111111111");
assertEquals(Map.of("team", "data"), service.tagsInAccount("111111111111", REGION, "tagged"));
assertTrue(service.tagsInAccount("222222222222", REGION, "tagged").isEmpty());
assertTrue(service.tagsInAccount("111111111111", REGION, "missing").isEmpty());
}
@Test
void omittedInstanceProtocolMatchesExplicitDefaultOnListenerRetry() {
ClassicListener listener = httpListener();
@@ -0,0 +1,67 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.elb.ElbClassicService;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/** IAM's lookup of the tags Elastic Load Balancing holds, routed to the version that keeps the resource. */
class ElbStoredResourceArnsTest {
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String ELB = "arn:aws:elasticloadbalancing:us-east-1:000000000000:";
private final ElbV2Service elbV2 = mock(ElbV2Service.class);
private final ElbClassicService classic = mock(ElbClassicService.class);
private final ElbStoredResourceArns lookup =
new ElbStoredResourceArns(elbV2, classic, new RegionResolver(REGION, ACCOUNT));
/**
* A version 2 resource's ARN reads the tags version 2 keeps under it, and a Classic Load Balancer's reads the load
* balancer of its name in its Region, a tag without a value as an empty one.
*/
@Test
void storedTagsReadTheVersionThatKeepsTheResource() {
String targetGroup = ELB + "targetgroup/web/0123456789abcdef";
String listener = ELB + "listener/app/web/0123456789abcdef/fedcba9876543210";
when(elbV2.tagsInAccount(ACCOUNT, targetGroup)).thenReturn(Map.of("team", "data"));
when(elbV2.tagsInAccount(ACCOUNT, listener)).thenReturn(Map.of("team", "ops"));
Map<String, String> noValue = new HashMap<>();
noValue.put("owner", null);
noValue.put("team", "web");
when(classic.tagsInAccount(ACCOUNT, REGION, "legacy")).thenReturn(noValue);
assertEquals("elasticloadbalancing", lookup.namespace());
assertEquals(Map.of("team", "data"), lookup.storedTags(targetGroup));
assertEquals(Map.of("team", "ops"), lookup.storedTags(listener));
assertEquals(Map.of("owner", "", "team", "web"), lookup.storedTags(ELB + "loadbalancer/legacy"));
}
/**
* An ARN of another account, another service, or a Classic Load Balancer's ARN without a Region or in another
* partition than its Region's reads nothing, and neither version is asked.
*/
@Test
void storedTagsReadNothingForAnArnFlociDoesNotGive() {
assertTrue(lookup.storedTags(ELB.replace(ACCOUNT, "111122223333") + "loadbalancer/legacy").isEmpty());
assertTrue(lookup.storedTags(ELB.replace(ACCOUNT, "111122223333") + "targetgroup/web/0123456789abcdef")
.isEmpty());
assertTrue(lookup.storedTags("arn:aws:ec2:us-east-1:000000000000:instance/i-0123456789abcdef0").isEmpty());
assertTrue(lookup.storedTags("arn:aws:elasticloadbalancing::000000000000:loadbalancer/legacy").isEmpty());
assertTrue(lookup.storedTags("arn:aws-cn:elasticloadbalancing:us-east-1:000000000000:loadbalancer/legacy")
.isEmpty());
verify(classic, never()).tagsInAccount(anyString(), anyString(), anyString());
verify(elbV2, never()).tagsInAccount(anyString(), anyString());
}
}
@@ -134,6 +134,66 @@ class IamRequestResourceEnforcementIntegrationTest {
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", createdArn).post("/"));
}
/**
* An {@code elasticloadbalancing:ResourceTag} or {@code aws:ResourceTag} condition reads the tags Elastic Load
* Balancing holds on the target group or the Classic Load Balancer a request names, as a tag call or the create
* leaves them, so an allow on one team's tag lets the caller change that team's resources and not another's.
*/
@Test
void anElbResourceTagConditionReadsTheTagsOfTheTargetGroupAndTheClassicLoadBalancer() {
String tagged = elbTargetGroup();
String other = elbTargetGroup();
admin("elasticloadbalancing").formParam("Action", "AddTags").formParam("Version", "2015-12-01")
.formParam("ResourceArns.member.1", tagged).formParam("Tags.member.1.Key", "team")
.formParam("Tags.member.1.Value", "data").post("/").then().statusCode(200);
String taggedLoadBalancer = classicLoadBalancer("data");
String otherLoadBalancer = classicLoadBalancer("web");
User user = user("res-elb-team");
user.policy("{\"Effect\":\"Allow\",\"Action\":\"elasticloadbalancing:ModifyTargetGroupAttributes\","
+ "\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"elasticloadbalancing:ResourceTag/team\":"
+ "\"data\"}}},{\"Effect\":\"Allow\",\"Action\":\"elasticloadbalancing:ConfigureHealthCheck\","
+ "\"Resource\":\"*\",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}");
modifyAttributes(user, tagged).statusCode(200);
refused(modifyAttributes(user, other), "elasticloadbalancing:ModifyTargetGroupAttributes");
configureHealthCheck(user, taggedLoadBalancer).statusCode(200);
refused(configureHealthCheck(user, otherLoadBalancer), "elasticloadbalancing:ConfigureHealthCheck");
}
/** An IP target group an administrator creates, deleted after the test; its ARN. */
private String elbTargetGroup() {
String arn = admin("elasticloadbalancing").formParam("Action", "CreateTargetGroup")
.formParam("Version", "2015-12-01").formParam("Name", "res-tg-team-" + suffix())
.formParam("Protocol", "HTTP").formParam("Port", "80").formParam("TargetType", "ip").post("/").then()
.statusCode(200).extract()
.path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
cleanup.register(() -> admin("elasticloadbalancing").formParam("Action", "DeleteTargetGroup")
.formParam("Version", "2015-12-01").formParam("TargetGroupArn", arn).post("/").then().statusCode(200));
return arn;
}
/** A Classic Load Balancer an administrator creates, tagged with {@code team}, deleted after the test; its name. */
private String classicLoadBalancer(String team) {
String name = "res-clb-" + suffix();
admin("elasticloadbalancing").formParam("Action", "CreateLoadBalancer").formParam("Version", "2012-06-01")
.formParam("LoadBalancerName", name).formParam("Listeners.member.1.Protocol", "TCP")
.formParam("Listeners.member.1.LoadBalancerPort", "443")
.formParam("Listeners.member.1.InstancePort", "443").formParam("Tags.member.1.Key", "team").formParam("Tags.member.1.Value", team).post("/").then()
.statusCode(200);
cleanup.register(() -> admin("elasticloadbalancing").formParam("Action", "DeleteLoadBalancer")
.formParam("Version", "2012-06-01").formParam("LoadBalancerName", name).post("/").then()
.statusCode(200));
return name;
}
private static ValidatableResponse configureHealthCheck(User user, String loadBalancerName) {
return user.query("elasticloadbalancing", "ConfigureHealthCheck").formParam("Version", "2012-06-01")
.formParam("LoadBalancerName", loadBalancerName).formParam("HealthCheck.Target", "TCP:443")
.formParam("HealthCheck.Interval", "10").formParam("HealthCheck.Timeout", "3")
.formParam("HealthCheck.HealthyThreshold", "2").formParam("HealthCheck.UnhealthyThreshold", "2")
.post("/").then();
}
/**
* The AWS Load Balancer Controller's policy creates on {@code *} with its cluster tag, and tags at creation only
* a target group or an application or network load balancer, as {@code elasticloadbalancing:CreateAction}