From 97fcbf21d08b0afa82011a7fcf77258febce2c46 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:42:27 -0400 Subject: [PATCH] fix(stepfunctions): check EMR Serverless tasks as the same request made directly (#8322) The EMR Serverless task arm wrote its action ("emr-serverless:" plus the API name) and its ARNs (/applications/, /jobruns/) by hand, and skipped the checks a direct request gets beside its own action: iam:PassRole on StartJobRun's execution role, and emr-serverless:TagResource on the tags CreateApplication and StartJobRun send. A new RequestChecks reads a JSON request as the enforcement filter reads the same request made directly: the action from IamAuthorizedActions, its resources from RequestResources.ofBody, the request's tags on the action where the tag-on-create table says it takes them, iam:PassRole on each role the passed-roles table reads with iam:PassedToService, and the tagging action on what a create makes. PassedRoles, TagOnCreate and RequestResources.created gain a body form for it. The arm now hands RequestChecks the request the integration sends EMR Serverless, so a regeneration of any of those tables moves the task and the direct call together. --- docs/services/step-functions.md | 10 ++- .../io/floci/aws/core/common/PassedRoles.java | 31 ++++++-- .../floci/aws/core/common/RequestChecks.java | 73 +++++++++++++++++++ .../aws/core/common/RequestResources.java | 31 +++++++- .../io/floci/aws/core/common/TagOnCreate.java | 15 +++- .../EmrServerlessTaskInvoker.java | 39 ++++++++-- .../stepfunctions/TaskPermissions.java | 30 +++----- .../aws/core/common/RequestChecksTest.java | 63 ++++++++++++++++ ...tepFunctionsJobTaskIamIntegrationTest.java | 52 ++++++++++++- .../stepfunctions/TaskPermissionsTest.java | 31 ++++++++ 10 files changed, 338 insertions(+), 37 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/RequestChecks.java create mode 100644 src/test/java/io/floci/aws/core/common/RequestChecksTest.java diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 011bfe6ae5..f5cdb351ef 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -747,8 +747,14 @@ calls, and it is what the CDK's policies for these two tasks grant. `.sync` authorizes the starting call only: a job cannot fail midway through its wait for lack of a Describe permission, and the best-effort cancel of an abandoned job is not evaluated either. What the CDK grants a `.sync` task beyond that, such as `elasticmapreduce:DescribeStep` or `ecs:DescribeTasks`, -is accepted but not needed here. `iam:PassRole` is not evaluated for the roles `runTask`, `createCluster` or -`startJobRun` pass, nor a tagging action such as `elasticmapreduce:AddTags` for what they tag. +is accepted but not needed here. `iam:PassRole` is not evaluated for the roles `runTask` or `createCluster` +pass, nor a tagging action such as `elasticmapreduce:AddTags` for what they tag. + +An EMR Serverless API is checked as the same request made directly is, from the generated tables, on the +request the integration sends: `startJobRun` also needs `iam:PassRole` on its `ExecutionRoleArn`, passed to +`emr-serverless.amazonaws.com`, and `createApplication` and `startJobRun` need `emr-serverless:TagResource` +for the `Tags` they send, on the application a create makes or the one a job run is checked on, with each +tag as `aws:RequestTag/` and the keys as `aws:TagKeys`, which the API's own action is checked with too. A request naming nothing it can reach has only the role checks, and its service answers it: no `TaskDefinition` or one ECS does not have, a service or cluster ECS does not have, no `ClusterId`, no diff --git a/src/main/java/io/floci/aws/core/common/PassedRoles.java b/src/main/java/io/floci/aws/core/common/PassedRoles.java index ea4a905988..74fc84bca9 100644 --- a/src/main/java/io/floci/aws/core/common/PassedRoles.java +++ b/src/main/java/io/floci/aws/core/common/PassedRoles.java @@ -16,6 +16,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -349,7 +350,26 @@ final class PassedRoles { return List.of(); } Map form = IamConditionContextResolver.formParameters(ctx); - JsonNode body = form.isEmpty() ? jsonBody(ctx) : null; + return fromTable(members, form, form.isEmpty() ? jsonBody(ctx) : null, + name -> lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name))); + } + + /** + * The roles a JSON request for {@code action} passes, for a call that is not an HTTP request of its own (a state + * machine's task to its integrated service), read from the members the table gives its operation as a direct + * request's are, a role given by name being the one {@code named} gives. An operation whose roles are read by + * hand here, from a request of its own, is not read so, and fails. + */ + static List ofBody(String action, JsonNode body, UnaryOperator named) { + if (PassedRoleMembers.table().byHand().contains(action)) { + throw new IllegalArgumentException(action + " passes roles read by hand, from a request of its own"); + } + List members = PassedRoleMembers.of(action); + return members == null ? List.of() : fromTable(members, Map.of(), body, named); + } + + private static List fromTable(List members, Map form, + JsonNode body, UnaryOperator named) { List passed = new ArrayList<>(); for (PassedRoleMembers.Member member : members) { List roles = new ArrayList<>(); @@ -364,7 +384,7 @@ final class PassedRoles { } else { collect(body, member.steps(), 0, roles); } - passed.addAll(passed(member.byName() ? heldOrNamedRoles(roles, lookups) : roles, + passed.addAll(passed(member.byName() ? heldOrNamedRoles(roles, named) : roles, member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo()))); } return passed; @@ -395,13 +415,12 @@ final class PassedRoles { } } - /** Roles given by ARN or by name: a name is the role IAM holds under it, or else the one it gives. */ - private static List heldOrNamedRoles(List roles, Lookups lookups) { + /** Roles given by ARN or by name, a name being the role {@code named} gives for it. */ + private static List heldOrNamedRoles(List roles, UnaryOperator named) { List arns = new ArrayList<>(); for (String role : roles) { if (!role.isBlank()) { - arns.add(AwsArnUtils.looksLikeArn(role) ? role - : lookups.heldRoleArn(role).orElseGet(() -> lookups.roleArn(role))); + arns.add(AwsArnUtils.looksLikeArn(role) ? role : named.apply(role)); } } return arns; diff --git a/src/main/java/io/floci/aws/core/common/RequestChecks.java b/src/main/java/io/floci/aws/core/common/RequestChecks.java new file mode 100644 index 0000000000..015a82a6f1 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/RequestChecks.java @@ -0,0 +1,73 @@ +package io.floci.aws.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import io.floci.aws.services.iam.IamAuthorizedActions; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * What a JSON request needs from IAM, read as the enforcement filter reads the same request made directly, for a call + * that is not an HTTP request of its own: a state machine's task to its integrated service, made as the role the task + * runs as. That is the operation's action on each resource it names ({@link RequestResources#ofBody}), or on + * {@code *} when it names none, as the filter falls back to, with the tags it carries where the action takes them; + * {@code iam:PassRole} on each role it passes ({@link PassedRoles}), with {@code iam:PassedToService}; and the + * service's tagging action on what it creates, for each set of tags it carries ({@link TagOnCreate}). A regeneration + * of any of those tables moves the call and the direct request together. + */ +public final class RequestChecks { + + /** One action on one resource, with the condition keys the request gives it. */ + public record Check(String action, String resource, Map> context) { + } + + private RequestChecks() { + } + + /** + * The checks a JSON request for {@code operation}, as {@code :}, needs in the partition, + * Region and account given, {@code stored} finding what it names by name ({@link StoredResourceArns}); none for an + * operation the request-resource table does not read. A role given by name is the account's of that name. An + * operation passing roles read by hand, from a request of its own, is not read here, and fails. + */ + public static List of(String operation, JsonNode body, String partition, String region, String accountId, + StoredResourceArns stored) { + if (!RequestResources.reads(operation)) { + return List.of(); + } + int colon = operation.indexOf(':'); + String action = IamAuthorizedActions.actionFor(operation.substring(0, colon), operation.substring(colon + 1)); + List named = RequestResources.actsOnNoResource(operation) ? List.of() + : RequestResources.ofBody(operation, body, partition, region, accountId, stored); + // A request naming none of its resources is checked on *, as the filter checks it. + List resources = named.isEmpty() ? List.of("*") : named; + Optional tagging = TagOnCreate.ofBody(operation, body); + // The operation's own action takes the tags where the table says it does, once for each reading of them. + List>> contexts = tagging.filter(TagOnCreate.Tagging::requestTags) + .map(TagOnCreate::requestTagContexts).filter(found -> !found.isEmpty()).orElse(List.of(Map.of())); + List checks = new ArrayList<>(); + for (String resource : resources) { + contexts.forEach(context -> checks.add(new Check(action, resource, Map.copyOf(context)))); + } + for (PassedRoles.PassedRole passed : PassedRoles.ofBody(action, body, + name -> new AwsArnUtils.Arn(partition, "iam", "", accountId, "role/" + name).toString())) { + checks.add(new Check("iam:PassRole", passed.roleArn(), passed.passedToService() == null ? Map.of() + : Map.of("iam:PassedToService", List.of(passed.passedToService())))); + } + if (tagging.isPresent()) { + // A create tags the resource it makes, not the parent it makes it in, as the filter checks it. + List created = RequestResources.created(operation, tagging.get().action(), body, partition, region, + accountId); + List made = created.isEmpty() ? resources : created; + for (TagOnCreate.TagSet set : tagging.get().checked()) { + Map> context = TagOnCreate.conditionContext(tagging.get(), set, operation); + for (String resource : TagOnCreate.resources(operation, set, partition, region, accountId, made)) { + checks.add(new Check(tagging.get().action(), resource, Map.copyOf(context))); + } + } + } + return List.copyOf(checks); + } +} diff --git a/src/main/java/io/floci/aws/core/common/RequestResources.java b/src/main/java/io/floci/aws/core/common/RequestResources.java index 9f3c0fcc1c..ac8c2048b2 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResources.java +++ b/src/main/java/io/floci/aws/core/common/RequestResources.java @@ -17,6 +17,8 @@ import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -306,9 +308,31 @@ public final class RequestResources { public static List created(String operation, String tagging, ContainerRequestContext ctx, String partition, String region, String accountId, Map labels) { RequestResourceMembers.Table table = RequestResourceMembers.table(); + return created(table, operation, tagging, resources -> served(resources, ctx), + () -> located(table, operation, IamConditionContextResolver.formParameters(ctx), ctx, labels), + () -> IamConditionContextResolver.formParameters(ctx).isEmpty() + ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null, + partition, region, accountId); + } + + /** + * As {@link #created(String, String, ContainerRequestContext, String, String, String, Map)}, for a JSON request + * body that is not an HTTP request of its own (a state machine's task to its integrated service): its members + * the table locates in a path given in the body, and every resource applying, whatever endpoint it would reach. + */ + public static List created(String operation, String tagging, JsonNode body, String partition, + String region, String accountId) { + return created(RequestResourceMembers.table(), operation, tagging, resources -> resources, Map::of, + () -> body, partition, region, accountId); + } + + private static List created(RequestResourceMembers.Table table, String operation, String tagging, + UnaryOperator> serving, + Supplier> sentForm, Supplier sentBody, + String partition, String region, String accountId) { List creates = operation == null ? null : table.creates().get(operation); List made = operation == null || creates != null ? List.of() - : served(table.operations().getOrDefault(operation, List.of()), ctx).stream() + : serving.apply(table.operations().getOrDefault(operation, List.of())).stream() .filter(RequestResourceMembers.Resource::made).toList(); if (creates == null && made.isEmpty() && operation != null) { made = table.makes().getOrDefault(operation, List.of()).stream() @@ -319,9 +343,8 @@ public final class RequestResources { if (creates == null && made.isEmpty()) { return List.of(); } - Map sent = IamConditionContextResolver.formParameters(ctx); - JsonNode body = sent.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null; - Map form = located(table, operation, sent, ctx, labels); + JsonNode body = sentBody.get(); + Map form = sentForm.get(); Map formats = formats(table, operation); if (creates == null) { return named(operation, made, formats, form, body, partition, region, accountId, null); diff --git a/src/main/java/io/floci/aws/core/common/TagOnCreate.java b/src/main/java/io/floci/aws/core/common/TagOnCreate.java index ca971f867c..30c13428f8 100644 --- a/src/main/java/io/floci/aws/core/common/TagOnCreate.java +++ b/src/main/java/io/floci/aws/core/common/TagOnCreate.java @@ -88,7 +88,20 @@ final class TagOnCreate { return Optional.empty(); } Map form = IamConditionContextResolver.formParameters(ctx); - JsonNode body = form.isEmpty() ? PassedRoles.jsonBody(ctx) : null; + return of(operation, entry, form, form.isEmpty() ? PassedRoles.jsonBody(ctx) : null); + } + + /** + * As {@link #of(String, ContainerRequestContext)}, for a JSON request that is not an HTTP request of its own (a + * state machine's task to its integrated service). + */ + static Optional ofBody(String operation, JsonNode body) { + TagOnCreateMembers.Entry entry = TagOnCreateMembers.of(operation); + return entry == null ? Optional.empty() : of(operation, entry, Map.of(), body); + } + + private static Optional of(String operation, TagOnCreateMembers.Entry entry, Map form, + JsonNode body) { Set sets = new LinkedHashSet<>(); Set otherSpellings = new LinkedHashSet<>(); for (TagOnCreateMembers.Member member : entry.members()) { diff --git a/src/main/java/io/floci/aws/services/stepfunctions/EmrServerlessTaskInvoker.java b/src/main/java/io/floci/aws/services/stepfunctions/EmrServerlessTaskInvoker.java index f34ec4c361..a8da0b9f8e 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/EmrServerlessTaskInvoker.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/EmrServerlessTaskInvoker.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.MissingNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsException; @@ -232,7 +233,7 @@ public class EmrServerlessTaskInvoker { * the model does not have is dropped, as the API has no place for it, such as a request's * {@code ApplicationId}, which travels in the path. */ - private JsonNode recase(JsonNode node, String shapeName, boolean toStates) { + private static JsonNode recase(JsonNode node, String shapeName, boolean toStates) { RequestShapeModel.Shape shape = shapeName == null ? null : SHAPES.shapes().get(shapeName); if (shape == null) { return node.deepCopy(); @@ -243,7 +244,7 @@ public class EmrServerlessTaskInvoker { if (!node.isArray()) { yield node.deepCopy(); } - ArrayNode items = objectMapper.createArrayNode(); + ArrayNode items = JsonNodeFactory.instance.arrayNode(); node.forEach(item -> items.add(recase(item, shape.element(), toStates))); yield items; } @@ -251,7 +252,7 @@ public class EmrServerlessTaskInvoker { if (!node.isObject()) { yield node.deepCopy(); } - ObjectNode entries = objectMapper.createObjectNode(); + ObjectNode entries = JsonNodeFactory.instance.objectNode(); node.properties().forEach(entry -> entries.set(entry.getKey(), recase(entry.getValue(), shape.element(), toStates))); yield entries; @@ -261,8 +262,8 @@ public class EmrServerlessTaskInvoker { } /** The structure's members in the model's order, each from the first field naming it in any case. */ - private ObjectNode recaseStructure(JsonNode node, RequestShapeModel.Shape shape, boolean toStates) { - ObjectNode members = objectMapper.createObjectNode(); + private static ObjectNode recaseStructure(JsonNode node, RequestShapeModel.Shape shape, boolean toStates) { + ObjectNode members = JsonNodeFactory.instance.objectNode(); for (Map.Entry member : shape.members().entrySet()) { String name = member.getKey(); JsonNode value = field(node, name); @@ -279,6 +280,34 @@ public class EmrServerlessTaskInvoker { return requiredText(field(request, name), name); } + /** + * The request the API sends EMR Serverless, its members as the operation's model names them, with the ids it sends + * in the path as members too ({@code applicationId}, and {@code jobRunId} to cancel), each read in either case as + * the integration reads it: what IAM checks the call on, as it checks the same request made directly. + */ + static ObjectNode apiRequest(String api, JsonNode input) { + JsonNode request = input != null && input.isObject() ? input : JsonNodeFactory.instance.objectNode(); + ObjectNode sent = switch (api) { + case "createApplication" -> recaseStructure(request, SHAPES.shapes().get("CreateApplicationRequest"), false); + case "startJobRun" -> recaseStructure(request, SHAPES.shapes().get("StartJobRunRequest"), false); + default -> JsonNodeFactory.instance.objectNode(); + }; + if (!"createApplication".equals(api)) { + putId(sent, request, "applicationId"); + } + if ("cancelJobRun".equals(api)) { + putId(sent, request, "jobRunId"); + } + return sent; + } + + private static void putId(ObjectNode sent, JsonNode request, String name) { + JsonNode id = field(request, name); + if (id.isTextual() && !id.asText().isBlank()) { + sent.put(name, id.asText()); + } + } + /** The first of {@code node}'s fields named {@code name} in any case, or a missing node. */ static JsonNode field(JsonNode node, String name) { for (Map.Entry field : node.properties()) { diff --git a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java index ab8e86dce1..00843d3ab6 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RequestChecks; import io.floci.aws.core.common.RequestResources; import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser; @@ -409,29 +410,22 @@ record TaskPermissions(String deniedError, List permissions) { } /** - * The action of the API's own name on the application or job run it names, the ids read in either case as the - * integration reads them. A request missing one is refused by the integration. {@code CreateApplication} has no - * resource type in the service reference. + * The checks the request the integration sends EMR Serverless needs, as the same request made directly does + * ({@link RequestChecks}): its action on the application or job run it names, {@code CreateApplication} on no + * resource; {@code iam:PassRole} on a job run's execution role; and {@code emr-serverless:TagResource} on what a + * create or a job run tags, with the tags as condition keys of both. A request missing an id the integration + * requires is refused by it. */ private static TaskPermissions emrServerless(String api, JsonNode input, StateMachine machine) { - String action = "emr-serverless:" + AslExecutor.capitalizeFirst(api); - if ("createApplication".equals(api)) { - return accessDenied(EMR_SERVERLESS_PREFIX, List.of(new Permission(action, ANY_RESOURCE))); - } - String application = text(EmrServerlessTaskInvoker.field(input, "ApplicationId")); - String jobRun = text(EmrServerlessTaskInvoker.field(input, "JobRunId")); - if (application == null || "cancelJobRun".equals(api) && jobRun == null) { + ObjectNode request = EmrServerlessTaskInvoker.apiRequest(api, input); + if (!"createApplication".equals(api) && !request.has("applicationId") + || "cancelJobRun".equals(api) && !request.has("jobRunId")) { return accessDenied(EMR_SERVERLESS_PREFIX, List.of()); } - String resource = "/applications/" + application + ("cancelJobRun".equals(api) ? "/jobruns/" + jobRun : ""); - return accessDenied(EMR_SERVERLESS_PREFIX, - List.of(new Permission(action, arn(machine, "emr-serverless", resource)))); - } - - /** The ARN of a resource of the state machine's partition, Region and account. */ - private static String arn(StateMachine machine, String service, String resource) { AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); - return new AwsArnUtils.Arn(owner.partition(), service, owner.region(), owner.accountId(), resource).toString(); + return accessDenied(EMR_SERVERLESS_PREFIX, RequestChecks.of("emr-serverless:" + AslExecutor.capitalizeFirst(api), + request, owner.partition(), owner.region(), owner.accountId(), null).stream() + .map(check -> new Permission(check.action(), check.resource(), check.context())).toList()); } private static String regionOf(StateMachine machine) { diff --git a/src/test/java/io/floci/aws/core/common/RequestChecksTest.java b/src/test/java/io/floci/aws/core/common/RequestChecksTest.java new file mode 100644 index 0000000000..aaba32db93 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/RequestChecksTest.java @@ -0,0 +1,63 @@ +package io.floci.aws.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +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.junit.jupiter.api.Assertions.assertThrows; + +/** A JSON request is checked as the enforcement filter checks the same request made directly. */ +class RequestChecksTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String APPLICATION = "arn:aws:emr-serverless:us-east-1:000000000000:/applications/a"; + + private static List checks(String operation, String body) throws Exception { + return RequestChecks.of(operation, MAPPER.readTree(body), "aws", "us-east-1", "000000000000", null); + } + + @Test + void anOperationIsCheckedOnTheResourcesItsRequestNames() throws Exception { + assertEquals(List.of(new RequestChecks.Check("emr-serverless:StartApplication", APPLICATION, Map.of())), + checks("emr-serverless:StartApplication", "{\"applicationId\":\"a\"}")); + assertEquals(List.of(new RequestChecks.Check("emr-serverless:CreateApplication", "*", Map.of())), + checks("emr-serverless:CreateApplication", "{}")); + } + + /** A request naming none of the resources its operation acts on is checked on {@code *}, as the filter does. */ + @Test + void aRequestNamingNoneOfItsResourcesIsCheckedOnAnyResource() throws Exception { + assertEquals(List.of(new RequestChecks.Check("emr-serverless:StartApplication", "*", Map.of())), + checks("emr-serverless:StartApplication", "{}")); + } + + @Test + void aJobRunsRoleAndTagsAreCheckedBesideItsAction() throws Exception { + String role = "arn:aws:iam::000000000000:role/job"; + Map> tagged = Map.of("aws:RequestTag/team", List.of("data"), "aws:TagKeys", List.of("team")); + assertEquals(List.of(new RequestChecks.Check("emr-serverless:StartJobRun", APPLICATION, tagged), + new RequestChecks.Check("iam:PassRole", role, + Map.of("iam:PassedToService", List.of("emr-serverless.amazonaws.com"))), + new RequestChecks.Check("emr-serverless:TagResource", APPLICATION, tagged)), + checks("emr-serverless:StartJobRun", + "{\"applicationId\":\"a\",\"executionRoleArn\":\"" + role + "\",\"tags\":{\"team\":\"data\"}}")); + } + + /** An operation whose passed roles are read by hand, from a request of its own, is refused rather than misread. */ + @Test + void anOperationPassingRolesReadByHandIsNotReadFromABody() { + assertThrows(IllegalArgumentException.class, + () -> checks("states:CreateStateMachine", "{\"name\":\"m\",\"roleArn\":\"arn:aws:iam::000000000000:role/r\"}")); + } + + /** An operation the request-resource table does not read needs nothing here. */ + @Test + void anOperationTheTableDoesNotReadNeedsNothing() throws Exception { + JsonNode body = MAPPER.readTree("{}"); + assertEquals(List.of(), RequestChecks.of("nothing:DoesIt", body, "aws", "us-east-1", "000000000000", null)); + } +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java index 62d40beb29..e9f8aeede2 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java @@ -215,6 +215,51 @@ class StepFunctionsJobTaskIamIntegrationTest { target.notReached().check(); } + /** + * A job run passes its execution role to EMR Serverless as a direct {@code StartJobRun} does, so the role the task + * runs as needs {@code iam:PassRole} on it beside the action on the application. + */ + @Test + void aJobRunNeedsPassRoleOnItsExecutionRole() throws Exception { + Target target = startJobRunTarget(); + String role = role(STATES_TRUST, allow(target.resourceArn(), target.actions())); + + Response refused = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(refused, target.error()); + String cause = refused.jsonPath().getString("cause"); + assertTrue(cause.contains("iam:PassRole") && cause.contains(target.arguments().get("ExecutionRoleArn").toString()), + cause); + target.notReached().check(); + } + + /** + * Tags an application is created with need {@code emr-serverless:TagResource} on the application it makes, as a + * direct {@code CreateApplication} does, and the create itself is checked with them. + */ + @Test + void tagsAnApplicationIsCreatedWithNeedTagResource() throws Exception { + Target untagged = createApplicationTarget(); + Map arguments = new LinkedHashMap<>(untagged.arguments()); + arguments.put("Tags", Map.of("team", "data")); + Target target = new Target(untagged.integration(), untagged.error(), untagged.resourceArn(), arguments, + untagged.reached(), untagged.notReached(), untagged.actions()); + + Response refused = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, target.grant())), "{}")); + assertFailed(refused, target.error()); + assertTrue(refused.jsonPath().getString("cause").contains("emr-serverless:TagResource"), refused.asString()); + target.notReached().check(); + + Response created = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, policy(List.of( + Map.of("Effect", "Allow", "Action", List.of("emr-serverless:CreateApplication"), "Resource", List.of("*"), + "Condition", Map.of("StringEquals", Map.of("aws:RequestTag/team", "data"))), + Map.of("Effect", "Allow", "Action", List.of("emr-serverless:TagResource"), + "Resource", List.of("arn:aws:emr-serverless:" + REGION + ":" + ACCOUNT + ":/applications/*")))))), + "{}")); + assertEquals("SUCCEEDED", created.jsonPath().getString("status"), created.asString()); + target.reached().check(); + } + @ParameterizedTest @MethodSource("eachIntegration") void aCredentialsRoleNotAllowedTheActionIsRefusedEvenIfTheExecutionRoleIs(String integration) throws Exception { @@ -530,8 +575,13 @@ class StepFunctionsJobTaskIamIntegrationTest { return actions[0]; } + /** The actions on the resource, and {@code iam:PassRole} on the execution role a request passes, if any. */ String grant() { - return allow(resourceArn, actions); + Object role = arguments.get("ExecutionRoleArn"); + Map onResource = Map.of("Effect", "Allow", "Action", List.of(actions), + "Resource", List.of(resourceArn)); + return policy(role == null ? List.of(onResource) : List.of(onResource, Map.of("Effect", "Allow", + "Action", List.of("iam:PassRole"), "Resource", List.of(role.toString())))); } } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java index f7bdf2d4ca..8a23cb2f3f 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java @@ -587,6 +587,37 @@ class TaskPermissionsTest { .orElseThrow().permissions()); } + /** A job run passes its execution role to EMR Serverless, as a direct {@code StartJobRun} does. */ + @Test + void aJobRunNeedsPassRoleOnItsExecutionRole() throws Exception { + String role = "arn:aws:iam::111122223333:role/job"; + assertEquals(List.of(new Permission("emr-serverless:StartJobRun", APPLICATION), + new Permission("iam:PassRole", role, + Map.of("iam:PassedToService", List.of("emr-serverless.amazonaws.com")))), + TaskPermissions.of(integration("emr-serverless:startJobRun"), + json("{\"ApplicationId\":\"a\",\"ExecutionRoleArn\":\"" + role + "\"}"), machine("aws")) + .orElseThrow().permissions()); + } + + /** + * Tags a create or a job run sends need {@code emr-serverless:TagResource}, on the application a create makes or + * the one a job run is checked on, as a direct request's do, and the call itself is checked with them. + */ + @Test + void tagsACreateOrAJobRunSendsNeedTagResource() throws Exception { + Map> tagged = Map.of("aws:RequestTag/team", List.of("data"), "aws:TagKeys", List.of("team")); + assertEquals(List.of(new Permission("emr-serverless:CreateApplication", "*", tagged), + new Permission("emr-serverless:TagResource", + "arn:aws:emr-serverless:eu-west-1:111122223333:/applications/*", tagged)), + TaskPermissions.of(integration("emr-serverless:createApplication"), + json("{\"Tags\":{\"team\":\"data\"}}"), machine("aws")).orElseThrow().permissions()); + assertEquals(List.of(new Permission("emr-serverless:StartJobRun", APPLICATION, tagged), + new Permission("emr-serverless:TagResource", APPLICATION, tagged)), + TaskPermissions.of(integration("emr-serverless:startJobRun"), + json("{\"ApplicationId\":\"a\",\"Tags\":{\"team\":\"data\"}}"), machine("aws")) + .orElseThrow().permissions()); + } + private static TaskPermissions ecsPermissions(String tail, String request, EcsService ecs) throws Exception { return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, ecs, false).orElseThrow(); }