diff --git a/docs/services/iam.md b/docs/services/iam.md index 2646c9fc57..80746ca9ad 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3148,9 +3148,9 @@ floci populates: CloudFormation for its stacks, stack sets and change sets, Lambda for its functions, their versions and aliases (the function's tags), event source mappings, web functions, their revisions and endpoints (the web function's tags), MicroVM images and network connectors, Glue for its schema registries and schemas and for the jobs, - crawlers, triggers, workflows, connections, databases, tables and other resources it tags, and Step Functions for - its state machines, their versions and executions (the state machine's tags) and activities. Tag keys differing - only in case are one condition key holding every value. + 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, and CodeBuild for its + projects and report groups. 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 2d0e7ff4d7..ed2d2eb274 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -31,9 +31,10 @@ import java.util.Optional; * table bucket or a table; Lambda, for the layer version a layer version ARN selects, the image of a MicroVM and the * execution of a callback, and the tags of a function, an event source mapping, a web function, a MicroVM image or a * network connector; Glue, for the tags of a resource it tags; Step Functions, for the tags of a state machine, its - * versions and executions, and an activity); 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.

+ * versions and executions, and an activity; CodeBuild, for the project a build belongs to and the tags of a project or + * a report group); 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/codebuild/CodeBuildService.java b/src/main/java/io/floci/aws/services/codebuild/CodeBuildService.java index 74386a9ee7..44c164177a 100644 --- a/src/main/java/io/floci/aws/services/codebuild/CodeBuildService.java +++ b/src/main/java/io/floci/aws/services/codebuild/CodeBuildService.java @@ -7,7 +7,9 @@ import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.EpochSeconds; +import io.floci.aws.core.storage.AccountAwareStorageBackend; import io.floci.aws.core.storage.StorageBackedMap; +import io.floci.aws.core.storage.StorageBackend; import io.floci.aws.core.storage.StorageFactory; import io.floci.aws.services.codebuild.model.Build; import io.floci.aws.services.codebuild.model.BuildPhase; @@ -24,9 +26,11 @@ import jakarta.inject.Inject; import java.time.Instant; import java.util.ArrayList; import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -43,6 +47,9 @@ public class CodeBuildService { private Map> projects = new ConcurrentHashMap<>(); // key: region -> arn -> report group private Map> reportGroups = new ConcurrentHashMap<>(); + /** The backends of {@link #projects} and {@link #reportGroups}, read in another account than the caller's. */ + private StorageBackend> projectStorage; + private StorageBackend> reportGroupStorage; // key: region -> arn -> source credential (token is stored but never returned) private Map> sourceCredentials = new ConcurrentHashMap<>(); // key: account:region -> buildId -> build (transient: builds are runtime state) @@ -70,10 +77,12 @@ public class CodeBuildService { if (storageFactory == null) { return; // keeps non-CDI unit tests working } - this.projects = storageBacked("codebuild-projects.json", + this.projectStorage = storageFactory.create("codebuild", "codebuild-projects.json", new TypeReference>>() {}); - this.reportGroups = storageBacked("codebuild-report-groups.json", + this.projects = new StorageBackedMap<>(projectStorage); + this.reportGroupStorage = storageFactory.create("codebuild", "codebuild-report-groups.json", new TypeReference>>() {}); + this.reportGroups = new StorageBackedMap<>(reportGroupStorage); this.sourceCredentials = storageBacked("codebuild-source-credentials.json", new TypeReference>>() {}); this.persistedBuildCounters = storageBacked("codebuild-build-counters.json", @@ -106,6 +115,48 @@ public class CodeBuildService { } } + /** + * The tags of the project or the report group stored under {@code arn} in the account and Region it names, read in + * place and matched on the whole ARN; empty for an ARN naming nothing stored. + */ + public Map storedTags(String arn) { + if (!AwsArnUtils.isArnFor(arn, "codebuild")) { + return Map.of(); + } + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + String resource = parsed.resource(); + List> tags = null; + if (resource.startsWith("project/")) { + tags = inRegion(projectStorage, projects, parsed.accountId(), parsed.region()) + .map(byName -> byName.get(resource.substring("project/".length()))) + .filter(project -> arn.equals(project.getArn())) + .map(Project::getTags) + .orElse(null); + } else if (resource.startsWith("report-group/")) { + tags = inRegion(reportGroupStorage, reportGroups, parsed.accountId(), parsed.region()) + .map(byArn -> byArn.get(arn)) + .map(ReportGroup::getTags) + .orElse(null); + } + Map byKey = new LinkedHashMap<>(); + if (tags != null) { + for (Map tag : tags) { + if (tag.get("key") instanceof String key && tag.get("value") instanceof String value) { + byKey.put(key, value); + } + } + } + return byKey; + } + + /** The resources stored for the Region in the account, read in place; from {@code local} without storage. */ + private static Optional> inRegion(StorageBackend> storage, + Map> local, String account, + String region) { + return storage == null ? Optional.ofNullable(local.get(region)) + : AccountAwareStorageBackend.readInAccount(storage, account, region); + } + private Map projectsFor(String region) { return projects.computeIfAbsent(region, r -> new ConcurrentHashMap<>()); } diff --git a/src/main/java/io/floci/aws/services/codebuild/CodeBuildStoredResourceArns.java b/src/main/java/io/floci/aws/services/codebuild/CodeBuildStoredResourceArns.java index c4120d0ffb..52ef599ce9 100644 --- a/src/main/java/io/floci/aws/services/codebuild/CodeBuildStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/codebuild/CodeBuildStoredResourceArns.java @@ -8,11 +8,13 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import java.util.List; +import java.util.Map; import java.util.Optional; /** * What IAM asks CodeBuild of the resources a request names: the project the caller's build of an id belongs to, as - * the service stores them, which CodeBuild checks a call naming the build on. + * the service stores them, which CodeBuild checks a call naming the build on, and the tags of a project or a report + * group. */ @ApplicationScoped public class CodeBuildStoredResourceArns implements StoredResourceArns { @@ -49,4 +51,9 @@ public class CodeBuildStoredResourceArns implements StoredResourceArns { .distinct() .toList(); } + + @Override + public Map storedTags(String arn) { + return codeBuild.storedTags(arn); + } } diff --git a/src/main/java/io/floci/aws/services/codebuild/model/Project.java b/src/main/java/io/floci/aws/services/codebuild/model/Project.java index 9b7011c34f..91b1114252 100644 --- a/src/main/java/io/floci/aws/services/codebuild/model/Project.java +++ b/src/main/java/io/floci/aws/services/codebuild/model/Project.java @@ -24,7 +24,7 @@ public class Project { private Integer timeoutInMinutes; private Integer queuedTimeoutInMinutes; private String encryptionKey; - private List> tags; + private volatile List> tags; private Double created; private Double lastModified; private Map logsConfig; diff --git a/src/main/java/io/floci/aws/services/codebuild/model/ReportGroup.java b/src/main/java/io/floci/aws/services/codebuild/model/ReportGroup.java index 5af7bc0d12..d3ee21ec2c 100644 --- a/src/main/java/io/floci/aws/services/codebuild/model/ReportGroup.java +++ b/src/main/java/io/floci/aws/services/codebuild/model/ReportGroup.java @@ -17,7 +17,7 @@ public class ReportGroup { private Map exportConfig; private Double created; private Double lastModified; - private List> tags; + private volatile List> tags; private String status; public String getArn() { return arn; } diff --git a/src/test/java/io/floci/aws/services/codebuild/CodeBuildStoredTagsTest.java b/src/test/java/io/floci/aws/services/codebuild/CodeBuildStoredTagsTest.java new file mode 100644 index 0000000000..a394dc8953 --- /dev/null +++ b/src/test/java/io/floci/aws/services/codebuild/CodeBuildStoredTagsTest.java @@ -0,0 +1,66 @@ +package io.floci.aws.services.codebuild; + +import io.floci.aws.config.EmulatorConfig; +import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.StorageFactory; +import io.floci.aws.services.codebuild.model.Project; +import io.floci.aws.services.codebuild.model.ProjectArtifacts; +import io.floci.aws.services.codebuild.model.ProjectEnvironment; +import io.floci.aws.services.codebuild.model.ProjectSource; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class CodeBuildStoredTagsTest { + + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + + private CodeBuildService service; + + @BeforeEach + void setUp() { + StorageFactory storageFactory = mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenAnswer(inv -> AccountAwareStorageBackend.inMemory(ACCOUNT)); + service = new CodeBuildService(mock(CodeBuildRunner.class), mock(EmulatorConfig.class), storageFactory); + service.initializeStorage(); + } + + @Test + void storedTagsReadTheProjectOrTheReportGroupTheArnNamesInItsAccountAndRegion() { + String project = createProject("web", List.of(tag("team", "data"))).getArn(); + String reportGroup = service.createReportGroup(REGION, ACCOUNT, "tests", "TEST", + Map.of("exportConfigType", "NO_EXPORT"), List.of(tag("team", "qa"))).getArn(); + + assertEquals(Map.of("team", "data"), service.storedTags(project)); + assertEquals(Map.of("team", "qa"), service.storedTags(reportGroup)); + assertEquals(Map.of(), service.storedTags(project.replace("web", "api"))); + assertEquals(Map.of(), service.storedTags(project.replace(ACCOUNT, "111111111111"))); + assertEquals(Map.of(), service.storedTags(project.replace(REGION, "us-west-2"))); + assertEquals(Map.of(), service.storedTags(reportGroup.replace(ACCOUNT, "111111111111"))); + assertEquals(Map.of(), service.storedTags(createProject("untagged", null).getArn())); + } + + private Project createProject(String name, List> tags) { + ProjectSource source = new ProjectSource(); + source.setType("NO_SOURCE"); + ProjectArtifacts artifacts = new ProjectArtifacts(); + artifacts.setType("NO_ARTIFACTS"); + return service.createProject(REGION, ACCOUNT, name, null, source, null, null, artifacts, null, + new ProjectEnvironment(), "arn:aws:iam::" + ACCOUNT + ":role/codebuild", null, null, null, tags, + null, null, null); + } + + private static Map tag(String key, String value) { + return Map.of("key", key, "value", value); + } +} 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 3bbb3fbae3..6054717e10 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -901,6 +901,51 @@ class IamRequestResourceEnforcementIntegrationTest { .body(containsString("ResourceNotFoundException")); } + /** + * An {@code aws:ResourceTag} condition reads the tags CodeBuild holds on a project and a report group, so an allow + * on one team's tag lets the caller read that team's and not another's. + */ + @Test + void aCodeBuildResourceTagConditionReadsTheTagsOfTheProjectAndTheReportGroup() { + String tagged = codeBuildProject("res-tag-project-" + suffix(), "data"); + String other = codeBuildProject("res-tag-project-" + suffix(), "web"); + String taggedGroup = codeBuildReportGroup("res-tag-group-" + suffix(), "data"); + String otherGroup = codeBuildReportGroup("res-tag-group-" + suffix(), "web"); + + User user = user("res-codebuild-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":[\"codebuild:BatchGetProjects\"," + + "\"codebuild:BatchGetReportGroups\"],\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + codeBuild(user, "BatchGetProjects", "{\"names\":[\"" + tagged + "\"]}").statusCode(200); + refusedJson(codeBuild(user, "BatchGetProjects", "{\"names\":[\"" + other + "\"]}"), + "codebuild:BatchGetProjects"); + codeBuild(user, "BatchGetReportGroups", "{\"reportGroupArns\":[\"" + taggedGroup + "\"]}").statusCode(200); + refusedJson(codeBuild(user, "BatchGetReportGroups", "{\"reportGroupArns\":[\"" + otherGroup + "\"]}"), + "codebuild:BatchGetReportGroups"); + } + + private String codeBuildProject(String name, String team) { + adminJson("codebuild", "CodeBuild_20161006.CreateProject").body("{\"name\":\"" + name + + "\",\"source\":{\"type\":\"NO_SOURCE\",\"buildspec\":\"version: 0.2\"}," + + "\"artifacts\":{\"type\":\"NO_ARTIFACTS\"},\"environment\":{\"type\":\"LINUX_CONTAINER\"," + + "\"image\":\"aws/codebuild/standard:7.0\",\"computeType\":\"BUILD_GENERAL1_SMALL\"}," + + "\"serviceRole\":\"arn:aws:iam::" + ACCOUNT + ":role/codebuild-role\"," + + "\"tags\":[{\"key\":\"team\",\"value\":\"" + team + "\"}]}").post("/").then().statusCode(200); + cleanup.register(() -> adminJson("codebuild", "CodeBuild_20161006.DeleteProject") + .body("{\"name\":\"" + name + "\"}").post("/")); + return name; + } + + private String codeBuildReportGroup(String name, String team) { + String arn = adminJson("codebuild", "CodeBuild_20161006.CreateReportGroup").body("{\"name\":\"" + name + + "\",\"type\":\"TEST\",\"exportConfig\":{\"exportConfigType\":\"NO_EXPORT\"}," + + "\"tags\":[{\"key\":\"team\",\"value\":\"" + team + "\"}]}").post("/").then().statusCode(200) + .extract().path("reportGroup.arn"); + cleanup.register(() -> adminJson("codebuild", "CodeBuild_20161006.DeleteReportGroup") + .body("{\"arn\":\"" + arn + "\"}").post("/")); + return arn; + } + /** A Managed Service for Apache Flink application is checked on the ARN its name gives. */ @Test void anApplicationIsCheckedOnTheArnItsNameGives() {