From e078bb7b008a6ba10e26c76c718f3d285da33e07 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:37:08 -0400 Subject: [PATCH] feat(emr): answer GetClusterSessionCredentials for runtime role clusters (#8714) GetClusterSessionCredentials, "temporary, HTTP basic credentials that are associated with a given runtime IAM role and used by a cluster with fine-grained access control activated", was not served. Floci now answers it with a random username and password that expire in an hour, for a RUNNING or WAITING cluster on emr-6.11.0 or later whose security configuration turns on runtime roles (EnableApplicationScopedIAMRole); any other cluster is refused. Floci runs no endpoint that checks them, and keeps none. A request without an ExecutionRoleArn is refused, as the credentials are "associated with a given runtime IAM role". Whether a cluster is a runtime role enabled one is now recorded as it is created, so a security configuration deleted or reused later changes nothing; CreatePersistentAppUI's RuntimeRoleEnabledCluster reads the same. --- docs/services/emr.md | 10 ++ docs/services/index.md | 2 +- .../io/floci/aws/services/emr/EmrHandler.java | 12 ++ .../io/floci/aws/services/emr/EmrService.java | 65 ++++++++++- .../aws/services/emr/model/EmrCluster.java | 6 + ...sterSessionCredentialsIntegrationTest.java | 105 ++++++++++++++++++ 6 files changed, 194 insertions(+), 6 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/emr/EmrClusterSessionCredentialsIntegrationTest.java diff --git a/docs/services/emr.md b/docs/services/emr.md index 361ef9d5dc..53a766948f 100644 --- a/docs/services/emr.md +++ b/docs/services/emr.md @@ -47,6 +47,7 @@ Floci emulates the Amazon EMR (Elastic MapReduce) management API. Clusters (job | `DescribePersistentAppUI` | Returns a persistent application UI's types and status | | `GetPersistentAppUIPresignedURL` | Returns a presigned URL to a persistent application UI, a page of Floci's | | `GetOnClusterAppUIPresignedURL` | Returns a presigned URL to a running cluster's on-cluster UI, a page of Floci's | +| `GetClusterSessionCredentials` | Returns temporary basic credentials for a runtime role enabled cluster; see [Application UIs](#application-uis) | | `AddInstanceGroups` | Adds instance groups to a running cluster | | `ListInstanceGroups` | Lists the instance groups of a cluster | | `AddInstanceFleet` | Adds an instance fleet to a cluster | @@ -328,6 +329,15 @@ Floci restarted opens a `403` page, and one whose cluster has gone a `404`. * **GetPersistentAppUIPresignedURL** gives a URL to one of the UI's types, its first by default; a type it has not is refused. **GetOnClusterAppUIPresignedURL** gives one to an on-cluster UI, the `ResourceManager` by default, while the cluster is `RUNNING` or `WAITING`, and none for a `DryRun`. Both are `PresignedURLReady` at once. +* **GetClusterSessionCredentials** gives "temporary, HTTP basic credentials that are associated with a given runtime + IAM role and used by a cluster with fine-grained access control activated": a random username and password that + expire in an hour, as no source gives AWS's lifetime, for a `RUNNING` or `WAITING` cluster on `emr-6.11.0` or later + (from which a Workspace attaches to a cluster with a runtime role) whose security configuration sets + `EnableApplicationScopedIAMRole` as the cluster was created (deleting or reusing the configuration's name later + changes nothing, for this and for `RuntimeRoleEnabledCluster`). A request without an `ExecutionRoleArn`, which the + model leaves optional, is refused too, as the credentials are "associated with a given runtime IAM role". Anything + else is refused with `InvalidRequestException`, in Floci's own wording. Floci runs no endpoint that checks them, and + keeps none. ## Running steps diff --git a/docs/services/index.md b/docs/services/index.md index 020bc13ac1..c9087df1f3 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -84,7 +84,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Redshift](redshift.md) | `POST /` with `Action=` param + PostgreSQL container | Query + PostgreSQL wire (+ CFN) | 65 | | [Redshift Data API](redshift-data.md) | `POST /` + `X-Amz-Target: RedshiftData.*` | JSON 1.1 | 12 | | [Redshift Serverless](redshift-serverless.md) | `POST /` + `X-Amz-Target: RedshiftServerless.*` | JSON 1.1 | 58 | -| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 63 | +| [EMR](emr.md) | `POST /` + `X-Amz-Target: ElasticMapReduce.*` | JSON 1.1 | 64 | | [EMR on EKS](emr-containers.md) | `/virtualclusters/*`, `/jobtemplates/*`, `/securityconfigurations/*`, `/tags/*` | REST JSON | 25 | | [EMR Serverless](emr-serverless.md) | `/applications/*`, `/tags/*` | REST JSON | 15 | | [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 | diff --git a/src/main/java/io/floci/aws/services/emr/EmrHandler.java b/src/main/java/io/floci/aws/services/emr/EmrHandler.java index ae587fedce..2287bf16cb 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrHandler.java +++ b/src/main/java/io/floci/aws/services/emr/EmrHandler.java @@ -109,6 +109,7 @@ public class EmrHandler { case "DescribePersistentAppUI" -> handleDescribePersistentAppUi(request); case "GetPersistentAppUIPresignedURL" -> handleGetPersistentAppUiPresignedUrl(request); case "GetOnClusterAppUIPresignedURL" -> handleGetOnClusterAppUiPresignedUrl(request); + case "GetClusterSessionCredentials" -> handleGetClusterSessionCredentials(request); case "AddInstanceGroups" -> handleAddInstanceGroups(request); case "ListInstanceGroups" -> handleListInstanceGroups(request); case "AddInstanceFleet" -> handleAddInstanceFleet(request); @@ -915,6 +916,17 @@ public class EmrHandler { return Response.ok(response).build(); } + private Response handleGetClusterSessionCredentials(JsonNode request) { + EmrService.ClusterSessionCredentials credentials = service.clusterSessionCredentials( + string(request, "ClusterId"), string(request, "ExecutionRoleArn")); + ObjectNode response = objectMapper.createObjectNode(); + ObjectNode usernamePassword = response.putObject("Credentials").putObject("UsernamePassword"); + usernamePassword.put("Username", credentials.username()); + usernamePassword.put("Password", credentials.password()); + putEpoch(response, "ExpiresAt", credentials.expiresAt()); + return Response.ok(response).build(); + } + // ──────────────────────────── Instance groups / fleets ──────────────────────────── private Response handleAddInstanceGroups(JsonNode request) { 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 5e617d4c50..36f647f3e5 100644 --- a/src/main/java/io/floci/aws/services/emr/EmrService.java +++ b/src/main/java/io/floci/aws/services/emr/EmrService.java @@ -59,6 +59,7 @@ import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; @@ -105,6 +106,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear private static final Logger LOG = Logger.getLogger(EmrService.class); private static final String UPPER_ALNUM = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final SecureRandom RANDOM = new SecureRandom(); + private static final int SESSION_PASSWORD_BYTES = 24; + // No source gives how long GetClusterSessionCredentials' credentials last; Floci's expire in an hour. + private static final Duration SESSION_CREDENTIALS_VALIDITY = Duration.ofHours(1); // AWS's answer to a change on a terminated cluster, for AddJobFlowSteps and ModifyInstanceFleet; Floci // gives it to AddInstanceGroups and AddInstanceFleet too, for one shutting down. private static final String JOB_FLOW_SHUT_DOWN = @@ -468,6 +472,9 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear throw new AwsException("ValidationException", "Security configuration does not exist: " + cluster.getSecurityConfiguration(), 400); } + // A security configuration applies to the cluster as it is created: deleting or reusing its name later + // changes nothing about the cluster. + cluster.setRuntimeRoleEnabled(runtimeRoleEnabled(region, cluster.getSecurityConfiguration())); String id = "j-" + randomId(13); cluster.setId(id); cluster.setRegion(region); @@ -1057,15 +1064,21 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear } /** - * Whether the cluster's security configuration turns on runtime roles, its - * {@code AuthorizationConfiguration.IAMConfiguration.EnableApplicationScopedIAMRole}: false for a cluster with - * none, or whose configuration has since been deleted. + * Whether the cluster's security configuration turned on runtime roles as the cluster was created, its + * {@code AuthorizationConfiguration.IAMConfiguration.EnableApplicationScopedIAMRole}; for a cluster stored before + * Floci kept that, its configuration as it now stands. False for a cluster with none. */ public boolean runtimeRoleEnabled(EmrCluster cluster) { - if (cluster.getSecurityConfiguration() == null) { + return cluster.getRuntimeRoleEnabled() != null ? cluster.getRuntimeRoleEnabled() + : runtimeRoleEnabled(regionOf(cluster), cluster.getSecurityConfiguration()); + } + + // Whether the named security configuration of the Region turns on runtime roles; false for none, or one deleted. + private boolean runtimeRoleEnabled(String region, String securityConfiguration) { + if (securityConfiguration == null) { return false; } - return secConfigStore.get(securityConfigurationKey(regionOf(cluster), cluster.getSecurityConfiguration())) + return secConfigStore.get(securityConfigurationKey(region, securityConfiguration)) .map(SecurityConfiguration::getSecurityConfiguration) .map(EmrService::rawJson) .map(json -> json.path("AuthorizationConfiguration").path("IAMConfiguration") @@ -1073,6 +1086,48 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear .orElse(false); } + /** + * GetClusterSessionCredentials: "temporary, HTTP basic credentials that are associated with a given runtime IAM + * role and used by a cluster with fine-grained access control activated". The cluster must be RUNNING or WAITING, + * a runtime role enabled one ({@link #runtimeRoleEnabled}), on "Amazon EMR release 6.11 or higher", from which a + * Workspace attaches to a cluster with a runtime role. Each refusal is InvalidRequestException in Floci's own + * wording. Floci runs no endpoint that checks the credentials, and keeps none; no source gives how long AWS's + * last, and Floci's expire in an hour. + */ + public ClusterSessionCredentials clusterSessionCredentials(String clusterId, String executionRoleArn) { + if (executionRoleArn != null && (executionRoleArn.length() < 20 || executionRoleArn.length() > 2048)) { + throw SmithyValidationErrors.validationException( + SmithyValidationErrors.lengthOutOfRange("executionRoleArn", executionRoleArn, 20, 2048)); + } + // The model leaves ExecutionRoleArn optional, but the credentials are "associated with a given runtime IAM + // role", and with none there is none to associate them with; AWS's answer is not recorded. + if (executionRoleArn == null) { + throw invalid("ExecutionRoleArn is required: the credentials are for a runtime role."); + } + return call(() -> { + EmrCluster cluster = settle(requireCluster(clusterId)); + if (!runsOrWaits(cluster)) { + throw invalid("Cluster " + clusterId + " is " + cluster.getState() + + ", and its endpoints are there only while it is RUNNING or WAITING."); + } + if (!releaseAtLeast(cluster.getReleaseLabel(), 6, 11, 0)) { + throw invalid("Cluster session credentials need a cluster of release emr-6.11.0 or later."); + } + if (!runtimeRoleEnabled(cluster)) { + throw invalid("Cluster " + clusterId + " is not a runtime role enabled cluster: its security" + + " configuration does not turn on EnableApplicationScopedIAMRole."); + } + byte[] password = new byte[SESSION_PASSWORD_BYTES]; + RANDOM.nextBytes(password); + return new ClusterSessionCredentials("emr-" + randomId(16).toLowerCase(), + HexFormat.of().formatHex(password), now().plus(SESSION_CREDENTIALS_VALIDITY)); + }); + } + + /** GetClusterSessionCredentials' username and password, and when they expire. */ + public record ClusterSessionCredentials(String username, String password, Instant expiresAt) { + } + public SecurityConfiguration describeSecurityConfiguration(String name, String region) { return secConfigStore.get(securityConfigurationKey(region, name)).orElseThrow(() -> new AwsException( "InvalidRequestException", "Security configuration does not exist: " + name, 400)); diff --git a/src/main/java/io/floci/aws/services/emr/model/EmrCluster.java b/src/main/java/io/floci/aws/services/emr/model/EmrCluster.java index 441ff48853..3259ade535 100644 --- a/src/main/java/io/floci/aws/services/emr/model/EmrCluster.java +++ b/src/main/java/io/floci/aws/services/emr/model/EmrCluster.java @@ -41,6 +41,9 @@ public class EmrCluster { private boolean keepJobFlowAliveWhenNoSteps; // RunJobFlow's SessionEnabled: whether the cluster takes Spark Connect sessions. private boolean sessionEnabled; + // Whether its security configuration turned on runtime roles as it was created; null for a cluster stored before + // Floci kept it. + private Boolean runtimeRoleEnabled; private int normalizedInstanceHours; private int stepConcurrencyLevel = 1; private int ebsRootVolumeSize; @@ -252,4 +255,7 @@ public class EmrCluster { public boolean isSessionEnabled() { return sessionEnabled; } public void setSessionEnabled(boolean sessionEnabled) { this.sessionEnabled = sessionEnabled; } + + public Boolean getRuntimeRoleEnabled() { return runtimeRoleEnabled; } + public void setRuntimeRoleEnabled(Boolean runtimeRoleEnabled) { this.runtimeRoleEnabled = runtimeRoleEnabled; } } diff --git a/src/test/java/io/floci/aws/services/emr/EmrClusterSessionCredentialsIntegrationTest.java b/src/test/java/io/floci/aws/services/emr/EmrClusterSessionCredentialsIntegrationTest.java new file mode 100644 index 0000000000..2d0b1f7309 --- /dev/null +++ b/src/test/java/io/floci/aws/services/emr/EmrClusterSessionCredentialsIntegrationTest.java @@ -0,0 +1,105 @@ +package io.floci.aws.services.emr; + +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.util.UUID; + +import static io.floci.aws.testing.EmrRequests.emr; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.Matchers.notNullValue; + +/** GetClusterSessionCredentials over the AWS JSON 1.1 wire protocol, for a runtime role enabled cluster and others. */ +@QuarkusTest +class EmrClusterSessionCredentialsIntegrationTest { + + private static final String ROLE = "arn:aws:iam::000000000000:role/test-emr-demo3"; + + @BeforeAll + static void configure() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void aRuntimeRoleEnabledClusterGivesTemporaryBasicCredentials() { + String clusterId = cluster("emr-6.15.0", runtimeRoles()); + + emr("GetClusterSessionCredentials", "{\"ClusterId\":\"" + clusterId + "\",\"ExecutionRoleArn\":\"" + ROLE + + "\"}") + .then().statusCode(200) + .body("Credentials.UsernamePassword.Username", matchesPattern("emr-[a-z0-9]{16}")) + .body("Credentials.UsernamePassword.Password", matchesPattern("[0-9a-f]{48}")) + .body("ExpiresAt", notNullValue()); + + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200); + refused(clusterId, "InvalidRequestException"); + } + + @Test + void aClusterKeepsTheRuntimeRolesItWasCreatedWithAfterItsSecurityConfigurationIsDeleted() { + String configuration = runtimeRoles(); + String clusterId = cluster("emr-6.15.0", configuration); + emr("DeleteSecurityConfiguration", "{\"Name\":\"" + configuration + "\"}").then().statusCode(200); + + emr("GetClusterSessionCredentials", "{\"ClusterId\":\"" + clusterId + "\",\"ExecutionRoleArn\":\"" + ROLE + + "\"}") + .then().statusCode(200) + .body("Credentials.UsernamePassword.Username", notNullValue()); + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200); + } + + @Test + void aRequestWithoutARuntimeRoleIsRefused() { + String clusterId = cluster("emr-6.15.0", runtimeRoles()); + emr("GetClusterSessionCredentials", "{\"ClusterId\":\"" + clusterId + "\"}") + .then().statusCode(400) + .body("__type", equalTo("InvalidRequestException")); + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + clusterId + "\"]}").then().statusCode(200); + } + + @Test + void aClusterWithoutRuntimeRolesOrOfAnEarlierReleaseIsRefused() { + String plain = cluster("emr-6.15.0", null); + refused(plain, "InvalidRequestException"); + String early = cluster("emr-6.10.0", runtimeRoles()); + refused(early, "InvalidRequestException"); + refused("j-NOSUCHCLUSTER", "InvalidRequestException"); + emr("GetClusterSessionCredentials", "{\"ClusterId\":\"" + plain + "\",\"ExecutionRoleArn\":\"arn:short\"}") + .then().statusCode(400) + .body("__type", equalTo("ValidationException")); + emr("TerminateJobFlows", "{\"JobFlowIds\":[\"" + plain + "\",\"" + early + "\"]}").then().statusCode(200); + } + + private static void refused(String clusterId, String type) { + emr("GetClusterSessionCredentials", "{\"ClusterId\":\"" + clusterId + "\",\"ExecutionRoleArn\":\"" + ROLE + + "\"}") + .then().statusCode(400) + .body("__type", equalTo(type)); + } + + // A security configuration that turns on runtime roles. + private static String runtimeRoles() { + String name = "runtime-roles-" + UUID.randomUUID(); + emr("CreateSecurityConfiguration", "{\"Name\":\"" + name + "\",\"SecurityConfiguration\":" + + "\"{\\\"AuthorizationConfiguration\\\":{\\\"IAMConfiguration\\\":" + + "{\\\"EnableApplicationScopedIAMRole\\\":true}}}\"}") + .then().statusCode(200); + return name; + } + + private static String cluster(String releaseLabel, String securityConfiguration) { + String extra = securityConfiguration != null + ? "\"SecurityConfiguration\": \"" + securityConfiguration + "\"," : ""; + return emr("RunJobFlow", """ + {"Name": "runtime-roles", "ReleaseLabel": "%s", %s + "Applications": [{"Name": "Spark"}, {"Name": "Livy"}, {"Name": "JupyterEnterpriseGateway"}], + "Instances": {"KeepJobFlowAliveWhenNoSteps": true, + "InstanceGroups": [{"Name": "primary", "InstanceRole": "MASTER", "InstanceType": "m5.xlarge", + "InstanceCount": 1}]}} + """.formatted(releaseLabel, extra)) + .then().statusCode(200).extract().path("JobFlowId"); + } +}