From b07c49082e16fcb548eb61d1191f3f0533c2a961 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:25:37 -0400 Subject: [PATCH] fix(ecr): give resource-tag conditions the tags of the repository a request names (#8676) The generated request resources give ECR's repository type the aws:ResourceTag/ and ecr:ResourceTag/ keys, but ECR had no StoredResourceArns, so a condition on a repository's tags saw none. EcrStoredResourceArns now answers from EcrService.storedTags, which reads the repository stored under the ARN in the account and Region it names, a pre-multi-account one of the default account in place, matched on the whole ARN. Tag writes now replace the map whole under one lock, filled one entry at a time so the listed order holds, and the field is volatile. --- docs/services/iam.md | 4 +- .../aws/core/common/StoredResourceArns.java | 6 +-- .../io/floci/aws/services/ecr/EcrService.java | 50 +++++++++++++++---- .../services/ecr/EcrStoredResourceArns.java | 37 ++++++++++++++ .../aws/services/ecr/model/Repository.java | 2 +- .../aws/services/ecr/EcrServiceTest.java | 19 +++++++ ...estResourceEnforcementIntegrationTest.java | 38 ++++++++++++++ 7 files changed, 141 insertions(+), 15 deletions(-) create mode 100644 src/main/java/io/floci/aws/services/ecr/EcrStoredResourceArns.java diff --git a/docs/services/iam.md b/docs/services/iam.md index b3e2f854f6..0a85352e25 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3157,8 +3157,8 @@ floci populates: crawlers, triggers, workflows, connections, databases, tables and other resources it tags, Step Functions for its state machines, their versions and executions (the state machine's tags) and activities, CodeBuild for its projects and report groups, Athena for its workgroups and data catalogs, Redshift Serverless for its namespaces, - workgroups and snapshots, and DynamoDB for its tables and their indexes (the table's tags). Tag keys differing - only in case are one condition key holding every value. + workgroups and snapshots, DynamoDB for its tables and their indexes (the table's tags), and ECR for its + repositories. 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 bf2cb692e2..266c9f9ac7 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -34,9 +34,9 @@ import java.util.Optional; * versions and executions, and an activity; CodeBuild, for the project a build belongs to and the tags of a project or * a report group; Athena, for the workgroup and the data catalog a request naming none uses and the tags of a * workgroup or a data catalog; Redshift Serverless, for the tags of a namespace, a workgroup or a snapshot; DynamoDB, - * for the tags of a table and its indexes); 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.

+ * for the tags of a table and its indexes; ECR, for the tags of a repository); 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/ecr/EcrService.java b/src/main/java/io/floci/aws/services/ecr/EcrService.java index 0c4bf1d94e..27ae304912 100644 --- a/src/main/java/io/floci/aws/services/ecr/EcrService.java +++ b/src/main/java/io/floci/aws/services/ecr/EcrService.java @@ -71,6 +71,7 @@ public class EcrService implements ResourceProvider, Resettable { "(?:[a-z0-9]+(?:(?:\\.|_|__|-+)[a-z0-9]+)*(?:/[a-z0-9]+" + "(?:(?:\\.|_|__|-+)[a-z0-9]+)*)*/?|ROOT)"); private static final Pattern REGISTRY_ID = Pattern.compile("[0-9]{12}"); + private static final String REPOSITORY_RESOURCE = "repository/"; private static final Pattern LAYER_DIGEST = Pattern.compile("[a-zA-Z0-9-_+.]+:[a-fA-F0-9]+"); private static final ObjectMapper MAPPER = new ObjectMapper(); /** ECR's imageTag rule, which the service model bounds at 300 characters. */ @@ -106,6 +107,9 @@ public class EcrService implements ResourceProvider, Resettable { private final EcrLayerUploads layerUploads = new EcrLayerUploads(this::discardUpload); private final Set inFlightImmutableTags = ConcurrentHashMap.newKeySet(); private final KeyedWriteLocks repositoryWriteLocks = new KeyedWriteLocks<>(); + // Held while a repository's tags are copied, changed and put in place of the map it held, which is never changed. + // The copy is put one entry at a time, as the map always was, so ListTagsForResource keeps the order it listed. + private final Object tagLock = new Object(); @Inject public EcrService(StorageFactory factory, @@ -1676,21 +1680,29 @@ public class EcrService implements ResourceProvider, Resettable { } public void tagResource(String repoName, String registryId, Map tags, String region) { - Repository repo = requireRepo(repoName, registryId, region); - if (tags != null) { - repo.getTags().putAll(tags); + synchronized (tagLock) { + Repository repo = requireRepo(repoName, registryId, region); + if (tags != null) { + Map updated = new HashMap<>(); + repo.getTags().forEach(updated::put); + tags.forEach(updated::put); + repo.setTags(updated); + } + repoStore.put(key(region, repo.getRegistryId(), repoName), repo); } - repoStore.put(key(region, repo.getRegistryId(), repoName), repo); } public void untagResource(String repoName, String registryId, List tagKeys, String region) { - Repository repo = requireRepo(repoName, registryId, region); - if (tagKeys != null) { - for (String k : tagKeys) { - repo.getTags().remove(k); + synchronized (tagLock) { + Repository repo = requireRepo(repoName, registryId, region); + if (tagKeys != null) { + Map updated = new HashMap<>(); + repo.getTags().forEach(updated::put); + tagKeys.forEach(updated::remove); + repo.setTags(updated); } + repoStore.put(key(region, repo.getRegistryId(), repoName), repo); } - repoStore.put(key(region, repo.getRegistryId(), repoName), repo); } public Map listTagsForResource(String repoName, String registryId, String region) { @@ -1698,6 +1710,26 @@ public class EcrService implements ResourceProvider, Resettable { return repo.getTags(); } + /** + * The tags of the repository stored under {@code arn} in the account and Region it names, a pre-multi-account one + * of the default account read in place, matched on the whole ARN; empty for an ARN naming nothing stored. + */ + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "ecr")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String resource = parsed.resource(); + if (!resource.startsWith(REPOSITORY_RESOURCE)) { + return Map.of(); + } + return AccountAwareStorageBackend.readInAccount(repoStore, parsed.accountId(), + key(parsed.region(), parsed.accountId(), resource.substring(REPOSITORY_RESOURCE.length()))) + .filter(repo -> arn.equals(repo.getRepositoryArn())) + .map(Repository::getTags) + .orElse(Map.of()); + } + public Repository putLifecyclePolicy(String repoName, String registryId, String policyText, String region) { validateLifecyclePolicyDocument(policyText); Repository repo = requireRepo(repoName, registryId, region); diff --git a/src/main/java/io/floci/aws/services/ecr/EcrStoredResourceArns.java b/src/main/java/io/floci/aws/services/ecr/EcrStoredResourceArns.java new file mode 100644 index 0000000000..4fa6843b7e --- /dev/null +++ b/src/main/java/io/floci/aws/services/ecr/EcrStoredResourceArns.java @@ -0,0 +1,37 @@ +package io.floci.aws.services.ecr; + +import io.floci.aws.core.common.StoredResourceArns; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** What IAM asks ECR of the resources a request names: the tags of the repository an ARN names. */ +@ApplicationScoped +public class EcrStoredResourceArns implements StoredResourceArns { + + private final EcrService ecr; + + @Inject + public EcrStoredResourceArns(EcrService ecr) { + this.ecr = ecr; + } + + @Override + public String namespace() { + return "ecr"; + } + + /** ECR mints no id into an ARN a request names by its name, so there is nothing to find. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + @Override + public Map storedTags(String arn) { + return ecr.storedTags(arn); + } +} diff --git a/src/main/java/io/floci/aws/services/ecr/model/Repository.java b/src/main/java/io/floci/aws/services/ecr/model/Repository.java index 4a10dfca05..34bb67c281 100644 --- a/src/main/java/io/floci/aws/services/ecr/model/Repository.java +++ b/src/main/java/io/floci/aws/services/ecr/model/Repository.java @@ -25,7 +25,7 @@ public class Repository { private String kmsKey; private String lifecyclePolicyText; private String repositoryPolicyText; - private Map tags = new HashMap<>(); + private volatile Map tags = new HashMap<>(); public Repository() {} diff --git a/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java b/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java index b2d12e79ba..0f8fd47f34 100644 --- a/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java +++ b/src/test/java/io/floci/aws/services/ecr/EcrServiceTest.java @@ -338,6 +338,25 @@ class EcrServiceTest { assertEquals("platform", repo.getTags().get("team")); } + @Test + void storedTagsAreTheTagsOfTheRepositoryTheArnNamesAndTaggingPutsANewMapInPlaceOfTheHeldOne() { + String arn = service.createRepository(REPO, null, null, null, null, null, Map.of("team", "data"), REGION) + .getRepositoryArn(); + Map held = service.listTagsForResource(REPO, null, REGION); + + assertEquals(Map.of("team", "data"), service.storedTags(arn)); + assertEquals(Map.of(), service.storedTags(arn + "-other")); + assertEquals(Map.of(), service.storedTags(arn.replace(ACCOUNT, "111111111111"))); + assertEquals(Map.of(), service.storedTags(arn.replace(REGION, "us-west-2"))); + assertEquals(Map.of(), service.storedTags(arn.replace("arn:aws:", "arn:aws-cn:"))); + + service.tagResource(REPO, null, Map.of("stage", "prod"), REGION); + service.untagResource(REPO, null, List.of("team"), REGION); + + assertEquals(Map.of("stage", "prod"), service.storedTags(arn)); + assertEquals(Map.of("team", "data"), held); + } + @Test void immutableRepositoryIsMarkedForDataPlaneTagProtection() { service.createRepository(REPO, null, "IMMUTABLE", null, null, null, null, REGION); 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 4a7b58708b..459a624026 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -3,6 +3,7 @@ package io.floci.aws.services.iam; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import io.floci.aws.services.ecr.registry.EcrRegistryManager; import io.floci.aws.services.redshift.model.Endpoint; import io.floci.aws.services.redshiftserverless.RedshiftServerlessRuntime; import io.floci.aws.testing.AwsTestClients; @@ -94,6 +95,10 @@ class IamRequestResourceEnforcementIntegrationTest { @InjectMock RedshiftServerlessRuntime runtime; + /** ECR's backing registry is not needed to check a request on a repository's metadata, so none starts. */ + @InjectMock + EcrRegistryManager ecrRegistry; + @BeforeAll static void configureRestAssured() { RestAssuredJsonUtils.configureAwsContentTypes(); @@ -636,6 +641,39 @@ class IamRequestResourceEnforcementIntegrationTest { + "\",\"tags\":[{\"Key\":\"a\",\"Value\":\"b\"}]}").post("/").then(), "ecr:TagResource"); } + /** + * An {@code ecr:ResourceTag} or {@code aws:ResourceTag} condition reads the tags ECR holds on the repository a + * request names, so an allow on one team's tag lets the caller read that team's repository and not another's. + */ + @Test + void anEcrResourceTagConditionReadsTheTagsOfTheRepository() { + String tagged = ecrRepository("res-tag-repo-" + suffix(), "data"); + String other = ecrRepository("res-tag-repo-" + suffix(), "web"); + String arns = "arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/"; + + User user = user("res-ecr-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":\"ecr:DescribeRepositories\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"ecr:ResourceTag/team\":\"data\"}}}," + + "{\"Effect\":\"Allow\",\"Action\":\"ecr:ListTagsForResource\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + describeRepositories(user, tagged).statusCode(200); + refusedJson(describeRepositories(user, other), "ecr:DescribeRepositories"); + send(user, "ecr", "AmazonEC2ContainerRegistry_V20150921.ListTagsForResource", "1.1", + "{\"resourceArn\":\"" + arns + tagged + "\"}").statusCode(200); + refusedJson(send(user, "ecr", "AmazonEC2ContainerRegistry_V20150921.ListTagsForResource", "1.1", + "{\"resourceArn\":\"" + arns + other + "\"}"), "ecr:ListTagsForResource"); + } + + /** An ECR repository of the name, tagged with the team, deleted afterwards. */ + private String ecrRepository(String name, String team) { + adminJson("ecr", "AmazonEC2ContainerRegistry_V20150921.CreateRepository").body("{\"repositoryName\":\"" + + name + "\",\"tags\":[{\"Key\":\"team\",\"Value\":\"" + team + "\"}]}").post("/").then() + .statusCode(200); + cleanup.register(() -> adminJson("ecr", "AmazonEC2ContainerRegistry_V20150921.DeleteRepository") + .body("{\"repositoryName\":\"" + name + "\",\"force\":true}").post("/")); + return name; + } + @Test void aDeliveryStreamIsCheckedOnTheArnItsNameGives() { String name = "res-stream-" + suffix();