From d63ad7c22696582c03145ce6492dc46b11d6983d Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 22 Nov 2026 05:02:40 -0400 Subject: [PATCH] fix(emr-serverless): scope a job run's credentials by its execution IAM policy (#9190) StartJobRun kept a run's executionIamPolicy only to give it back: its credentials had every permission of its execution role, and the policy was stored as sent, members it does not have included. - A run's inline policy now scopes the session its containers get, as an assumed role's session policy does, so with IAM enforcement on "The resulting job IAM role permissions will be an intersection of this policy and the policy associated with your job execution role". Its policyArns are kept and given back but not applied, as Floci's IAM applies no managed session policy, an assumed role's included. - The policy keeps only its two members. An inline policy outside 1 to 2,048 characters, more than 10 policy ARNs, or one outside 20 to 2,048 characters is refused with the framework's ValidationException, and either member of another JSON type with SerializationException. --- docs/services/emr-serverless.md | 8 +- .../EmrServerlessJobRunService.java | 83 ++++++++++++++++++- .../EmrServerlessSparkRunner.java | 3 +- .../emrserverless/SparkJobRunner.java | 8 ++ .../io/floci/aws/services/iam/IamService.java | 13 +++ .../LambdaExecutionRoleCredentials.java | 12 ++- .../EmrServerlessJobRunServiceTest.java | 52 ++++++++++++ .../aws/services/iam/IamServiceTest.java | 17 ++++ 8 files changed, 191 insertions(+), 5 deletions(-) diff --git a/docs/services/emr-serverless.md b/docs/services/emr-serverless.md index 7fb983487d..aac96edb0f 100644 --- a/docs/services/emr-serverless.md +++ b/docs/services/emr-serverless.md @@ -407,7 +407,13 @@ worker of its own on EMR Serverless (see **Executors** below). executors, in the driver's JVM in local mode, and the Python workers they start. * **Credentials**: the container gets a session for the run's execution role when IAM knows the role, otherwise the account's placeholder credentials, and `AWS_ENDPOINT_URL` pointing at Floci, so the - job's own SDK clients reach Floci too. + job's own SDK clients reach Floci too. A run's `executionIamPolicy.policy` scopes that session as an + assumed role's session policy does, so with IAM enforcement on "The resulting job IAM role permissions will be + an intersection of this policy and the policy associated with your job execution role". Its `policyArns` are + kept and given back but not applied, as Floci's IAM applies no managed session policy, an assumed role's + included. `StartJobRun` refuses an inline policy outside 1 to 2,048 characters, more than 10 policy ARNs, or + one outside 20 to 2,048 characters, with the framework's `ValidationException`, and either member of another + JSON type with `SerializationException`. Only those two members are kept. * **HTTPS**: with [TLS](../configuration/tls.md) on, the container also gets Floci's CA bundle as a Java trust store, `/etc/floci-ca-bundle.p12`, which every JVM in it uses through `JAVA_TOOL_OPTIONS`, each saying so on its standard error (`Picked up JAVA_TOOL_OPTIONS: ...`); a diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java index 3b06af7578..ba5e765fff 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunService.java @@ -100,6 +100,13 @@ public class EmrServerlessJobRunService implements Resettable { static final String STATE_QUEUED = "QUEUED"; private static final String MODE_BATCH = "BATCH"; private static final String MODE_STREAMING = "STREAMING"; + // JobRunExecutionIamPolicy's members, and the model's bounds on them: PolicyDocument's and Arn's lengths, and + // PolicyArnList's size. + private static final String INLINE_POLICY = "policy"; + private static final String POLICY_ARNS = "policyArns"; + private static final int MAX_POLICY_LENGTH = 2048; + private static final int MIN_ARN_LENGTH = 20; + private static final int MAX_POLICY_ARNS = 10; // CancelJobRun's grace period: its default for a streaming run, and its range. private static final int DEFAULT_STREAMING_GRACE_SECONDS = 120; private static final int MIN_GRACE_SECONDS = 15; @@ -595,7 +602,7 @@ public class EmrServerlessJobRunService implements Resettable { private static void requested(JobRun run, StartJobRunRequest request) { run.setName(request.getName()); run.setExecutionRole(request.getExecutionRoleArn()); - run.setExecutionIamPolicy(request.getExecutionIamPolicy()); + run.setExecutionIamPolicy(executionIamPolicy(request.getExecutionIamPolicy())); run.setConfigurationOverrides(request.getConfigurationOverrides()); run.setJobDriver(request.getJobDriver()); run.setTags(request.getTags() != null ? new LinkedHashMap<>(request.getTags()) : new LinkedHashMap<>()); @@ -606,6 +613,61 @@ public class EmrServerlessJobRunService implements Resettable { run.setFlexExecution(flexExecution(request.getFlexExecution())); } + // StartJobRun's executionIamPolicy as the model's JobRunExecutionIamPolicy holds it: its policy and policyArns. + private static Map executionIamPolicy(Map given) { + if (given == null) { + return null; + } + Map policy = new LinkedHashMap<>(); + for (String member : List.of(INLINE_POLICY, POLICY_ARNS)) { + if (given.get(member) != null) { + policy.put(member, given.get(member)); + } + } + return policy; + } + + /** + * What is wrong with StartJobRun's executionIamPolicy, against the model's constraints: an inline policy of 1 to + * 2,048 characters, and at most 10 policy ARNs of 20 to 2,048 characters each. A member of another JSON type is + * refused with SerializationException, as retryPolicy's are. + */ + private static List executionIamPolicyViolations(Map given) { + List violations = new ArrayList<>(); + Object policy = given != null ? given.get(INLINE_POLICY) : null; + Object arns = given != null ? given.get(POLICY_ARNS) : null; + if (policy != null && !(policy instanceof String)) { + throw new AwsException("SerializationException", "executionIamPolicy.policy must be a string", 400); + } + if (arns != null && !(arns instanceof List list && list.stream().allMatch(String.class::isInstance))) { + throw new AwsException("SerializationException", + "executionIamPolicy.policyArns must be a list of strings", 400); + } + if (policy instanceof String document) { + String violation = SmithyValidationErrors.Violations.WITHOUT_VALUES.lengthOutOfRange( + "executionIamPolicy.policy", document, 1, MAX_POLICY_LENGTH); + if (violation != null) { + violations.add(violation); + } + } + if (arns instanceof List list) { + String size = SmithyValidationErrors.sizeOutOfRange("executionIamPolicy.policyArns", list.size(), 0, + MAX_POLICY_ARNS); + if (size != null) { + violations.add(size); + } + for (int i = 0; i < list.size(); i++) { + String violation = SmithyValidationErrors.lengthOutOfRange( + "executionIamPolicy.policyArns." + (i + 1) + ".member", (String) list.get(i), MIN_ARN_LENGTH, + MAX_POLICY_LENGTH); + if (violation != null) { + violations.add(violation); + } + } + } + return violations; + } + // StartJobRun's flexExecution as the model's FlexExecution holds it: its one member, enabled, where it is given. private static Map flexExecution(Map given) { if (given == null) { @@ -1142,6 +1204,18 @@ public class EmrServerlessJobRunService implements Resettable { .orElse(false); } + /** + * The inline policy of a run's executionIamPolicy, which scopes its credentials: "The resulting job IAM role + * permissions will be an intersection of this policy and the policy associated with your job execution role". + * Null where it has none. Its policyArns are not applied, as Floci's IAM applies no managed session policy, an + * assumed role's included. + */ + private synchronized String inlinePolicy(String jobRunId) { + return store.get(jobRunId).map(record -> record.getJobRun().getExecutionIamPolicy()) + .map(policy -> policy.get(INLINE_POLICY)).filter(String.class::isInstance).map(String.class::cast) + .orElse(null); + } + // A run cancelled with a grace period that has not ended, whose driver may still end by itself. private boolean shuttingDown(JobRunRecord record) { return STATE_CANCELLING.equals(record.getJobRun().getState()) && record.getShutdownDeadline() != null @@ -1794,7 +1868,7 @@ public class EmrServerlessJobRunService implements Resettable { if (flex != null && !(flex instanceof Boolean)) { throw new AwsException("SerializationException", "flexExecution.enabled must be a boolean", 400); } - List violations = new ArrayList<>(); + List violations = executionIamPolicyViolations(request.getExecutionIamPolicy()); if (request.getClientToken() == null) { violations.add(SmithyValidationErrors.notNull("clientToken")); } @@ -1991,5 +2065,10 @@ public class EmrServerlessJobRunService implements Resettable { RequestScopes.runAs(job.accountId(), job.region(), () -> keepExecutorLifetimes(job.runId(), launchedIn, lifetimes)); } + + @Override + public String sessionPolicy() { + return RequestScopes.callAs(job.accountId(), job.region(), () -> inlinePolicy(job.runId())); + } } } diff --git a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java index a97cb02f90..3c9d6d0f81 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/EmrServerlessSparkRunner.java @@ -540,7 +540,8 @@ public class EmrServerlessSparkRunner implements SparkJobRunner, ContainerTeardo if (progress.cancelled()) { return Outcome.halted(); } - credentials = roleCredentials.forRole(job.executionRole(), job.accountId(), job.runId()); + credentials = roleCredentials.forRole(job.executionRole(), job.accountId(), job.runId(), + progress.sessionPolicy()); Map labels = new LinkedHashMap<>(ContainerStorageHelper.resourceIdentityLabels( job.service(), job.runId(), job.accountId(), job.region())); // The deployment that started the driver, which removeLeftoverDrivers() goes by. diff --git a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java index ab26ec78d8..55766ba046 100644 --- a/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java +++ b/src/main/java/io/floci/aws/services/emrserverless/SparkJobRunner.java @@ -103,6 +103,14 @@ public interface SparkJobRunner { */ default void executorsRan(List lifetimes) { } + + /** + * The inline session policy the run's credentials are scoped by, so that its permissions are what its + * execution role and the policy both allow; null for none. + */ + default String sessionPolicy() { + return null; + } } /** What a run's container runs as: its driver, or one of its executors. */ diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java index 67df59cee6..94c25a0786 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -5558,6 +5558,18 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId, String secretAccessKey, String sessionToken, String roleArn, String roleSessionName, String assumedRoleId) { + registerLambdaExecutionRoleSession(accountId, sessionAccessKeyId, secretAccessKey, sessionToken, roleArn, + roleSessionName, assumedRoleId, null); + } + + /** + * Stores a non-expiring execution-role session with its session token, assumed role ID and an inline session + * policy, which scopes it as an assumed role's session policy does; null for none. + */ + public void registerLambdaExecutionRoleSession(String accountId, String sessionAccessKeyId, + String secretAccessKey, String sessionToken, String roleArn, + String roleSessionName, String assumedRoleId, + String sessionPolicyDocument) { if (accountId == null || accountId.isBlank()) { throw new IllegalArgumentException("Lambda function account ID must not be blank"); } @@ -5566,6 +5578,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { session.setLambdaExecutionRole(true); session.setRoleSessionName(roleSessionName); session.setAssumedRoleId(assumedRoleId); + session.setSessionPolicyDocument(sessionPolicyDocument); issuedNow(session); if (sessions instanceof AccountAwareStorageBackend aware) { aware.putForAccount(accountId, sessionAccessKeyId, session); diff --git a/src/main/java/io/floci/aws/services/lambda/launcher/LambdaExecutionRoleCredentials.java b/src/main/java/io/floci/aws/services/lambda/launcher/LambdaExecutionRoleCredentials.java index a9e11b09b0..b202473ee1 100644 --- a/src/main/java/io/floci/aws/services/lambda/launcher/LambdaExecutionRoleCredentials.java +++ b/src/main/java/io/floci/aws/services/lambda/launcher/LambdaExecutionRoleCredentials.java @@ -58,6 +58,16 @@ public class LambdaExecutionRoleCredentials { /** A session for {@code roleArn} assumed on behalf of {@code functionName} in {@code functionAccountId}. */ public Optional forRole(String roleArn, String functionAccountId, String functionName) { + return forRole(roleArn, functionAccountId, functionName, null); + } + + /** + * A session for {@code roleArn} assumed on behalf of {@code functionName} in {@code functionAccountId}, its + * permissions scoped by the inline {@code sessionPolicy} as an assumed role's are by the one it is assumed with; + * none where it is null. + */ + public Optional forRole(String roleArn, String functionAccountId, String functionName, + String sessionPolicy) { if (roleArn == null || roleArn.isBlank() || functionAccountId == null || functionAccountId.isBlank()) { return Optional.empty(); @@ -90,7 +100,7 @@ public class LambdaExecutionRoleCredentials { String assumedRoleId = role.get().getRoleId() != null ? role.get().getRoleId() + ":" + functionName : null; iamService.registerLambdaExecutionRoleSession( functionAccountId, credentials.accessKeyId(), credentials.secretAccessKey(), - credentials.sessionToken(), roleArn, functionName, assumedRoleId); + credentials.sessionToken(), roleArn, functionName, assumedRoleId, sessionPolicy); return Optional.of(credentials); } diff --git a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java index f26745e07e..9a95b86713 100644 --- a/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java +++ b/src/test/java/io/floci/aws/services/emrserverless/EmrServerlessJobRunServiceTest.java @@ -34,8 +34,10 @@ import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -1200,6 +1202,53 @@ class EmrServerlessJobRunServiceTest { immediate.getJobRun(applicationId, stored, null).getTotalResourceUtilization().get("vCPUHour")); } + @Test + void aRunsCredentialsAreScopedByItsInlinePolicyAndItKeepsOnlyThePolicysMembers() { + FakeRunner runner = new FakeRunner(); + EmrServerlessJobRunService service = dockerService(runner); + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + String readOnly = "arn:aws:iam::aws:policy/ReadOnlyAccess"; + StartJobRunRequest scoped = request(null, null); + scoped.setExecutionIamPolicy(Map.of("policy", policy, "policyArns", List.of(readOnly), "extra", "dropped")); + String scopedRun = service.startJobRun(applicationId, scoped).getJobRunId(); + runNext(); + service.startJobRun(applicationId, request(null, null)); + runNext(); + + assertEquals(Arrays.asList(policy, null), runner.sessionPolicies); + assertEquals(Map.of("policy", policy, "policyArns", List.of(readOnly)), + service.getJobRun(applicationId, scopedRun, null).getExecutionIamPolicy()); + } + + @Test + void anExecutionIamPolicyOutsideTheModelsBoundsIsRefused() { + EmrServerlessJobRunService service = service(0); + List elevenArns = new ArrayList<>(); + for (int i = 0; i < 11; i++) { + elevenArns.add("arn:aws:iam::aws:policy/Policy" + i); + } + Map, String> refusals = new LinkedHashMap<>(); + refusals.put(Map.of("policy", ""), "'executionIamPolicy.policy'"); + refusals.put(Map.of("policy", "x".repeat(2049)), "'executionIamPolicy.policy'"); + refusals.put(Map.of("policyArns", elevenArns), "'executionIamPolicy.policyArns'"); + refusals.put(Map.of("policyArns", List.of("arn:aws:iam::1:p/x")), "'executionIamPolicy.policyArns.1.member'"); + for (Map.Entry, String> refusal : refusals.entrySet()) { + StartJobRunRequest refused = request(null, null); + refused.setExecutionIamPolicy(refusal.getKey()); + AwsException error = assertThrows(AwsException.class, () -> service.startJobRun(applicationId, refused)); + assertEquals("ValidationException", error.getErrorCode()); + assertTrue(error.getMessage().contains(refusal.getValue()), error.getMessage()); + } + for (Map malformed : List.>of(Map.of("policy", 1), + Map.of("policyArns", "arn:aws:iam::aws:policy/ReadOnlyAccess"))) { + StartJobRunRequest refused = request(null, null); + refused.setExecutionIamPolicy(malformed); + assertEquals("SerializationException", assertThrows(AwsException.class, + () -> service.startJobRun(applicationId, refused)).getErrorCode()); + } + } + @Test void eachAttemptIsLaunchedWhileItsApplicationCannotBeDeleted() { FakeRunner runner = new FakeRunner(); @@ -1906,6 +1955,8 @@ class EmrServerlessJobRunServiceTest { final Set stopped = new HashSet<>(); final Set interrupted = new HashSet<>(); final List driversStarted = new ArrayList<>(); + // The session policy each run's credentials were scoped by, as its driver started. + final List sessionPolicies = new ArrayList<>(); // What progress.cancelled() said once the driver ran, and again after whileRunning. final List cancelledAsRunning = new ArrayList<>(); Outcome outcome = Outcome.exitedWith(0); @@ -1935,6 +1986,7 @@ class EmrServerlessJobRunServiceTest { resolved(progress, WorkerType.EXECUTOR, job.executors().image(), executorsResolve); } driversStarted.add(job.runId()); + sessionPolicies.add(progress.sessionPolicy()); progress.started(); cancelledAsRunning.add(progress.cancelled()); whileRunning.run(); diff --git a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java index eee8ec18bb..d4d0602881 100644 --- a/src/test/java/io/floci/aws/services/iam/IamServiceTest.java +++ b/src/test/java/io/floci/aws/services/iam/IamServiceTest.java @@ -2769,6 +2769,23 @@ class IamServiceTest { assertTrue(sessions.getForAccount(accountId, accessKeyId).isEmpty()); } + @Test + void anExecutionRoleSessionWithAnInlinePolicyIsScopedByItAsAnAssumedRolesIs() { + String accountId = "222233334444"; + String accessKeyId = "ASIAEXECUTIONSCOPED"; + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}"; + AccountAwareStorageBackend sessions = new AccountAwareStorageBackend<>( + new InMemoryStorage<>(), null, "000000000000"); + IamService service = iamService(false, new InMemoryStorage<>(), sessions); + + service.registerLambdaExecutionRoleSession(accountId, accessKeyId, "secret", "token", + "arn:aws:iam::222233334444:role/JobRole", "run-1", null, policy); + + assertEquals(policy, sessions.getForAccount(accountId, accessKeyId).orElseThrow().getSessionPolicyDocument()); + assertEquals(policy, service.resolveCallerContext(accessKeyId).sessionPolicyDocument()); + } + @Test void temporarySessionUsesExplicitAccountNamespace() { String accountId = "222233334444";