fix(iam): read the stored tags of CloudWatch alarms, dashboards and metric streams (#9796)

The request-resources table gives CloudWatch's alarms, dashboards and metric streams the aws:ResourceTag keys, which
the Service Reference lists for them, but CloudWatch answered no storedTags, so a condition on a resource tag never
matched: a caller allowed cloudwatch:DeleteAlarms only on alarms tagged team=blue was refused it on the blue alarm as
on any other.

CloudWatchStoredResourceArns reads the tags CloudWatch's tag operations read, each kind from the service keeping it:
an alarm's from the metrics service, a dashboard's from the dashboards service and a metric stream's from the metric
streams service. An ARN of another account, or one naming no resource CloudWatch holds, reads none.

The dashboards and metric streams services changed a resource's tags in place under no lock, and their tag read
handed out the live map, which an IAM check reading it while another request tags the resource could see half
changed or fail on. Their tag read, tag and untag are now synchronized, and the read returns a copy, as the metrics
service's already were; the dashboards and metric streams service tests check the read is a copy.

Each kind is told by the resource part its ARN starts with (alarm:, dashboard/, metric-stream/), as the table's
formats name it. isDashboardArn and isMetricStreamArn matched their word anywhere in the ARN, and an alarm may be
named x:dashboard/y, which then went to the dashboards service, read no tags and escaped a tag-scoped Deny; the tag
handlers dispatched with the same helpers, so they now match the prefix too.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-29 23:26:55 -04:00
1 parent bcb2a5e29c
commit 10cec1d376
7 files changed
+284 -15

No files matched your search

+6 -5
View File
@@ -4017,11 +4017,12 @@ floci populates:
Load Balancing for its load balancers, target groups, listeners and rules and its Classic Load Balancers, SQS for its
queues, SNS for its topics, Kinesis Data Streams for its streams and consumers, EventBridge Pipes for its pipes,
Aurora DSQL for its clusters, MemoryDB for its clusters, users and ACLs, EKS for its clusters, node groups,
Fargate profiles, add-ons, Pod Identity associations and access entries, Resource Groups for its groups, CloudWatch Logs for its log groups,
destinations, delivery sources, delivery destinations and deliveries, Pricing Calculator for its workload
estimates, AWS Config for its rules, aggregators, conformance packs and the other resources it tags, EFS for its
file systems and access points, Route 53 Resolver for its endpoints, rules and firewall domain lists, and Amazon
Managed Service for Prometheus for its workspaces and rule groups namespaces. Tag keys
Fargate profiles, add-ons, Pod Identity associations and access entries, Resource Groups for its groups,
CloudWatch Logs for its log groups, destinations, delivery sources, delivery destinations and deliveries,
CloudWatch for its alarms, dashboards and metric streams, Pricing Calculator for its workload estimates, AWS
Config for its rules, aggregators, conformance packs and the other resources it tags, EFS for its file systems
and access points, Route 53 Resolver for its endpoints, rules and firewall domain lists, and Amazon Managed
Service for Prometheus for its workspaces and rule groups namespaces. 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
@@ -300,20 +300,27 @@ public class CloudWatchDashboardsService {
* taggable resource it owns, so the handler needs to know which service should answer.
*/
public static boolean isDashboardArn(String resourceArn) {
return resourceArn != null && resourceArn.contains(":dashboard/");
// The resource part the ARN starts with, not a match anywhere in it: another kind's name may hold this word
// (an alarm named x:dashboard/y).
return AwsArnUtils.resourceIfArnFor(resourceArn, "cloudwatch")
.filter(resource -> resource.startsWith("dashboard/")).isPresent();
}
public Map<String, String> listTagsForResource(String resourceArn, String region) {
return requireDashboard(resourceArn).getTags();
/**
* The resource's tags, as a copy taken under the monitor its tag changes hold, so a concurrent change, IAM's read
* of them for an {@code aws:ResourceTag} condition included, sees them whole or not at all.
*/
public synchronized Map<String, String> listTagsForResource(String resourceArn, String region) {
return new LinkedHashMap<>(requireDashboard(resourceArn).getTags());
}
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
public synchronized void tagResource(String resourceArn, Map<String, String> tags, String region) {
Dashboard dashboard = requireDashboard(resourceArn);
dashboard.getTags().putAll(tags);
dashboardStore.put(dashboard.getDashboardName(), dashboard);
}
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
public synchronized void untagResource(String resourceArn, List<String> tagKeys, String region) {
Dashboard dashboard = requireDashboard(resourceArn);
tagKeys.forEach(dashboard.getTags()::remove);
dashboardStore.put(dashboard.getDashboardName(), dashboard);
@@ -0,0 +1,87 @@
package io.floci.aws.services.cloudwatch.metrics;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.cloudwatch.dashboards.CloudWatchDashboardsService;
import io.floci.aws.services.cloudwatch.metricstreams.CloudWatchMetricStreamsService;
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;
/**
* What IAM asks CloudWatch of the resources a request names: the tags it keeps on an alarm, a dashboard or a metric
* stream, which the request-resources table's resource-tag keys for those types take as their values
* ({@code aws:ResourceTag/<key>}).
*/
@ApplicationScoped
public class CloudWatchStoredResourceArns implements StoredResourceArns {
private final CloudWatchMetricsService metrics;
private final CloudWatchDashboardsService dashboards;
private final CloudWatchMetricStreamsService streams;
private final RegionResolver regionResolver;
@Inject
public CloudWatchStoredResourceArns(CloudWatchMetricsService metrics, CloudWatchDashboardsService dashboards,
CloudWatchMetricStreamsService streams, RegionResolver regionResolver) {
this.metrics = metrics;
this.dashboards = dashboards;
this.streams = streams;
this.regionResolver = regionResolver;
}
@Override
public String namespace() {
return "cloudwatch";
}
/** A request names an alarm, a dashboard or a metric stream by the name its ARN ends in: nothing to find. */
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
/**
* {@inheritDoc}
*
* <p>The tags of the caller's alarm, dashboard or metric stream the ARN names, as CloudWatch's tag operations read
* them, each kind from the service that keeps it and as a copy taken under the monitor its tag changes hold; none
* for an ARN of another account, whose resources CloudWatch keeps none of for the caller, or one naming no resource
* it holds.
*/
@Override
public Map<String, String> storedTags(String arn) {
if (!AwsArnUtils.isArnFor(arn, "cloudwatch")) {
return Map.of();
}
AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn);
if (!parsed.accountId().equals(regionResolver.getAccountId())) {
return Map.of();
}
// Each kind by the resource part its ARN starts with, as the table's formats name it: a name may hold another
// kind's word (an alarm named x:dashboard/y), which a match anywhere in the ARN would send to the wrong store.
String resource = parsed.resource();
try {
Map<String, String> tags;
if (resource.startsWith("alarm:") && !parsed.region().isBlank()) {
tags = metrics.listTagsForResource(arn, parsed.region());
} else if (resource.startsWith("dashboard/")) {
tags = dashboards.listTagsForResource(arn, parsed.region());
} else if (resource.startsWith("metric-stream/") && !parsed.region().isBlank()) {
tags = streams.listTagsForResource(arn, parsed.region());
} else {
return Map.of();
}
return StoredResourceArns.withEmptyValues(tags == null ? Map.of() : new LinkedHashMap<>(tags));
} catch (AwsException expected) {
// A resource CloudWatch does not hold has no stored tags for IAM to read.
return Map.of();
}
}
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.cloudwatch.metricstreams;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
@@ -192,20 +193,27 @@ public class CloudWatchMetricStreamsService {
* taggable resource it owns, so the handler needs to know which service should answer.
*/
public static boolean isMetricStreamArn(String resourceArn) {
return resourceArn != null && resourceArn.contains(":metric-stream/");
// The resource part the ARN starts with, not a match anywhere in it: another kind's name may hold this word
// (an alarm named x:metric-stream/y).
return AwsArnUtils.resourceIfArnFor(resourceArn, "cloudwatch")
.filter(resource -> resource.startsWith("metric-stream/")).isPresent();
}
public Map<String, String> listTagsForResource(String resourceArn, String region) {
return requireStream(resourceArn, region).getTags();
/**
* The resource's tags, as a copy taken under the monitor its tag changes hold, so a concurrent change, IAM's read
* of them for an {@code aws:ResourceTag} condition included, sees them whole or not at all.
*/
public synchronized Map<String, String> listTagsForResource(String resourceArn, String region) {
return new LinkedHashMap<>(requireStream(resourceArn, region).getTags());
}
public void tagResource(String resourceArn, Map<String, String> tags, String region) {
public synchronized void tagResource(String resourceArn, Map<String, String> tags, String region) {
MetricStream stream = requireStream(resourceArn, region);
stream.getTags().putAll(tags);
streamStore.put(key(region, stream.getName()), stream);
}
public void untagResource(String resourceArn, List<String> tagKeys, String region) {
public synchronized void untagResource(String resourceArn, List<String> tagKeys, String region) {
MetricStream stream = requireStream(resourceArn, region);
tagKeys.forEach(stream.getTags()::remove);
streamStore.put(key(region, stream.getName()), stream);
@@ -142,6 +142,23 @@ class CloudWatchDashboardsServiceTest {
service.listDashboards(null, REGION).stream().map(Dashboard::getDashboardName).toList());
}
/**
* The tags read are a copy: changing it leaves the dashboard's tags as they are, and a later tag change leaves an
* earlier read as it was, so IAM's read of them can neither change them nor see them change under it.
*/
@Test
void theTagsReadAreACopy() {
service.putDashboard("copy", BODY, Map.of("team", "platform"), REGION);
String arn = service.getDashboard("copy", REGION).getDashboardArn();
Map<String, String> read = service.listTagsForResource(arn, REGION);
read.put("forged", "yes");
service.tagResource(arn, Map.of("later", "change"), REGION);
assertEquals(Map.of("team", "platform", "later", "change"), service.listTagsForResource(arn, REGION));
assertEquals(Map.of("team", "platform", "forged", "yes"), read);
}
@Test
void tagsGivenOnCreateAreReadableByArn() {
service.putDashboard("ops", BODY, Map.of("team", "platform"), REGION);
@@ -336,6 +353,9 @@ class CloudWatchDashboardsServiceTest {
String arn = service.getDashboard("ops", REGION).getDashboardArn();
String ghost = arn.replace("dashboard/ops", "dashboard/nosuch");
assertTrue(CloudWatchDashboardsService.isDashboardArn(ghost));
// An alarm whose name holds the word is still an alarm.
assertFalse(CloudWatchDashboardsService.isDashboardArn(
"arn:aws:cloudwatch:us-east-1:000000000000:alarm:x:dashboard/ops"));
for (Runnable call : List.<Runnable>of(
() -> service.tagResource(ghost, Map.of("env", "prod"), REGION),
@@ -0,0 +1,125 @@
package io.floci.aws.services.cloudwatch.metrics;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.ComparisonOperator;
import software.amazon.awssdk.services.cloudwatch.model.Statistic;
import java.net.URI;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
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 condition on {@code aws:ResourceTag} reads the tags CloudWatch keeps on an alarm and a dashboard, the types the
* request-resources table gives resource-tag keys: a caller allowed {@code cloudwatch:DeleteAlarms} and
* {@code cloudwatch:GetDashboard} only on resources tagged {@code team=blue} acts on the blue one and is refused the
* red one.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class CloudWatchResourceTagIamIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final Region REGION = Region.US_EAST_1;
@TestHTTPResource("/")
URI endpoint;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void anAlarmIsCheckedWithItsTags() {
alarmsAreCheckedWithTheirTags("blue-" + suffix(), "red-" + suffix());
}
/**
* An alarm is read as an alarm by the resource part its ARN starts with, whatever its name holds: one named like a
* dashboard or a metric stream is checked with its own tags, not none.
*/
@Test
void anAlarmNamedLikeAnotherKindIsCheckedWithItsOwnTags() {
alarmsAreCheckedWithTheirTags("blue:dashboard/" + suffix(), "red:metric-stream/" + suffix());
}
private void alarmsAreCheckedWithTheirTags(String blue, String red) {
try (CloudWatchClient admin = admin()) {
for (String[] alarm : new String[][] {{blue, "blue"}, {red, "red"}}) {
admin.putMetricAlarm(r -> r.alarmName(alarm[0]).namespace("Floci/Test").metricName("Errors")
.statistic(Statistic.SUM).period(60).evaluationPeriods(1).threshold(1.0)
.comparisonOperator(ComparisonOperator.GREATER_THAN_THRESHOLD)
.tags(t -> t.key("team").value(alarm[1])));
}
cleanup.register(() -> {
try (CloudWatchClient owner = admin()) {
owner.deleteAlarms(r -> r.alarmNames(red));
}
});
}
try (CloudWatchClient caller = blueOnly("cloudwatch:DeleteAlarms")) {
denied(() -> caller.deleteAlarms(r -> r.alarmNames(red)));
caller.deleteAlarms(r -> r.alarmNames(blue));
}
}
@Test
void aDashboardIsCheckedWithItsTags() {
String blue = "blue-" + suffix();
String red = "red-" + suffix();
try (CloudWatchClient admin = admin()) {
for (String[] dashboard : new String[][] {{blue, "blue"}, {red, "red"}}) {
admin.putDashboard(r -> r.dashboardName(dashboard[0]).dashboardBody("{\"widgets\":[]}"));
String arn = "arn:aws:cloudwatch::" + ACCOUNT + ":dashboard/" + dashboard[0];
admin.tagResource(r -> r.resourceARN(arn).tags(t -> t.key("team").value(dashboard[1])));
cleanup.register(() -> {
try (CloudWatchClient owner = admin()) {
owner.deleteDashboards(r -> r.dashboardNames(dashboard[0]));
}
});
}
}
try (CloudWatchClient caller = blueOnly("cloudwatch:GetDashboard")) {
denied(() -> caller.getDashboard(r -> r.dashboardName(red)));
assertEquals(blue, caller.getDashboard(r -> r.dashboardName(blue)).dashboardName());
}
}
private CloudWatchClient admin() {
return AwsTestClients.create(CloudWatchClient.builder(), ACCOUNT, REGION, endpoint);
}
private CloudWatchClient blueOnly(String action) {
String name = "tags-" + suffix();
String authorization = auth(ACCOUNT, REGION.id(), "iam");
UserCredentials user = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), authorization, name);
EnforcementFixtures.putUserPolicy(endpoint.getPort(), authorization, name, "blue", """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"%s","Resource":"*",
"Condition":{"StringEquals":{"aws:ResourceTag/team":"blue"}}}]}""".formatted(action));
return AwsTestClients.create(CloudWatchClient.builder(), user.accessKeyId(), user.secretAccessKey(), REGION,
endpoint);
}
private static void denied(Runnable call) {
CloudWatchException e = assertThrows(CloudWatchException.class, call::run);
assertTrue(e.awsErrorDetails().errorCode().startsWith("AccessDenied"), e.awsErrorDetails().errorCode());
}
private static String suffix() {
return UUID.randomUUID().toString().substring(0, 8);
}
}
@@ -215,6 +215,24 @@ class CloudWatchMetricStreamsServiceTest {
assertTrue(service.listMetricStreams(REGION).isEmpty());
}
/**
* The tags read are a copy: changing it leaves the stream's tags as they are, and a later tag change leaves an
* earlier read as it was, so IAM's read of them can neither change them nor see them change under it.
*/
@Test
void theTagsReadAreACopy() {
MetricStream tagged = stream("copy");
tagged.setTags(new LinkedHashMap<>(Map.of("team", "platform")));
String arn = service.putMetricStream(tagged, REGION).getArn();
Map<String, String> read = service.listTagsForResource(arn, REGION);
read.put("forged", "yes");
service.tagResource(arn, Map.of("later", "change"), REGION);
assertEquals(Map.of("team", "platform", "later", "change"), service.listTagsForResource(arn, REGION));
assertEquals(Map.of("team", "platform", "forged", "yes"), read);
}
@Test
void tagsRoundTripByArn() {
MetricStream tagged = stream("ops");
@@ -224,6 +242,9 @@ class CloudWatchMetricStreamsServiceTest {
assertTrue(CloudWatchMetricStreamsService.isMetricStreamArn(arn));
assertFalse(CloudWatchMetricStreamsService.isMetricStreamArn(
"arn:aws:cloudwatch:us-east-1:000000000000:alarm:ops"));
// An alarm whose name holds the word is still an alarm.
assertFalse(CloudWatchMetricStreamsService.isMetricStreamArn(
"arn:aws:cloudwatch:us-east-1:000000000000:alarm:x:metric-stream/ops"));
assertEquals("platform", service.listTagsForResource(arn, REGION).get("team"));
service.tagResource(arn, Map.of("owner", "ops"), REGION);