From 933b6179616964f695ff879c5d76b4b96fdf9ef2 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:19:15 -0400 Subject: [PATCH] fix(codepipeline): give resource-tag conditions the tags of the pipeline a request names (#8839) The generated request resources give CodePipeline's pipeline, webhook and actiontype types the aws:ResourceTag/ key, but no service answered the codepipeline namespace's stored tags, so a condition on their tags saw none. CodePipelineService now answers it, in the request's account and in place: a pipeline under its name and a webhook under its name, each matched on the ARN it recorded, and a custom action type under the key its ARN gives, as the tag handlers find it. A stage or an action ARN reads nothing. Tag writes already replace the map under the resource's lock; the tags fields are now volatile. --- docs/services/iam.md | 4 +- .../aws/core/common/StoredResourceArns.java | 8 +- .../codepipeline/CodePipelineService.java | 79 ++++++++++++++++++- .../model/CodePipelinePipeline.java | 2 +- .../model/CodePipelineStoredItem.java | 2 +- .../codepipeline/CodePipelineServiceTest.java | 78 ++++++++++++++++++ ...estResourceEnforcementIntegrationTest.java | 58 ++++++++++---- 7 files changed, 204 insertions(+), 27 deletions(-) diff --git a/docs/services/iam.md b/docs/services/iam.md index 8099dd99a4..67618ca98c 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3356,8 +3356,8 @@ floci populates: 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, Timestream for InfluxDB for its DB instances, DB clusters, parameter groups and backups, CloudTrail for its trails, Budgets for its budgets and budget - actions, and AWS FIS for its experiment templates, experiments and actions. Tag keys differing only in case are one - condition key holding every value. + actions, AWS FIS for its experiment templates, experiments and actions, and CodePipeline for its pipelines, webhooks + and custom action types. 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 b326ecd542..fde2557f6b 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -49,10 +49,10 @@ import java.util.Optional; * 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; CloudTrail, for the tags of a trail; Budgets, for - * the tags of a budget or a budget action; AWS FIS, for the tags of an experiment template, an experiment or an - * action); 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.

+ * the tags of a budget or a budget action; AWS FIS, for the tags of an experiment template, an experiment or an action; + * CodePipeline, for the tags of a pipeline, a webhook or a custom action type); 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/codepipeline/CodePipelineService.java b/src/main/java/io/floci/aws/services/codepipeline/CodePipelineService.java index 1ea70813f8..9d6fae12ea 100644 --- a/src/main/java/io/floci/aws/services/codepipeline/CodePipelineService.java +++ b/src/main/java/io/floci/aws/services/codepipeline/CodePipelineService.java @@ -10,6 +10,7 @@ import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.DeadlineCharSequence; import io.floci.aws.core.common.EpochSeconds; +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; @@ -77,9 +78,13 @@ import java.util.zip.InflaterInputStream; import java.util.zip.ZipEntry; @ApplicationScoped -public class CodePipelineService { +public class CodePipelineService implements StoredResourceArns { private static final Logger LOG = Logger.getLogger(CodePipelineService.class); private static final String DEFAULT_EXECUTION_MODE = "SUPERSEDED"; + /** What a custom action type's ARN resource starts with, its Owner/Category/Provider/Version following. */ + private static final String ACTION_TYPE_RESOURCE = "actiontype:"; + /** What a webhook's ARN resource starts with, its name following. */ + private static final String WEBHOOK_RESOURCE = "webhook:"; private static final String DEFAULT_PIPELINE_TYPE = "V1"; private static final int MAX_ACTIVE_EXECUTIONS = 50; private static final long DEFAULT_WORKER_POLL_INTERVAL_MS = 100L; @@ -1456,7 +1461,7 @@ public class CodePipelineService { ObjectNode item = mapper.createObjectNode(); item.set("definition", webhook.deepCopy()); item.put("url", "http://localhost:4566/codepipeline/webhooks/" + name); - item.put("arn", AwsArnUtils.Arn.of("codepipeline", region, account, "webhook:" + name).toString()); + item.put("arn", AwsArnUtils.Arn.of("codepipeline", region, account, WEBHOOK_RESOURCE + name).toString()); if (request.path("tags").isArray() && !request.path("tags").isEmpty()) { item.set("tags", request.path("tags").deepCopy()); } @@ -1540,11 +1545,77 @@ public class CodePipelineService { }); } + @Override + public String namespace() { + return "codepipeline"; + } + + /** A request names a pipeline, a webhook or an action type by its name or its id, which its ARN carries whole. */ + @Override + public Optional find(String type, List names, String region) { + return Optional.empty(); + } + + /** + * The tags of the pipeline, the webhook or the custom action type 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 Region the + * ARN names, a record stored before storage was account-aware included: a pipeline under its name and a webhook + * under its name, each matched on the whole ARN it recorded, and an action type under the key its ARN gives, as + * the tag handlers find it, the type recording no ARN of its own. A webhook's tags are the ones PutWebhook gave + * it. A stage's or an action's ARN reads nothing, Floci holding no tags of their own. Tags are replaced by a new + * map under the resource's lock, never changed in place, so the read is of one whole set. + */ + @Override + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "codepipeline")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String account = pipelineStore.accountId(); + if (!parsed.accountId().equals(account)) { + return Map.of(); + } + String resource = parsed.resource(); + Map tags; + if (resource.startsWith(ACTION_TYPE_RESOURCE)) { + tags = actionTypeKey(account, parsed.region(), arn) + .flatMap(key -> AccountAwareStorageBackend.readInAccount(itemStore, account, key)) + .map(CodePipelineStoredItem::getTags) + .orElse(Map.of()); + } else if (resource.startsWith(WEBHOOK_RESOURCE)) { + tags = AccountAwareStorageBackend.readInAccount(itemStore, account, + itemKey(parsed.region(), "webhook", resource.substring(WEBHOOK_RESOURCE.length()))) + .map(CodePipelineStoredItem::getData) + .filter(data -> arn.equals(data.path("arn").asText(null))) + .map(data -> webhookTags(data.path("tags"))) + .orElse(Map.of()); + } else if (resource.indexOf('/') < 0) { + tags = AccountAwareStorageBackend.readInAccount(pipelineStore, account, + pipelineKey(parsed.region(), resource)) + .filter(pipeline -> arn.equals(pipeline.getArn())) + .map(CodePipelinePipeline::getTags) + .orElse(Map.of()); + } else { + tags = Map.of(); + } + Map copy = new LinkedHashMap<>(); + tags.forEach((key, value) -> copy.put(key, value == null ? "" : value)); + return copy; + } + + /** The {@code key}/{@code value} pairs of the tags PutWebhook stored with a webhook. */ + private static Map webhookTags(JsonNode tags) { + Map read = new LinkedHashMap<>(); + tags.forEach(tag -> read.put(tag.path("key").asText(), tag.path("value").asText(""))); + return read; + } + private Optional actionTypeKey(String account, String region, String arn) { return AwsArnUtils.parseIfArnIn(arn, "codepipeline", region) - .filter(parsed -> account.equals(parsed.accountId()) && parsed.resource().startsWith("actiontype:")) + .filter(parsed -> account.equals(parsed.accountId()) + && parsed.resource().startsWith(ACTION_TYPE_RESOURCE)) // The ARN names the type as Owner/Category/Provider/Version. - .map(parsed -> parsed.resource().substring("actiontype:".length()).split("/")) + .map(parsed -> parsed.resource().substring(ACTION_TYPE_RESOURCE.length()).split("/")) .filter(id -> id.length == 4) .map(id -> itemKey(region, "action", actionTypeId(id[1], id[0], id[2], id[3]))); } diff --git a/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelinePipeline.java b/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelinePipeline.java index b57a118414..6f46d47755 100644 --- a/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelinePipeline.java +++ b/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelinePipeline.java @@ -21,7 +21,7 @@ public class CodePipelinePipeline { private Double created; private Double updated; private JsonNode declaration; - private Map tags = new LinkedHashMap<>(); + private volatile Map tags = new LinkedHashMap<>(); private Map transitions = new LinkedHashMap<>(); public String getAccountId() { diff --git a/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelineStoredItem.java b/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelineStoredItem.java index 88150525ea..e183050f5e 100644 --- a/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelineStoredItem.java +++ b/src/main/java/io/floci/aws/services/codepipeline/model/CodePipelineStoredItem.java @@ -21,7 +21,7 @@ public class CodePipelineStoredItem { private Double created; private Double updated; private JsonNode data; - private Map tags = new LinkedHashMap<>(); + private volatile Map tags = new LinkedHashMap<>(); public String getAccountId() { return accountId; diff --git a/src/test/java/io/floci/aws/services/codepipeline/CodePipelineServiceTest.java b/src/test/java/io/floci/aws/services/codepipeline/CodePipelineServiceTest.java index 73d14fa95f..5e6f536ee1 100644 --- a/src/test/java/io/floci/aws/services/codepipeline/CodePipelineServiceTest.java +++ b/src/test/java/io/floci/aws/services/codepipeline/CodePipelineServiceTest.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsException; 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.codebuild.CodeBuildService; import io.floci.aws.services.codebuild.model.Build; @@ -55,7 +56,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -798,6 +801,81 @@ class CodePipelineServiceTest { } } + /** + * IAM's lookup reads the tags of the pipeline, the webhook or the custom action type the ARN names, as the tag + * calls and PutWebhook leave them, and nothing for a stage, another account's, another Region's or an unknown one. + */ + @Test + void storedTagsAreTheTagsOfThePipelineWebhookOrActionTypeTheArnNames() throws Exception { + String pipelineArn = "arn:aws:codepipeline:us-east-1:000000000000:stored"; + handle("CreatePipeline", pipelineRequest("stored", "[{\"key\": \"team\", \"value\": \"web\"}]")); + handle("TagResource", "{\"resourceArn\": \"" + pipelineArn + + "\", \"tags\": [{\"key\": \"team\", \"value\": \"data\"}, {\"key\": \"env\", \"value\": \"dev\"}]}"); + handle("UntagResource", "{\"resourceArn\": \"" + pipelineArn + "\", \"tagKeys\": [\"env\"]}"); + String actionTypeArn = "arn:aws:codepipeline:us-east-1:000000000000:actiontype:Custom/Build/StoredProvider/1"; + handle("CreateCustomActionType", customActionTypeRequest("StoredProvider", 1)); + handle("PutWebhook", """ + {"webhook": {"name": "stored-hook", "targetPipeline": "stored", "targetAction": "ManualApproval"}, + "tags": [{"key": "team", "value": "ops"}]} + """); + String webhookArn = "arn:aws:codepipeline:us-east-1:000000000000:webhook:stored-hook"; + + assertEquals("codepipeline", service.namespace()); + assertEquals(Map.of("team", "data"), service.storedTags(pipelineArn)); + assertEquals(Map.of("k0", "v"), service.storedTags(actionTypeArn)); + assertEquals(Map.of("team", "ops"), service.storedTags(webhookArn)); + assertTrue(service.storedTags(pipelineArn + "/Approve").isEmpty()); + assertTrue(service.storedTags(pipelineArn.replace(ACCOUNT, "111122223333")).isEmpty()); + assertTrue(service.storedTags(pipelineArn.replace(REGION, "us-west-2")).isEmpty()); + assertTrue(service.storedTags(actionTypeArn.replace(REGION, "us-west-2")).isEmpty()); + assertTrue(service.storedTags(webhookArn.replace("stored-hook", "missing")).isEmpty()); + assertTrue(service.storedTags(pipelineArn.replace(":stored", ":missing")).isEmpty()); + assertTrue(service.storedTags("arn:aws:codebuild:us-east-1:000000000000:project/stored").isEmpty()); + } + + /** A pipeline stored before storage was account-aware is read in place: the lookup migrates nothing. */ + @Test + void storedTagsReadAPreAccountAwarePipelineInPlace() { + InMemoryStorage raw = new InMemoryStorage<>(); + StorageFactory factory = mock(StorageFactory.class); + doAnswer(invocation -> AccountAwareStorageBackend.inMemory(ACCOUNT)) + .when(factory).create(anyString(), anyString(), any()); + doReturn(new AccountAwareStorageBackend<>(raw, null, ACCOUNT)) + .when(factory).create(anyString(), eq("codepipeline-pipelines.json"), any()); + CodePipelineService legacyState = new CodePipelineService(factory, mapper, mock(CodeBuildService.class), + mock(CodeDeployService.class), mock(LambdaService.class), mock(S3Service.class), + configWithPollInterval(500L)); + CodePipelinePipeline legacy = new CodePipelinePipeline(); + legacy.setName("legacy"); + legacy.setRegion(REGION); + legacy.setArn("arn:aws:codepipeline:us-east-1:000000000000:legacy"); + legacy.setTags(Map.of("team", "data")); + raw.put(REGION + ":legacy", legacy); + + assertEquals(Map.of("team", "data"), legacyState.storedTags(legacy.getArn())); + assertEquals(Set.of(REGION + ":legacy"), raw.keys()); + } + + /** A two-stage pipeline of manual approvals named {@code name}, with the {@code tags} list. */ + private static String pipelineRequest(String name, String tags) { + return """ + { + "pipeline": { + "name": "%s", + "roleArn": "arn:aws:iam::000000000000:role/codepipeline-role", + "artifactStore": {"type": "S3", "location": "codepipeline-artifacts"}, + "stages": [ + {"name": "Approve", "actions": [{"name": "ManualApproval", "actionTypeId": + {"category": "Approval", "owner": "AWS", "provider": "Manual", "version": "1"}}]}, + {"name": "Complete", "actions": [{"name": "ManualApprovalComplete", "actionTypeId": + {"category": "Approval", "owner": "AWS", "provider": "Manual", "version": "1"}}]} + ] + }, + "tags": %s + } + """.formatted(name, tags); + } + private static String customActionTypeRequest(String provider, int tagCount) { StringJoiner tags = new StringJoiner(", "); for (int i = 0; i < tagCount; i++) { 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 e1c93a0a65..661b56edaf 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -988,10 +988,7 @@ class IamRequestResourceEnforcementIntegrationTest { @Test void aPipelineAndAWebhookAreCheckedOnTheArnsTheirNamesGive() { String name = "res-pipeline-" + suffix(); - adminJson("codepipeline", "CodePipeline_20150709.CreatePipeline").body(pipeline(name)).post("/") - .then().statusCode(200); - cleanup.register(() -> adminJson("codepipeline", "CodePipeline_20150709.DeletePipeline") - .body("{\"name\":\"" + name + "\"}").post("/")); + createPipeline(name, null); String pipelineArn = adminJson("codepipeline", "CodePipeline_20150709.GetPipeline") .body("{\"name\":\"" + name + "\"}").post("/").then().statusCode(200).extract().path("metadata.pipelineArn"); assertEquals("arn:aws:codepipeline:" + REGION + ":" + ACCOUNT + ":" + name, pipelineArn); @@ -1015,6 +1012,38 @@ class IamRequestResourceEnforcementIntegrationTest { codePipeline(user, "DeleteWebhook", "{\"name\":\"" + hook + "\"}").statusCode(200); } + /** + * An {@code aws:ResourceTag} condition reads the tags CodePipeline holds on the pipeline a request names, as + * TagResource leaves them, so an allow on one team's tag lets the caller read that team's pipeline and not + * another's. + */ + @Test + void aCodePipelineResourceTagConditionReadsTheTagsOfThePipeline() { + String web = "[{\"key\":\"team\",\"value\":\"web\"}]"; + String tagged = "res-pipeline-tagged-" + suffix(); + String other = "res-pipeline-other-" + suffix(); + createPipeline(tagged, web); + createPipeline(other, web); + adminJson("codepipeline", "CodePipeline_20150709.TagResource") + .body("{\"resourceArn\":\"arn:aws:codepipeline:" + REGION + ":" + ACCOUNT + ":" + tagged + + "\",\"tags\":[{\"key\":\"team\",\"value\":\"data\"}]}") + .post("/").then().statusCode(200); + + User user = user("res-pipeline-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":\"codepipeline:GetPipeline\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + codePipeline(user, "GetPipeline", "{\"name\":\"" + tagged + "\"}").statusCode(200); + refusedJson(codePipeline(user, "GetPipeline", "{\"name\":\"" + other + "\"}"), "codepipeline:GetPipeline"); + } + + /** Creates the pipeline {@code name} as an administrator, with the {@code tags} list if any, deleted afterwards. */ + private void createPipeline(String name, String tags) { + adminJson("codepipeline", "CodePipeline_20150709.CreatePipeline").body(pipeline(name, tags)).post("/") + .then().statusCode(200); + cleanup.register(() -> adminJson("codepipeline", "CodePipeline_20150709.DeletePipeline") + .body("{\"name\":\"" + name + "\"}").post("/")); + } + /** {@code StartPipelineExecution} names its pipeline by a bare {@code name}, on which it is checked. */ @Test void aPipelineExecutionIsCheckedOnThePipelineItsNameGives() { @@ -1037,12 +1066,8 @@ class IamRequestResourceEnforcementIntegrationTest { void anUpdateIsCheckedOnThePipelineItNamesNotOneItsRoleHolds() { String allowed = "res-pipeline-" + suffix(); String other = allowed + "-other"; - for (String name : List.of(allowed, other)) { - adminJson("codepipeline", "CodePipeline_20150709.CreatePipeline").body(pipeline(name)).post("/") - .then().statusCode(200); - cleanup.register(() -> adminJson("codepipeline", "CodePipeline_20150709.DeletePipeline") - .body("{\"name\":\"" + name + "\"}").post("/")); - } + createPipeline(allowed, null); + createPipeline(other, null); String allowedArn = "arn:aws:codepipeline:" + REGION + ":" + ACCOUNT + ":" + allowed; User user = user("res-pipeline-update"); user.policy(allowOn("codepipeline:UpdatePipeline", allowedArn) + "," @@ -1056,10 +1081,7 @@ class IamRequestResourceEnforcementIntegrationTest { @Test void aWebhooksTagsAreCheckedOnTheWebhookNotItsPipeline() { String name = "res-pipeline-" + suffix(); - adminJson("codepipeline", "CodePipeline_20150709.CreatePipeline").body(pipeline(name)).post("/") - .then().statusCode(200); - cleanup.register(() -> adminJson("codepipeline", "CodePipeline_20150709.DeletePipeline") - .body("{\"name\":\"" + name + "\"}").post("/")); + createPipeline(name, null); String hook = "res-hook-" + suffix(); String codePipeline = "arn:aws:codepipeline:" + REGION + ":" + ACCOUNT + ":"; User user = user("res-webhook-tags"); @@ -2799,12 +2821,18 @@ class IamRequestResourceEnforcementIntegrationTest { /** A pipeline with a source and a build stage, the two stages CodePipeline requires. */ private static String pipeline(String name) { + return pipeline(name, null); + } + + /** A CreatePipeline or UpdatePipeline body for the pipeline {@code name}, with the {@code tags} list if any. */ + private static String pipeline(String name, String tags) { return "{\"pipeline\":{\"name\":\"" + name + "\",\"roleArn\":\"arn:aws:iam::" + ACCOUNT + ":role/codepipeline-role\"," + "\"artifactStore\":{\"type\":\"S3\",\"location\":\"codepipeline-artifacts\"},\"stages\":[" + "{\"name\":\"Source\",\"actions\":[{\"name\":\"SourceAction\",\"actionTypeId\":{\"category\":\"Source\"," + "\"owner\":\"AWS\",\"provider\":\"S3\",\"version\":\"1\"},\"runOrder\":1}]}," + "{\"name\":\"Build\",\"actions\":[{\"name\":\"BuildAction\",\"actionTypeId\":{\"category\":\"Build\"," - + "\"owner\":\"AWS\",\"provider\":\"CodeBuild\",\"version\":\"1\"},\"runOrder\":1}]}]}}"; + + "\"owner\":\"AWS\",\"provider\":\"CodeBuild\",\"version\":\"1\"},\"runOrder\":1}]}]}" + + (tags == null ? "" : ",\"tags\":" + tags) + "}"; } private static RequestSpecification tagged(RequestSpecification request) {