From 5548bb78eb4babd9ac7718c161c347c9acd954ed Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:21:41 -0400 Subject: [PATCH] fix(emr): give resource-tag conditions the tags of the session a request names (#8878) The generated request resources give EMR's session type the aws:ResourceTag/ and elasticmapreduce:ResourceTag/ keys, but EmrService.storedTags answered clusters, Studios and notebook executions and nothing for a session's ARN, so a condition on a session's tags saw none. It now reads the session stored under the id the ARN ends in, in the account the ARN names, in place, matched on the whole ARN, giving the tags it started with. --- docs/services/iam.md | 8 ++-- .../aws/core/common/StoredResourceArns.java | 4 +- .../io/floci/aws/services/emr/EmrService.java | 20 +++++++--- .../aws/services/emr/EmrServiceFixture.java | 5 +++ .../aws/services/emr/EmrSessionsTest.java | 37 +++++++++++++++++++ ...estResourceEnforcementIntegrationTest.java | 34 +++++++++++++++++ 6 files changed, 97 insertions(+), 11 deletions(-) diff --git a/docs/services/iam.md b/docs/services/iam.md index 80d28f2560..12eb04ab2e 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3468,10 +3468,10 @@ floci populates: 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, - EMR for its clusters, CloudFront for every resource it tags, by its ARN, IAM Identity Center for its instances, - permission sets, applications and trusted token issuers, OAM for its sinks and links, RAM for its resource shares, - Payment Cryptography for its keys, Resource Explorer for its indexes and views, Application Auto Scaling for its - scalable targets, ECS for its clusters, task definitions, services, capacity providers, tasks and container + EMR for its clusters and sessions, CloudFront for every resource it tags, by its ARN, IAM Identity Center for its + instances, permission sets, applications and trusted token issuers, OAM for its sinks and links, RAM for its resource + shares, Payment Cryptography for its keys, Resource Explorer for its indexes and views, Application Auto Scaling for + its 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, Timestream for InfluxDB for its 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 7816ca68ad..1ccb343ad7 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -23,8 +23,8 @@ import java.util.Optional; * connections and API destinations; Application Auto Scaling, for its scalable targets and their tags; Redshift * Data, for the Redshift Serverless workgroups it runs statements on and the targets of its sessions; Payment * Cryptography, for the key an alias names and the tags of a key; EMR, for the clusters of its instance groups and a - * tag call's resource and the tags of a cluster; IAM Identity Center, for the accounts its permission sets are - * provisioned to and the tags of an instance, + * tag call's resource and the tags of a cluster or a session; IAM Identity Center, for the accounts its permission + * sets are provisioned to and the tags of an instance, * a permission set, an application or a trusted token issuer; Resource Explorer, for its default view and the tags * of an index or a view; OAM and RAM, for the sinks, invitations and shares of other accounts they act on, OAM for * the tags of a sink or a link, and RAM for the tags of a resource share; diff --git a/src/main/java/io/floci/aws/services/emr/EmrService.java b/src/main/java/io/floci/aws/services/emr/EmrService.java index 371f65aff8..33c8bab84c 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -135,6 +135,8 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear private static final String SERVICE = "emr"; // The resource of a cluster's ARN, before its id. static final String CLUSTER_RESOURCE = "cluster/"; + /** What follows a cluster's ARN in the ARN of one of its sessions, the session's id following. */ + static final String SESSION_SEGMENT = "/session/"; // The reason of a cluster a failed bootstrap action ended, as Terraform reported a real one's // (hashicorp/terraform-provider-aws#4378) and the Management Guide's VPC errors page quotes it. private static final String BOOTSTRAP_ACTION_FAILED = @@ -777,7 +779,7 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear long sequence = sessions.stream().mapToLong(EmrSession::getSequence).max().orElse(0) + 1; EmrSession session = EmrSessions.start(cluster, request, id, regionResolver.buildArn("elasticmapreduce", regionOf(cluster), - "cluster/" + cluster.getId() + "/session/" + id), + CLUSTER_RESOURCE + cluster.getId() + SESSION_SEGMENT + id), regionResolver.getAccountId(), now(), sequence, parameters); session.setContainerSession(runsSessionServers()); sessionStore.put(id, session); @@ -1833,10 +1835,10 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } /** - * The tags held on the cluster, Studio or notebook execution stored under {@code arn}, in the account it names, - * read in place: the cluster of that id in the ARN's Region, or one recorded with no Region, as the tag handlers - * find it, or the Studio or execution of that id in the ARN's Region; empty for an ARN naming nothing stored or - * naming anything else. + * The tags held on the cluster, session, Studio or notebook execution stored under {@code arn}, in the account it + * names, read in place: the cluster of that id in the ARN's Region, or one recorded with no Region, as the tag + * handlers find it, the session of that id recording that ARN, the tags it started with, or the Studio or execution + * of that id in the ARN's Region; empty for an ARN naming nothing stored or naming anything else. */ @Override public Map storedTags(String arn) { @@ -1851,6 +1853,14 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear if (resource.startsWith(EmrNotebookExecutionService.EXECUTION_RESOURCE)) { return notebookExecutions != null ? notebookExecutions.get().storedTags(arn) : Map.of(); } + int session = resource.startsWith(CLUSTER_RESOURCE) ? resource.indexOf(SESSION_SEGMENT) : -1; + if (session > 0) { + return AccountAwareStorageBackend.readInAccount(sessionStore, parsed.accountId(), + resource.substring(session + SESSION_SEGMENT.length())) + .filter(stored -> arn.equals(stored.getArn())) + .map(stored -> heldTags(stored.getTags())) + .orElse(Map.of()); + } String clusterId = resourceIdOf(parsed, CLUSTER_RESOURCE); if (clusterId == null || !arn.equals(AwsArnUtils.Arn.of("elasticmapreduce", parsed.region(), parsed.accountId(), resource).toString())) { diff --git a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java index 47ab351212..151e7d3393 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java +++ b/src/test/java/io/floci/aws/services/emr/EmrServiceFixture.java @@ -311,6 +311,11 @@ final class EmrServiceFixture { startupDelaySeconds, stepDurationSeconds, terminationDelaySeconds); } + /** The service as configured by default, every duration 0, on {@code storage}, so a test can seed its stores. */ + static EmrServiceFixture on(InMemoryStorageFactory storage) { + return new EmrServiceFixture(storage, new MutableClock(), null, null, null, null, null, null, 0, 0, 0); + } + /** The service in the {@code docker} runner mode, every duration 0, its steps run by {@code runner}. */ static EmrServiceFixture docker(SparkJobRunner runner, IamService iam) { return docker(runner, null, iam); diff --git a/src/test/java/io/floci/aws/services/emr/EmrSessionsTest.java b/src/test/java/io/floci/aws/services/emr/EmrSessionsTest.java index ca13fe83d9..6ee82bf276 100644 --- a/src/test/java/io/floci/aws/services/emr/EmrSessionsTest.java +++ b/src/test/java/io/floci/aws/services/emr/EmrSessionsTest.java @@ -5,15 +5,18 @@ import io.floci.aws.core.common.AwsException; import io.floci.aws.core.common.PaginatedResult; import io.floci.aws.core.common.SparkConnectEndpoint; import io.floci.aws.core.storage.AccountAwareStorageBackend; +import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.emr.model.EmrCluster; import io.floci.aws.services.emr.model.EmrInstanceGroup; import io.floci.aws.services.emr.model.EmrSession; +import io.floci.aws.testing.InMemoryStorageFactory; import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import static io.floci.aws.services.emr.EmrServiceFixture.REGION; @@ -53,6 +56,40 @@ class EmrSessionsTest { assertEquals("notebook", read.getName()); } + /** + * IAM's lookup reads the tags a session started with, by the ARN it records, and nothing for an unknown session, + * a session named under another cluster, or another account's ARN. + */ + @Test + void storedTagsAreTheTagsTheSessionStartedWith() { + String clusterId = sessionCluster(); + EmrSession started = service.startSession(clusterId, + new EmrSessions.Request("tagged", null, null, null, null, null, Map.of("team", "data"))); + String arn = started.getArn(); + + assertEquals(Map.of("team", "data"), service.storedTags(arn)); + assertTrue(service.storedTags(arn.replace(started.getId(), "is-UNKNOWN000000")).isEmpty()); + assertTrue(service.storedTags(arn.replace(clusterId, "j-OTHERCLUSTER")).isEmpty()); + assertTrue(service.storedTags(arn.replace("000000000000", "111122223333")).isEmpty()); + } + + /** A session stored before storage was account-aware is read in place: the lookup migrates nothing. */ + @Test + void storedTagsReadAPreAccountAwareSessionInPlace() { + InMemoryStorage raw = new InMemoryStorage<>(); + EmrService legacyState = EmrServiceFixture.on(new InMemoryStorageFactory("000000000000") + .withStore("emr-sessions.json", raw)).service; + EmrSession legacy = new EmrSession(); + legacy.setId("is-LEGACY000000"); + legacy.setClusterId("j-LEGACY"); + legacy.setArn("arn:aws:elasticmapreduce:us-east-1:000000000000:cluster/j-LEGACY/session/is-LEGACY000000"); + legacy.setTags(Map.of("team", "data")); + raw.put("is-LEGACY000000", legacy); + + assertEquals(Map.of("team", "data"), legacyState.storedTags(legacy.getArn())); + assertEquals(Set.of("is-LEGACY000000"), raw.keys()); + } + @Test void anIdleSessionEndsOnceItsIdleTimeoutHasPassed() { String clusterId = sessionCluster(); 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 7aa39f5b59..c49bf2c769 100644 --- a/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -2156,6 +2156,40 @@ class IamRequestResourceEnforcementIntegrationTest { "elasticmapreduce:DescribeCluster"); } + /** + * An {@code aws:ResourceTag} condition reads the tags EMR holds on the session a request names, those it started + * with, so an allow on one team's tag lets the caller read that team's session and not another's. + */ + @Test + void anEmrResourceTagConditionReadsTheTagsOfTheSession() { + String clusterId = adminJson("elasticmapreduce", "ElasticMapReduce.RunJobFlow") + .body("{\"Name\":\"res-emr-sessions\",\"ReleaseLabel\":\"emr-spark-8.0.0\",\"Applications\":[{\"Name\":" + + "\"Spark\"}],\"SessionEnabled\":true,\"Instances\":{\"KeepJobFlowAliveWhenNoSteps\":true," + + "\"InstanceGroups\":[{\"Name\":\"primary\",\"InstanceRole\":\"MASTER\",\"InstanceType\":" + + "\"m5.xlarge\",\"InstanceCount\":1}]}}") + .post("/").then().statusCode(200).extract().path("JobFlowId"); + cleanup.register(() -> adminJson("elasticmapreduce", "ElasticMapReduce.TerminateJobFlows") + .body("{\"JobFlowIds\":[\"" + clusterId + "\"]}").post("/")); + String tagged = emrSession(clusterId, "data"); + String other = emrSession(clusterId, "web"); + + User user = user("res-emr-session-tags"); + user.policy("{\"Effect\":\"Allow\",\"Action\":\"elasticmapreduce:GetSession\",\"Resource\":\"*\"," + + "\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/team\":\"data\"}}}"); + emr(user, "GetSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + tagged + "\"}") + .statusCode(200); + refusedJson(emr(user, "GetSession", "{\"ClusterId\":\"" + clusterId + "\",\"SessionId\":\"" + other + "\"}"), + "elasticmapreduce:GetSession"); + } + + /** The id of a session an administrator starts on the cluster, tagged with the team. */ + private static String emrSession(String clusterId, String team) { + return adminJson("elasticmapreduce", "ElasticMapReduce.StartSession") + .body("{\"ClusterId\":\"" + clusterId + "\",\"Name\":\"res-" + team + "\",\"Tags\":[{\"Key\":\"team\"," + + "\"Value\":\"" + team + "\"}]}") + .post("/").then().statusCode(200).extract().path("Id"); + } + /** The id of the cluster {@code arn} names, tagged with the team by an administrator. */ private static String emrClusterId(String arn, String team) { String id = arn.substring(arn.lastIndexOf('/') + 1);