From 6829c0b592465584b60ccc26d07c059a93239436 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:02:52 -0400 Subject: [PATCH] fix(cloudtrail): give resource-tag conditions the tags of the trail a request names (#8814) The generated request resources give CloudTrail's trail type the aws:ResourceTag/ key, but no service answered the cloudtrail namespace's stored tags, so a condition on a trail's tags saw none. CloudTrailService now answers it: storedTags reads the trail stored under its home Region, which its ARN names, and its name, in the request's account, where the tag handlers read, in place, and matched on the whole ARN. A tag with no value, which AddTags allows, reads as the empty string. A trail is stored whole and its tags never change in place, so no lock change. --- docs/services/iam.md | 6 +-- .../aws/core/common/StoredResourceArns.java | 7 +-- .../cloudtrail/CloudTrailService.java | 47 +++++++++++++++++-- .../cloudtrail/CloudTrailServiceTest.java | 44 +++++++++++++++++ ...estResourceEnforcementIntegrationTest.java | 45 ++++++++++++++---- 5 files changed, 132 insertions(+), 17 deletions(-) diff --git a/docs/services/iam.md b/docs/services/iam.md index f716f718a4..7321ba3188 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3354,9 +3354,9 @@ floci populates: scalable targets, ECS for its clusters, task definitions, services, capacity providers, tasks and container instances, ACM for its certificates, Firehose for its delivery streams, Cognito for its user pools and identity pools, OpenSearch for its domains, Signer for its signing profiles, Access Analyzer for its analyzers, Managed Service - for Apache Flink for its applications, S3 Vectors for its vector buckets and indexes, and Timestream for InfluxDB for - its DB instances, DB clusters, parameter groups and backups. Tag keys differing only in case are one condition key - holding every value. + for Apache Flink for its applications, S3 Vectors for its vector buckets and indexes, Timestream for InfluxDB for its + DB instances, DB clusters, parameter groups and backups, and CloudTrail for its trails. 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 diff --git a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java index 396335d63e..63abf34f08 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -48,9 +48,10 @@ import java.util.Optional; * stream; Cognito, for the tags of a user pool or an identity pool; OpenSearch, for the tags of a domain; Signer, for * the tags of a signing profile; Access Analyzer, for the tags of an analyzer; Managed Service for Apache Flink, for * the tags of an application; S3 Vectors, for the tags of a vector bucket or an index; Timestream for InfluxDB, for the - * tags of a DB instance, a DB cluster, a parameter group or a backup); looked up lazily by {@code ResourceArnBuilder} - * and {@code IamConditionContextResolver} through {@code Instance} for the namespace a request or - * an ARN is of, so IAM never depends on that service directly.

+ * tags of a DB instance, a DB cluster, a parameter group or a backup; CloudTrail, for the tags of a trail); looked up + * lazily by {@code ResourceArnBuilder} and {@code IamConditionContextResolver} through + * {@code Instance} for the namespace a request or an ARN is of, so IAM never depends on that + * service directly.

* *

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 diff --git a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java index 8b43fdfbc6..be2f375e1d 100644 --- a/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java +++ b/src/main/java/io/floci/aws/services/cloudtrail/CloudTrailService.java @@ -11,6 +11,8 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.AwsRegions; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.ServicePrincipals; +import io.floci.aws.core.common.StoredResourceArns; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.cloudtrail.model.AdvancedEventSelector; @@ -32,6 +34,7 @@ import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -43,12 +46,14 @@ import java.util.function.Supplier; import java.util.regex.Pattern; @ApplicationScoped -public class CloudTrailService { +public class CloudTrailService implements StoredResourceArns { private static final Logger LOG = Logger.getLogger(CloudTrailService.class); private static final String EVENT_VERSION = "1.11"; private static final String S3_EVENT_SOURCE = ServicePrincipals.of("s3"); + /** What a trail's ARN resource starts with, its name following. */ + private static final String TRAIL_RESOURCE = "trail/"; static final int MAX_PENDING_RECORDS_PER_TRAIL = 1024; static final long MAX_PENDING_BYTES_PER_TRAIL = 4L * 1024L * 1024L; @@ -133,7 +138,7 @@ public class CloudTrailService { "Trail " + name + " already exists.", 400); } String arn = AwsArnUtils.Arn.of("cloudtrail", region, regionResolver.getAccountId(), - "trail/" + name).toString(); + TRAIL_RESOURCE + name).toString(); Trail trail = new Trail( name, arn, s3BucketName, s3KeyPrefix, snsTopicArn, includeGlobalServiceEvents, isMultiRegionTrail, region, @@ -382,6 +387,42 @@ public class CloudTrailService { return findEntryByArnOrThrow(resourceId).tags(); } + @Override + public String namespace() { + return "cloudtrail"; + } + + /** A request names a trail by its name or its ARN, the name being the end of its ARN: nothing to find. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + /** + * The tags of the trail whose ARN is {@code arn}, in the request's account, where the tag handlers read: an ARN of + * another account names none. Read in place under the trail's home Region, which its ARN names, and its name, a + * trail stored before storage was account-aware included, and matched on the whole ARN. A tag CloudTrail holds + * with no value, which AddTags allows, reads as the empty string, so a condition compares a string. A trail is + * stored whole and its tags never change in place, so the read is of one whole set. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "cloudtrail")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + if (!parsed.accountId().equals(regionResolver.getAccountId()) + || !parsed.resource().startsWith(TRAIL_RESOURCE)) { + return Map.of(); + } + Map tags = new LinkedHashMap<>(); + AccountAwareStorageBackend.readInAccount(store, parsed.accountId(), + regionKey(parsed.region(), parsed.resource().substring(TRAIL_RESOURCE.length()))) + .filter(entry -> arn.equals(entry.trail().trailArn())) + .ifPresent(entry -> entry.tags().forEach((key, value) -> tags.put(key, value == null ? "" : value))); + return tags; + } + private CloudTrailEntry findEntryByArnOrThrow(String resourceId) { String key = findKeyByArnOrThrow(resourceId); return store.get(key).orElseThrow(() -> new AwsException( @@ -399,7 +440,7 @@ public class CloudTrailService { throw new AwsException("CloudTrailARNInvalidException", resourceId + " is not a valid ARN.", 400); } - if (!"cloudtrail".equals(arn.service()) || !arn.resource().startsWith("trail/")) { + if (!"cloudtrail".equals(arn.service()) || !arn.resource().startsWith(TRAIL_RESOURCE)) { throw new AwsException("CloudTrailARNInvalidException", resourceId + " is not a valid trail ARN.", 400); } diff --git a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java index 38d5071556..cdbd55ed4e 100644 --- a/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudtrail/CloudTrailServiceTest.java @@ -4,17 +4,23 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.cloudtrail.model.Trail; import io.floci.aws.services.iam.IamService; +import io.floci.aws.testing.InMemoryStorageFactory; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; 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.anyString; import static org.mockito.Mockito.mock; @@ -41,6 +47,44 @@ class CloudTrailServiceTest { return service.createTrail(REGION, name, "trail-bucket", prefix, TOPIC, true, false, false, false); } + /** + * IAM's lookup reads the tags of the trail the ARN names, as AddTags and RemoveTags leave them, a tag with no value + * as the empty string, and nothing for another account's, another Region's or an unknown trail. + */ + @Test + void storedTagsAreTheTagsOfTheTrailTheArnNames() { + String arn = service.createTrail(REGION, "tagged", "trail-bucket", null, TOPIC, true, false, false, false, + Map.of("team", "web", "env", "dev")).trailArn(); + Map unvalued = new HashMap<>(); + unvalued.put("team", "data"); + unvalued.put("reviewed", null); + service.addTags(arn, unvalued); + service.removeTags(arn, List.of("env")); + + assertEquals("cloudtrail", service.namespace()); + assertEquals(Map.of("team", "data", "reviewed", ""), service.storedTags(arn)); + assertTrue(service.storedTags(arn.replace(ACCOUNT, "111122223333")).isEmpty()); + assertTrue(service.storedTags(arn.replace(REGION, "us-west-2")).isEmpty()); + assertTrue(service.storedTags(arn.replace("trail/tagged", "trail/missing")).isEmpty()); + assertTrue(service.storedTags("arn:aws:s3:::trail-bucket").isEmpty()); + } + + /** A trail stored before storage was account-aware is read in place: the lookup migrates nothing. */ + @Test + void storedTagsReadAPreAccountAwareTrailInPlace() { + InMemoryStorage raw = new InMemoryStorage<>(); + CloudTrailService legacyState = new CloudTrailService( + new InMemoryStorageFactory(ACCOUNT).withStore("cloudtrail-trails.json", raw), + new RegionResolver(REGION, ACCOUNT), mock(IamService.class), new ObjectMapper()); + String arn = legacyState.createTrail(REGION, "legacy", "trail-bucket", null, TOPIC, true, false, false, false, + Map.of("team", "data")).trailArn(); + raw.put(REGION + ":legacy", raw.get(ACCOUNT + "/" + REGION + ":legacy").orElseThrow()); + raw.delete(ACCOUNT + "/" + REGION + ":legacy"); + + assertEquals(Map.of("team", "data"), legacyState.storedTags(arn)); + assertEquals(Set.of(REGION + ":legacy"), raw.keys()); + } + // --- replaceTrailS3KeyPrefix: a service method that does not exist on main --- @Test diff --git a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java index 000015d78c..a8971da4ac 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -1516,14 +1516,8 @@ class IamRequestResourceEnforcementIntegrationTest { void aTrailIsCheckedOnTheArnItsNameGives() { String name = "res-trail-" + suffix(); String other = name + "-other"; - for (String trail : List.of(name, other)) { - adminJson("cloudtrail", "CloudTrail_20131101.CreateTrail") - .body("{\"Name\":\"" + trail + "\",\"S3BucketName\":\"res-trail-logs\"}").post("/").then() - .statusCode(200); - cleanup.register(() -> adminJson("cloudtrail", "CloudTrail_20131101.DeleteTrail") - .body("{\"Name\":\"" + trail + "\"}").post("/")); - } - String arn = "arn:aws:cloudtrail:" + REGION + ":" + ACCOUNT + ":trail/" + name; + String arn = trail(name, null); + trail(other, null); User user = user("res-trail"); user.policy(allowOn("cloudtrail:GetTrailStatus", arn) + "," + allowOn("cloudtrail:AddTags", arn)); @@ -1540,6 +1534,41 @@ class IamRequestResourceEnforcementIntegrationTest { "{\"ResourceId\":\"" + arn + "-other" + tags), "cloudtrail:AddTags"); } + /** + * An {@code aws:ResourceTag} condition reads the tags CloudTrail holds on the trail a request names, as AddTags + * leaves them, so an allow on one team's tag lets the caller read that team's trail status and not another's. + */ + @Test + void aCloudTrailResourceTagConditionReadsTheTagsOfTheTrail() { + String web = "[{\"Key\":\"team\",\"Value\":\"web\"}]"; + String tagged = "res-trail-tagged-" + suffix(); + String other = "res-trail-untagged-" + suffix(); + String taggedArn = trail(tagged, web); + trail(other, web); + adminJson("cloudtrail", "CloudTrail_20131101.AddTags") + .body("{\"ResourceId\":\"" + taggedArn + "\",\"TagsList\":[{\"Key\":\"team\",\"Value\":\"data\"}]}") + .post("/").then().statusCode(200); + + User user = user("res-trail-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":\"cloudtrail:GetTrailStatus\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + send(user, "cloudtrail", "CloudTrail_20131101.GetTrailStatus", "1.1", "{\"Name\":\"" + tagged + "\"}") + .statusCode(200); + refusedJson(send(user, "cloudtrail", "CloudTrail_20131101.GetTrailStatus", "1.1", + "{\"Name\":\"" + other + "\"}"), "cloudtrail:GetTrailStatus"); + } + + /** The ARN of the trail {@code name} an administrator creates, with the {@code tags} list if any, deleted after. */ + private String trail(String name, String tags) { + adminJson("cloudtrail", "CloudTrail_20131101.CreateTrail") + .body("{\"Name\":\"" + name + "\",\"S3BucketName\":\"res-trail-logs\"" + + (tags == null ? "" : ",\"TagsList\":" + tags) + "}") + .post("/").then().statusCode(200); + cleanup.register(() -> adminJson("cloudtrail", "CloudTrail_20131101.DeleteTrail") + .body("{\"Name\":\"" + name + "\"}").post("/")); + return "arn:aws:cloudtrail:" + REGION + ":" + ACCOUNT + ":trail/" + name; + } + /** A CloudTrail dashboard is checked on the one its {@code DashboardId}, a name or an ARN, names. */ @Test void aDashboardIsCheckedOnTheOneItsIdNames() {