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.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-18 12:21:41 -04:00
1 parent 0842636ed9
commit 5548bb78eb
6 files changed
+97 -11

No files matched your search

+4 -4
View File
@@ -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
@@ -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;
@@ -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<String, String> 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())) {
@@ -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);
@@ -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<String, EmrSession> 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();
@@ -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);