From 15519216c36f4e46897b3155cd5d2617469f8229 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:54:23 -0400 Subject: [PATCH] fix(cloudfront): give resource-tag conditions the tags of the resource a request names (#8700) The generated request resources give ten CloudFront types the aws:ResourceTag/ key, but CloudFrontKeyValueStoreService, the namespace's StoredResourceArns, answered no tags, so a condition on a CloudFront resource's tags saw none. It now reads the tags CloudFront holds under the ARN, in place, from the tag store CloudFrontService writes, where the tag handlers keep them: in the request's account, by the whole ARN, since CloudFront ARNs name the default account whichever account owns the resource. DeleteFunction now removes the tags kept under the function's ARN, its name, and CreateFunction drops any left there, so a function created again under a deleted one's name starts with none. CloudFront's tag writes already put a new map in place of the held one. --- docs/services/iam.md | 5 +- .../aws/core/common/StoredResourceArns.java | 7 +- .../cloudfront/CloudFrontController.java | 4 +- .../CloudFrontKeyValueStoreService.java | 28 ++++++++ .../cloudfront/CloudFrontService.java | 12 +++- .../cloudfront/CloudFrontServiceTest.java | 55 ++++++++++++++++ ...amRestRouteEnforcementIntegrationTest.java | 65 +++++++++++++++---- 7 files changed, 156 insertions(+), 20 deletions(-) diff --git a/docs/services/iam.md b/docs/services/iam.md index d8299600bf..8b646cca36 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3191,8 +3191,9 @@ floci populates: projects and report groups, Athena for its workgroups and data catalogs, Redshift Serverless for its namespaces, workgroups and snapshots, DynamoDB for its tables and their indexes (the table's tags), ECR for its repositories, Redshift for its clusters, snapshots, parameter groups, subnet groups, snapshot copy grants, - snapshot schedules, event subscriptions and integrations, SSM for its parameters, documents and associations, and - EMR for its clusters. Tag keys differing only in case are one condition key holding every value. + snapshot schedules, event subscriptions and integrations, SSM for its parameters, documents and associations, + EMR for its clusters, and CloudFront for every resource it tags, by its ARN. 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 a6e6fc9a53..60b2059d9e 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -38,9 +38,10 @@ import java.util.Optional; * for the tags of a table and its indexes; ECR, for the tags of a repository; Redshift, for the key a snapshot records * 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); 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.

+ * 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} 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/cloudfront/CloudFrontController.java b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontController.java index 696487417e..c8b7e0d19d 100644 --- a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontController.java +++ b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontController.java @@ -985,7 +985,7 @@ public class CloudFrontController { appendKeyValueStoreAssociations(xml, fn); xml.end("FunctionConfig") .start("FunctionMetadata") - .elem("FunctionARN", service.arn("function/" + fn.getName())) + .elem("FunctionARN", service.functionArn(fn.getName())) .elem("Stage", fn.getStage()) .elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "") .elem("LastModifiedTime", @@ -2533,7 +2533,7 @@ public class CloudFrontController { appendKeyValueStoreAssociations(xml, fn); return xml.end("FunctionConfig") .start("FunctionMetadata") - .elem("FunctionARN", service.arn("function/" + fn.getName())) + .elem("FunctionARN", service.functionArn(fn.getName())) .elem("Stage", fn.getStage()) .elem("CreatedTime", fn.getCreatedTime() != null ? fn.getCreatedTime().toString() : "") .elem("LastModifiedTime", diff --git a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontKeyValueStoreService.java b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontKeyValueStoreService.java index 84d63e168b..b3ee02cccd 100644 --- a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontKeyValueStoreService.java +++ b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontKeyValueStoreService.java @@ -1,6 +1,7 @@ package io.floci.aws.services.cloudfront; 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; @@ -49,12 +50,19 @@ public class CloudFrontKeyValueStoreService implements StoredResourceArns { private static final String STATUS_READY = "READY"; private final StorageBackend store; + /** + * The tags CloudFront holds by resource ARN, which {@link CloudFrontService} keeps; the factory hands every caller + * of the file the same store, so this one reads the tags it writes. + */ + private final StorageBackend> tags; private final RegionResolver regionResolver; @Inject public CloudFrontKeyValueStoreService(StorageFactory factory, RegionResolver regionResolver) { this.store = factory.create("cloudfront", "cloudfront-key-value-stores.json", new TypeReference>() {}); + this.tags = factory.create("cloudfront", CloudFrontService.TAGS_FILE, + new TypeReference>>() {}); this.regionResolver = regionResolver; } @@ -145,6 +153,26 @@ public class CloudFrontKeyValueStoreService implements StoredResourceArns { } return store.get(names.getFirst()).map(KeyValueStore::getArn); } + + /** + * The tags CloudFront holds under {@code arn}, whatever its resource type, read in place where its tag handlers + * keep and read them: in the account the request runs in, by the whole ARN. CloudFront ARNs name the configured + * default account whichever account owns the resource, so the ARN's account does not say where its tags are. + * Empty when it holds none there. + */ + @Override + public Map storedTags(String arn) { + Map held = new LinkedHashMap<>(); + if (!AwsArnUtils.isArnFor(arn, "cloudfront")) { + return held; + } + tags.get(arn).ifPresent(stored -> stored.forEach((key, value) -> { + if (key != null && value != null) { + held.put(key, value); + } + })); + return held; + } public Optional findByArn(String arn) { if (arn == null) { return Optional.empty(); diff --git a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontService.java b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontService.java index 8d76e34b89..340d160c7f 100644 --- a/src/main/java/io/floci/aws/services/cloudfront/CloudFrontService.java +++ b/src/main/java/io/floci/aws/services/cloudfront/CloudFrontService.java @@ -65,6 +65,8 @@ import java.util.regex.Pattern; @ApplicationScoped public class CloudFrontService implements ServerCertificateReferenceProvider { + /** The file CloudFront's tags are stored in, by resource ARN, which IAM's tag lookup also reads. */ + static final String TAGS_FILE = "cloudfront-tags.json"; private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final int MAX_CUSTOM_RESPONSE_HEADERS_POLICIES = 20; private static final int MAX_DISTRIBUTIONS_PER_RESPONSE_HEADERS_POLICY = 100; @@ -209,7 +211,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { new TypeReference>() {}); this.functionStore = factory.create("cloudfront", "cloudfront-functions.json", new TypeReference>() {}); - this.tagStore = factory.create("cloudfront", "cloudfront-tags.json", + this.tagStore = factory.create("cloudfront", TAGS_FILE, new TypeReference>>() {}); this.cdpStore = factory.create("cloudfront", "cloudfront-continuous-deployment-policies.json", new TypeReference>() {}); @@ -1877,10 +1879,17 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { fn.setEtag(UUID.randomUUID().toString()); fn.setCreatedTime(Instant.now()); fn.setLastModifiedTime(Instant.now()); + // A function's ARN is its name: a new one starts with no tags, whatever was left under that ARN before. + tagStore.delete(functionArn(fn.getName())); functionStore.put(fn.getName(), fn); return fn; } + /** The ARN of the function {@code name}, which is the one its tags are kept under. */ + public String functionArn(String name) { + return arn("function/" + name); + } + public CloudFrontFunction describeFunction(String name, String stage) { String effectiveStage = normalizeFunctionStage(stage); Optional function = functionStore.get(functionKey(name, effectiveStage)); @@ -1940,6 +1949,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider { } functionStore.delete(name); functionStore.delete(functionKey(name, "LIVE")); + tagStore.delete(functionArn(name)); } public List listFunctions(String stage, String marker, int maxItems) { diff --git a/src/test/java/io/floci/aws/services/cloudfront/CloudFrontServiceTest.java b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontServiceTest.java index 7e52fd0859..c29df2b989 100644 --- a/src/test/java/io/floci/aws/services/cloudfront/CloudFrontServiceTest.java +++ b/src/test/java/io/floci/aws/services/cloudfront/CloudFrontServiceTest.java @@ -348,6 +348,61 @@ class CloudFrontServiceTest { assertEquals(Map.of("team", "infra"), service.listTagsForResource(dist.getArn())); } + /** + * IAM's tag lookup, which the key value store service answers for the namespace, reads the tags CloudFront holds + * under the whole ARN where its tag handlers keep them, in the account the request runs in, from the store this + * service writes them to; the ARN's account does not move the read, since CloudFront ARNs name the default one. + */ + @Test + void storedTagsAreTheTagsHeldUnderTheWholeArnWhereTheRequestRuns() { + CloudFrontService service = serviceWithDomainSuffix(DEFAULT_DOMAIN_SUFFIX); + CloudFrontKeyValueStoreService lookup = keyValueStoresOnTheSameFiles(); + Distribution dist = service.createDistribution(new Distribution(), Map.of("team", "data")); + service.tagResource(dist.getArn(), Map.of("env", "prod")); + String otherAccountArn = dist.getArn().replace(ACCOUNT, "111111111111"); + service.tagResource(otherAccountArn, Map.of("owner", "them")); + + assertEquals(Map.of("team", "data", "env", "prod"), lookup.storedTags(dist.getArn())); + assertEquals(Map.of("owner", "them"), lookup.storedTags(otherAccountArn)); + assertEquals(Map.of(), lookup.storedTags(dist.getArn() + "X")); + assertEquals(Map.of(), lookup.storedTags("arn:aws:s3:::" + dist.getId().toLowerCase())); + } + + /** A function's ARN is its name, so one deleted and created again starts with no tags, for IAM as for the API. */ + @Test + void aFunctionCreatedAgainUnderADeletedOnesNameHasNoneOfItsTags() { + CloudFrontService service = serviceWithDomainSuffix(DEFAULT_DOMAIN_SUFFIX); + CloudFrontKeyValueStoreService lookup = keyValueStoresOnTheSameFiles(); + String arn = service.functionArn("tagged"); + service.tagResource(arn, Map.of("seeded", "before")); + CloudFrontFunction created = service.createFunction(function("tagged")); + assertEquals(Map.of(), service.listTagsForResource(arn)); + service.tagResource(arn, Map.of("team", "data")); + + service.deleteFunction("tagged", created.getEtag()); + service.createFunction(function("tagged")); + + assertEquals(Map.of(), service.listTagsForResource(arn)); + assertEquals(Map.of(), lookup.storedTags(arn)); + } + + /** A key value store service on the same per-file stores as the service {@link #serviceWithDomainSuffix} built. */ + private CloudFrontKeyValueStoreService keyValueStoresOnTheSameFiles() { + StorageFactory sameFiles = Mockito.mock(StorageFactory.class); + when(sameFiles.create(Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenAnswer(invocation -> stores.computeIfAbsent(invocation.getArgument(1, String.class), + ignored -> AccountAwareStorageBackend.inMemory(ACCOUNT))); + return new CloudFrontKeyValueStoreService(sameFiles, new RegionResolver("us-east-1", ACCOUNT)); + } + + private static CloudFrontFunction function(String name) { + CloudFrontFunction function = new CloudFrontFunction(); + function.setName(name); + function.setFunctionCode("function handler(event) { return event.request; }"); + function.setRuntime("cloudfront-js-2.0"); + return function; + } + @Test void deletingDistributionRemovesTagsStoredUnderItsArn() { CloudFrontService service = serviceWithDomainSuffix(DEFAULT_DOMAIN_SUFFIX); diff --git a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java index 2e86b81141..78d6984e3b 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRestRouteEnforcementIntegrationTest.java @@ -53,6 +53,8 @@ class IamRestRouteEnforcementIntegrationTest { private static final String MANAGEMENT = "731000000154"; /** Another account, owning the sinks and shares this class's own account reaches across accounts. */ private static final String PEER = "731000000162"; + /** The XML namespace of CloudFront's 2020-05-31 control plane requests. */ + private static final String CLOUDFRONT_XMLNS = "http://cloudfront.amazonaws.com/doc/2020-05-31/"; @TestHTTPResource("/") static URI baseUri; @@ -115,18 +117,10 @@ class IamRestRouteEnforcementIntegrationTest { @Test void cloudFrontKeyValueStoreControlPlaneIsCheckedAgainstTheStoresReturnedArn() { String user = user("route-kvs-control"); - String name = "kvs-" + suffix(); - String namespace = "http://cloudfront.amazonaws.com/doc/2020-05-31/"; - Response created = given().header("Authorization", auth(ADMIN, "cloudfront")) - .contentType("application/xml") - .body("" + name - + "") - .post("/2020-05-31/key-value-store"); - created.then().statusCode(201); - String arn = XmlParser.extractFirst(created.asString(), "ARN", null); - String etag = created.header("ETag"); - cleanup.register(() -> given().header("Authorization", auth(ADMIN, "cloudfront")).header("If-Match", etag) - .delete("/2020-05-31/key-value-store/" + name).then().statusCode(204)); + KeyValueStoreFixture created = keyValueStore(); + String name = created.name(); + String arn = created.arn(); + String etag = created.etag(); policy(user, allow("cloudfront:*", "*") + "," + "{\"Effect\":\"Deny\",\"Action\":\"cloudfront:DeleteKeyValueStore\",\"Resource\":\"" + arn + "\"}"); @@ -141,6 +135,53 @@ class IamRestRouteEnforcementIntegrationTest { policy(user, allow("cloudfront:DescribeKeyValueStore", arn)); as(user, "cloudfront").get("/2020-05-31/key-value-store/" + name).then().statusCode(200); } + + /** + * An {@code aws:ResourceTag} condition reads the tags CloudFront holds on the key value store a request names, so + * an allow on one team's tag lets the caller describe that team's store and not another's. + */ + @Test + void aCloudFrontResourceTagConditionReadsTheTagsOfTheKeyValueStore() { + String user = user("route-kvs-tags"); + KeyValueStoreFixture tagged = keyValueStore(); + KeyValueStoreFixture other = keyValueStore(); + tagCloudFront(tagged.arn(), "data"); + tagCloudFront(other.arn(), "web"); + + policy(user, "{\"Effect\":\"Allow\",\"Action\":\"cloudfront:DescribeKeyValueStore\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + as(user, "cloudfront").get("/2020-05-31/key-value-store/" + tagged.name()).then().statusCode(200); + refused(as(user, "cloudfront").get("/2020-05-31/key-value-store/" + other.name()).then(), + "cloudfront:DescribeKeyValueStore"); + } + + /** A CloudFront key value store an administrator created, by its name, ARN and control plane ETag. */ + private record KeyValueStoreFixture(String name, String arn, String etag) {} + + /** A key value store an administrator creates, deleted after the test. */ + private KeyValueStoreFixture keyValueStore() { + String name = "kvs-" + suffix(); + Response created = given().header("Authorization", auth(ADMIN, "cloudfront")) + .contentType("application/xml") + .body("" + name + + "") + .post("/2020-05-31/key-value-store"); + created.then().statusCode(201); + String etag = created.header("ETag"); + cleanup.register(() -> given().header("Authorization", auth(ADMIN, "cloudfront")).header("If-Match", etag) + .delete("/2020-05-31/key-value-store/" + name).then().statusCode(204)); + return new KeyValueStoreFixture(name, XmlParser.extractFirst(created.asString(), "ARN", null), etag); + } + + /** Tags the CloudFront resource {@code arn} with the team, as an administrator. */ + private static void tagCloudFront(String arn, String team) { + given().header("Authorization", auth(ADMIN, "cloudfront")).contentType("application/xml") + .queryParam("Operation", "Tag").queryParam("Resource", arn) + .body("team" + team + + "") + .post("/2020-05-31/tagging").then().statusCode(204); + } + @Test void aScheduleRequestSignedForAnotherServiceIsStillCheckedAsScheduler() { // Checked by the route it reached, not by the credential scope it was signed with: an S3