diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index a2bb8a84b2..2b22d40f95 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -3,12 +3,9 @@ package io.floci.aws.core.common; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.services.dynamodb.DynamoDbConditionKeys; import io.floci.aws.services.dynamodb.DynamoDbFacade; -import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser; -import io.floci.aws.services.dynamodb.DynamoDbTableNames; import io.floci.aws.services.dynamodb.model.TableDefinition; import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ec2.model.Tag; @@ -1007,18 +1004,13 @@ public class IamConditionContextResolver { public List>> resolveRemainingTargets(String credentialScope, String action, ContainerRequestContext ctx) { if ("dynamodb".equals(credentialScope)) { - List modes = singleItemReturnValues(action, bufferedJsonBody(ctx)); - if (modes.size() < 2) { + JsonNode body = bufferedJsonBody(ctx); + if (DynamoDbConditionKeys.returnValues(action, body).size() < 2) { return List.of(); } - Map> primary = dynamoDbConditionContext(action, ctx); - List>> contexts = new ArrayList<>(); - for (int i = 1; i < modes.size(); i++) { - Map> context = new LinkedHashMap<>(primary); - context.put("dynamodb:ReturnValues", List.of(modes.get(i))); - contexts.add(context); - } - return contexts; + List>> contexts = DynamoDbConditionKeys.perReturnMode(action, body, + dynamoDbConditionContext(action, ctx)); + return contexts.subList(1, contexts.size()); } if (!"ec2".equals(credentialScope)) { return List.of(); @@ -1346,41 +1338,9 @@ public class IamConditionContextResolver { TableDefinition table = describeTargetTable(targetTableName(body)); DynamoDbConditionKeys.Result keys = dynamoDbKeys(action, body, table, ctx); - Map> conditions = new LinkedHashMap<>(); - putKeyConditions(conditions, keys); - List returnValues = singleItemReturnValues(action, body); - if (!returnValues.isEmpty()) { - conditions.put("dynamodb:ReturnValues", List.of(returnValues.getFirst())); - } - return conditions.isEmpty() ? null : conditions; - } - - /** Adds the request-derived {@code LeadingKeys}, {@code Attributes} and {@code Select} that were resolved. */ - private static void putKeyConditions(Map> conditions, DynamoDbConditionKeys.Result keys) { - if (!keys.leadingKeys().isEmpty()) { - conditions.put("dynamodb:LeadingKeys", keys.leadingKeys()); - } - if (!keys.attributes().isEmpty()) { - conditions.put("dynamodb:Attributes", keys.attributes()); - } - if (keys.select() != null) { - conditions.put("dynamodb:Select", List.of(keys.select())); - } - } - - private static List singleItemReturnValues(String action, JsonNode body) { - if (!("dynamodb:PutItem".equals(action) || "dynamodb:UpdateItem".equals(action) - || "dynamodb:DeleteItem".equals(action)) || body == null || !body.isObject()) { - return List.of(); - } - Set modes = new LinkedHashSet<>(); - for (String field : List.of("ReturnValues", "ReturnValuesOnConditionCheckFailure")) { - String mode = body.path(field).asText("NONE"); - if (!"NONE".equals(mode)) { - modes.add(mode); - } - } - return modes.isEmpty() ? List.of("NONE") : List.copyOf(modes); + Map> conditions = DynamoDbConditionKeys.perReturnMode(action, body, keys.conditionKeys()) + .getFirst(); + return conditions.isEmpty() ? null : new LinkedHashMap<>(conditions); } /** @@ -1396,32 +1356,7 @@ public class IamConditionContextResolver { return resolve(credentialScope, action, ctx); } String enclosing = operation.substring(operation.indexOf(':') + 1); - Map> context = new LinkedHashMap<>(); - if (part.has("Statement")) { - String statement = DynamoDbConditionKeys.partiQLStatement(part); - if ("ExecuteTransaction".equals(enclosing)) { - context.put("dynamodb:EnclosingOperation", List.of(enclosing)); - } - putKeyConditions(context, DynamoDbConditionKeys.extract(action, part, - describeTargetTable(DynamoDbPartiQLParser.extractTable(statement)))); - return context; - } - boolean read = "TransactGetItems".equals(enclosing); - String tableName = targetTableName(part); - TableDefinition table; - try { - table = describeTargetTable(tableName == null ? null - : DynamoDbTableNames.resolveWithRegion(tableName, region).name()); - } catch (AwsException e) { - table = null; - } - context.put("dynamodb:EnclosingOperation", List.of(enclosing)); - putKeyConditions(context, read ? DynamoDbConditionKeys.extractTransactionGet(part, table) - : DynamoDbConditionKeys.extract(action, part, table)); - if (!read && part.hasNonNull("ReturnValuesOnConditionCheckFailure")) { - context.put("dynamodb:ReturnValues", List.of(part.path("ReturnValuesOnConditionCheckFailure").asText())); - } - return context; + return DynamoDbConditionKeys.partConditionKeys(action, enclosing, part, this::describeTargetTable, region); } /** Request-wide context for callers that do not yet have a resolved resource. */ @@ -1446,23 +1381,19 @@ public class IamConditionContextResolver { } List>> contexts = new ArrayList<>(); JsonNode body = bufferedJsonBody(ctx); - JsonNode items = body == null ? null : body.get("RequestItems"); + JsonNode items = body == null || !body.isObject() ? null : body.get("RequestItems"); if (items == null || !items.isObject()) { return List.of(Map.of()); } + // Only the tables the checked resource names are copied out, each as a shallow copy of the batch. items.properties().forEach(entry -> { String reference = entry.getKey().trim(); if (resourceArn != null && !matchesTableResource(reference, resourceArn)) { return; } - ObjectNode single = ((ObjectNode) body).objectNode(); - single.setAll((ObjectNode) body); - single.putObject("RequestItems").set(entry.getKey(), entry.getValue()); - DynamoDbConditionKeys.Result keys = dynamoDbKeys( - action, single, describeTargetTable(reference), ctx); - Map> conditions = new LinkedHashMap<>(); - putKeyConditions(conditions, keys); - contexts.add(conditions); + DynamoDbConditionKeys.Result keys = dynamoDbKeys(action, + DynamoDbConditionKeys.batchTableRequest(body, entry.getKey()), describeTargetTable(reference), ctx); + contexts.add(new LinkedHashMap<>(keys.conditionKeys())); }); return contexts.isEmpty() ? List.of(Map.of()) : contexts; } diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 4ec16896e3..97554aab5a 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -25,7 +25,6 @@ import io.floci.aws.services.iam.ResourcePolicyProvider; import io.floci.aws.services.iam.ResourcePolicyProviders; import io.floci.aws.services.iam.ScpProvider; import io.floci.aws.services.iam.model.CallerContext; -import io.floci.aws.services.iam.model.IamRole; import io.floci.aws.services.s3.S3ObjectActions; import io.floci.aws.services.s3.S3ScratchSpace; import io.floci.aws.services.s3.S3Service; @@ -1118,87 +1117,13 @@ public class IamEnforcementFilter implements ContainerRequestFilter { /** What {@link PassedRoles} looks up, in the request's account and Region. */ private PassedRoles.Lookups lookupsFor(String accountId, String region) { - return new PassedRoles.Lookups() { - @Override - public List instanceProfileRoleArns(String profileName, String profileArn) { - return IamEnforcementFilter.this.instanceProfileRoleArns(accountId, profileName, profileArn); - } - - @Override - public List taskDefinitionRoles(String reference) { - List roles = new ArrayList<>(); - for (PassedRoleLookup lookup : roleLookups()) { - roles.addAll(lookup.taskDefinitionRoles(reference, region)); - } - return roles; - } - - @Override - public Optional stackSetPermissionModel(String stackSetName) { - return firstFound(lookup -> lookup.stackSetPermissionModel(stackSetName)); - } - - @Override - public Optional launchTemplateInstanceProfile(String templateId, String templateName, - String version) { - return firstFound(lookup -> lookup.launchTemplateInstanceProfile(templateId, templateName, version, - region)); - } - - @Override - public Optional launchConfigurationInstanceProfile(String instanceId) { - return firstFound(lookup -> lookup.launchConfigurationInstanceProfile(instanceId, region)); - } - - @Override - public Optional instanceRefreshInstanceProfile(String groupName, String templateId, - String templateName, String version) { - return firstFound(lookup -> lookup.instanceRefreshInstanceProfile(groupName, templateId, templateName, - version, region)); - } - - @Override - public String roleArn(String roleName) { - return AwsArnUtils.Arn.global(requestPartition(), "iam", accountId, "role/" + roleName).toString(); - } - - @Override - public Optional heldRoleArn(String roleName) { - return iamService.findRole(accountId, roleName).map(IamRole::getArn); - } - - @Override - public Optional serviceCatalogConstraintType(String constraintId) { - return firstFound(lookup -> lookup.serviceCatalogConstraintType(constraintId)); - } - }; + return new PassedRoleLookups(iamService, roleLookups()).in(requestPartition(), accountId, region); } private Iterable roleLookups() { return passedRoleLookups == null || passedRoleLookups.isUnsatisfied() ? List.of() : passedRoleLookups; } - /** The first answer a {@link PassedRoleLookup} gives, each answering only for what its service owns. */ - private Optional firstFound(Function> question) { - for (PassedRoleLookup lookup : roleLookups()) { - Optional answer = question.apply(lookup); - if (answer.isPresent()) { - return answer; - } - } - return Optional.empty(); - } - - /** The ARNs of the roles the instance profile, named by {@code name} or {@code arn}, holds. */ - private List instanceProfileRoleArns(String accountId, String name, String arn) { - return IamService.instanceProfileNamed(iamService, accountId, arn != null ? arn : name) - .map(profile -> profile.getRoleNames().stream() - .flatMap(roleName -> iamService.findRole(accountId, roleName).stream()) - .map(IamRole::getArn) - .toList()) - .orElse(List.of()); - } - /** * Evaluates one action against every resource and target context, aborting the request with * AccessDenied on the first DENY. Returns true when the request was aborted. diff --git a/src/main/java/io/floci/aws/core/common/PassedRoleLookups.java b/src/main/java/io/floci/aws/core/common/PassedRoleLookups.java new file mode 100644 index 0000000000..ed2ddb4e07 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/PassedRoleLookups.java @@ -0,0 +1,127 @@ +package io.floci.aws.core.common; + +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.PassedRoleLookup; +import io.floci.aws.services.iam.model.IamRole; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; +import jakarta.inject.Inject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + +/** + * What {@link PassedRoles} looks up to find the roles a request passes, in one account and Region: the roles IAM holds + * and the instance profiles holding them, and what the services owning a resource that names roles answer + * ({@link PassedRoleLookup}). A request made directly and a call made on a caller's behalf (a state machine's task) + * look them up alike. + */ +@ApplicationScoped +public class PassedRoleLookups { + + private final IamService iamService; + private final Iterable services; + + @Inject + public PassedRoleLookups(IamService iamService, Instance services) { + this(iamService, (Iterable) services); + } + + /** + * @param iamService the roles and instance profiles IAM holds; without it IAM holds none + * @param services the services that answer for a resource of theirs; without them none answers + */ + public PassedRoleLookups(IamService iamService, Iterable services) { + this.iamService = iamService; + this.services = services; + } + + /** What is looked up for a request made in {@code accountId} and {@code region}, in {@code partition}. */ + PassedRoles.Lookups in(String partition, String accountId, String region) { + return new PassedRoles.Lookups() { + @Override + public List instanceProfileRoleArns(String profileName, String profileArn) { + return PassedRoleLookups.this.instanceProfileRoleArns(accountId, profileName, profileArn); + } + + @Override + public List taskDefinitionRoles(String reference) { + List roles = new ArrayList<>(); + for (PassedRoleLookup lookup : services()) { + roles.addAll(lookup.taskDefinitionRoles(reference, region)); + } + return roles; + } + + @Override + public Optional stackSetPermissionModel(String stackSetName) { + return firstFound(lookup -> lookup.stackSetPermissionModel(stackSetName)); + } + + @Override + public Optional launchTemplateInstanceProfile(String templateId, String templateName, + String version) { + return firstFound(lookup -> lookup.launchTemplateInstanceProfile(templateId, templateName, version, + region)); + } + + @Override + public Optional launchConfigurationInstanceProfile(String instanceId) { + return firstFound(lookup -> lookup.launchConfigurationInstanceProfile(instanceId, region)); + } + + @Override + public Optional instanceRefreshInstanceProfile(String groupName, String templateId, + String templateName, String version) { + return firstFound(lookup -> lookup.instanceRefreshInstanceProfile(groupName, templateId, templateName, + version, region)); + } + + @Override + public String roleArn(String roleName) { + return AwsArnUtils.Arn.global(partition, "iam", accountId, "role/" + roleName).toString(); + } + + @Override + public Optional heldRoleArn(String roleName) { + return iamService == null ? Optional.empty() + : iamService.findRole(accountId, roleName).map(IamRole::getArn); + } + + @Override + public Optional serviceCatalogConstraintType(String constraintId) { + return firstFound(lookup -> lookup.serviceCatalogConstraintType(constraintId)); + } + }; + } + + private Iterable services() { + return services == null ? List.of() : services; + } + + /** The first answer a {@link PassedRoleLookup} gives, each answering only for what its service owns. */ + private Optional firstFound(Function> question) { + for (PassedRoleLookup lookup : services()) { + Optional answer = question.apply(lookup); + if (answer.isPresent()) { + return answer; + } + } + return Optional.empty(); + } + + /** The ARNs of the roles the instance profile, named by {@code name} or {@code arn}, holds. */ + private List instanceProfileRoleArns(String accountId, String name, String arn) { + if (iamService == null) { + return List.of(); + } + return IamService.instanceProfileNamed(iamService, accountId, arn != null ? arn : name) + .map(profile -> profile.getRoleNames().stream() + .flatMap(roleName -> iamService.findRole(accountId, roleName).stream()) + .map(IamRole::getArn) + .toList()) + .orElse(List.of()); + } +} 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 69aeb9b759..d209ba3441 100644 --- a/src/main/java/io/floci/aws/core/common/PassedRoles.java +++ b/src/main/java/io/floci/aws/core/common/PassedRoles.java @@ -284,16 +284,12 @@ final class PassedRoles { fromInstanceProfile(ctx, lookups, "LaunchTemplateData.IamInstanceProfile"); case "ec2:CreateFlowLogs" -> fromForm(ctx, VPC_FLOW_LOGS, "DeliverLogsPermissionArn"); case "iam:AddRoleToInstanceProfile" -> instanceProfileRole(ctx, lookups); - case "ecs:RegisterTaskDefinition" -> ecsTaskDefinition(jsonBody(ctx), lookups); - case "ecs:RunTask", "ecs:StartTask" -> ecsTask(jsonBody(ctx), lookups); - case "ecs:CreateService", "ecs:UpdateService" -> ecsService(jsonBody(ctx), lookups); - case "ecs:CreateTaskSet" -> ecsTaskDefinitionRoles(jsonBody(ctx), lookups); - case "ecs:CreateCapacityProvider", "ecs:UpdateCapacityProvider" -> - ecsRoles(values(jsonBody(ctx), "managedInstancesProvider", "infrastructureRoleArn"), ECS, lookups); + case "ecs:RegisterTaskDefinition", "ecs:RunTask", "ecs:StartTask", "ecs:CreateService", "ecs:UpdateService", + "ecs:CreateTaskSet", "ecs:CreateCapacityProvider", "ecs:UpdateCapacityProvider", + "scheduler:CreateSchedule", "scheduler:UpdateSchedule" -> byHandOfBody(action, jsonBody(ctx), lookups); case "states:CreateStateMachine", "states:UpdateStateMachine" -> fromJson(ctx, STATES, "roleArn"); case "events:PutRule" -> fromJson(ctx, EVENTS, "RoleArn"); case "events:PutTargets" -> fromJson(ctx, EVENTS, "Targets", "[]", "RoleArn"); - case "scheduler:CreateSchedule", "scheduler:UpdateSchedule" -> fromJson(ctx, SCHEDULER, "Target", "RoleArn"); case "pipes:CreatePipe", "pipes:UpdatePipe" -> fromJson(ctx, PIPES, "RoleArn"); case "eks:CreatePodIdentityAssociation", "eks:UpdatePodIdentityAssociation" -> fromJson(ctx, EKS_PODS, "roleArn"); @@ -304,8 +300,11 @@ final class PassedRoles { case "cloudformation:CreateStack", "cloudformation:UpdateStack", "cloudformation:DeleteStack", "cloudformation:CreateChangeSet", "cloudformation:ContinueUpdateRollback" -> fromForm(ctx, CLOUDFORMATION, "RoleARN"); - case "cloudformation:CreateStackSet", "cloudformation:UpdateStackSet" -> - stackSetAdministrationRole(ctx, lookups, "cloudformation:UpdateStackSet".equals(action)); + case "cloudformation:CreateStackSet", "cloudformation:UpdateStackSet" -> { + Map form = IamConditionContextResolver.formParameters(ctx); + yield stackSetAdministrationRole(form.get("AdministrationRoleARN"), form.get("PermissionModel"), + form.get("StackSetName"), lookups, "cloudformation:UpdateStackSet".equals(action)); + } case "autoscaling:CreateLaunchConfiguration" -> launchConfiguration(ctx, lookups); case "autoscaling:CreateAutoScalingGroup", "autoscaling:UpdateAutoScalingGroup" -> autoScalingGroup(ctx, lookups); @@ -344,6 +343,32 @@ final class PassedRoles { }; } + /** + * The roles a JSON request for an operation read here passes, for one that is not an HTTP request of its own (a + * state machine's task to its integrated service), read from the members a direct request's are read from: the + * same body for an ECS or a Scheduler request, and for a CloudFormation request the members its form parameters + * carry. Null for any other operation. + */ + private static List byHandOfBody(String operation, JsonNode body, Lookups lookups) { + return switch (operation) { + case "ecs:RegisterTaskDefinition" -> ecsTaskDefinition(body, lookups); + case "ecs:RunTask", "ecs:StartTask" -> ecsTask(body, lookups); + case "ecs:CreateService", "ecs:UpdateService" -> ecsService(body, lookups); + case "ecs:CreateTaskSet" -> ecsTaskDefinitionRoles(body, lookups); + case "ecs:CreateCapacityProvider", "ecs:UpdateCapacityProvider" -> + ecsRoles(values(body, "managedInstancesProvider", "infrastructureRoleArn"), ECS, lookups); + case "scheduler:CreateSchedule", "scheduler:UpdateSchedule" -> + passed(values(body, "Target", "RoleArn"), SCHEDULER); + case "cloudformation:CreateStack", "cloudformation:UpdateStack", "cloudformation:DeleteStack", + "cloudformation:CreateChangeSet", "cloudformation:ContinueUpdateRollback" -> + passed(values(body, "RoleARN"), CLOUDFORMATION); + case "cloudformation:CreateStackSet", "cloudformation:UpdateStackSet" -> + stackSetAdministrationRole(text(body, "AdministrationRoleARN"), text(body, "PermissionModel"), + text(body, "StackSetName"), lookups, "cloudformation:UpdateStackSet".equals(operation)); + default -> null; + }; + } + /** * The roles a request names in the members the table gives for its operation: from its form parameters * when it comes in the Query protocol, from its JSON or CBOR body, and from its XML body when it comes in the @@ -409,21 +434,24 @@ final class PassedRoles { /** * The roles a JSON request for {@code operation} 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 the 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, or that names an instance profile, whose roles only IAM's own - * lookup finds, is not read so, and fails. + * state machine's task to its integrated service), read as a direct request's are: by hand for the operations + * {@link #byHandOfBody} reads, and otherwise from the members the table gives the operation, a role given by name + * being the one IAM holds under it, or else the one the name gives in the account, and an instance profile + * passing the roles it holds. Any other operation whose roles are read by hand here, from a request of its own, + * is not read so, and fails. */ - static List ofBody(String operation, JsonNode body, UnaryOperator named) { + static List ofBody(String operation, JsonNode body, Lookups lookups) { + List byHand = byHandOfBody(operation, body, lookups); + if (byHand != null) { + return byHand; + } if (PassedRoleMembers.table().byHand().contains(operation)) { throw new IllegalArgumentException(operation + " passes roles read by hand, from a request of its own"); } List members = PassedRoleMembers.of(operation); - if (members != null && members.stream().anyMatch(PassedRoleMembers.Member::instanceProfile)) { - throw new IllegalArgumentException(operation + " passes an instance profile's roles, which only a lookup " - + "finds"); - } - return members == null ? List.of() : fromTable(members, Map.of(), body, named, null); + return members == null ? List.of() : fromTable(members, Map.of(), body, + name -> lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name)), + profile -> instanceProfileRoles(lookups, profile)); } private static List fromTable(List members, Map form, @@ -700,16 +728,15 @@ final class PassedRoles { * own permission model, which Floci keeps whatever the request names, and one of a StackSet that * does not exist passes nothing. */ - private static List stackSetAdministrationRole(ContainerRequestContext ctx, Lookups lookups, - boolean update) { - Map form = IamConditionContextResolver.formParameters(ctx); - String named = blankToNull(form.get("AdministrationRoleARN")); + private static List stackSetAdministrationRole(String administrationRole, String permissionModel, + String stackSetName, Lookups lookups, boolean update) { + String named = blankToNull(administrationRole); if (named != null) { return passed(List.of(named), CLOUDFORMATION); } - String model = blankToNull(form.get("PermissionModel")); + String model = blankToNull(permissionModel); if (update) { - String name = blankToNull(form.get("StackSetName")); + String name = blankToNull(stackSetName); Optional stored = name == null ? Optional.empty() : lookups.stackSetPermissionModel(name); if (stored.isEmpty()) { return List.of(); @@ -1020,6 +1047,12 @@ final class PassedRoles { || "x-amz-cbor-1.1".equalsIgnoreCase(mediaType.getSubtype())); } + /** The string {@code member} of {@code body}; null when it is none. */ + private static String text(JsonNode body, String member) { + List found = values(body, member); + return found.isEmpty() ? null : found.getFirst(); + } + private static String blankToNull(String value) { return value == null || value.isBlank() ? null : value; } diff --git a/src/main/java/io/floci/aws/core/common/RequestChecks.java b/src/main/java/io/floci/aws/core/common/RequestChecks.java index a0f595d37d..dbed17b19f 100644 --- a/src/main/java/io/floci/aws/core/common/RequestChecks.java +++ b/src/main/java/io/floci/aws/core/common/RequestChecks.java @@ -34,6 +34,15 @@ public final class RequestChecks { */ public static List of(String operation, JsonNode body, String partition, String region, String accountId, StoredResourceArns stored) { + return of(operation, body, partition, region, accountId, stored, null); + } + + /** + * {@link #of(String, JsonNode, String, String, String, StoredResourceArns)}, {@code roles} finding the roles the + * request passes as a direct request's are found; without it a role given by name is the account's of that name. + */ + public static List of(String operation, JsonNode body, String partition, String region, String accountId, + StoredResourceArns stored, PassedRoleLookups roles) { if (!RequestResources.reads(operation)) { return List.of(); } @@ -51,11 +60,7 @@ public final class RequestChecks { for (String resource : resources) { contexts.forEach(context -> checks.add(new Check(action, resource, Map.copyOf(context)))); } - for (PassedRoles.PassedRole passed : PassedRoles.ofBody(operation, 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())))); - } + checks.addAll(passedRoles(operation, body, partition, region, accountId, roles)); 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, @@ -70,4 +75,23 @@ public final class RequestChecks { } return List.copyOf(checks); } + + /** + * {@code iam:PassRole} on each role a JSON request for {@code operation} passes (the table is keyed by operation, + * as the Service Reference lists it, not by the action it is authorized as), with {@code iam:PassedToService} where AWS names the service ({@link PassedRoles}), the + * roles found by {@code roles} in the partition, Region and account given; without it a role given by name is the + * account's of that name and a resource holding roles holds none. An operation passing roles read by hand from a + * request of its own, and not from a body, fails. + */ + public static List passedRoles(String operation, JsonNode body, String partition, String region, + String accountId, PassedRoleLookups roles) { + PassedRoleLookups lookups = roles != null ? roles : new PassedRoleLookups(null, List.of()); + List checks = new ArrayList<>(); + for (PassedRoles.PassedRole passed : PassedRoles.ofBody(operation, body, + lookups.in(partition, accountId, region))) { + checks.add(new Check("iam:PassRole", passed.roleArn(), passed.passedToService() == null ? Map.of() + : Map.of("iam:PassedToService", List.of(passed.passedToService())))); + } + return checks; + } } diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeys.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeys.java index 2d7b31446e..888d602143 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeys.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeys.java @@ -1,6 +1,8 @@ package io.floci.aws.services.dynamodb; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.floci.aws.core.common.AwsException; import io.floci.aws.services.dynamodb.model.GlobalSecondaryIndex; import io.floci.aws.services.dynamodb.model.KeySchemaElement; import io.floci.aws.services.dynamodb.model.LocalSecondaryIndex; @@ -8,10 +10,13 @@ import io.floci.aws.services.dynamodb.model.TableDefinition; import java.util.ArrayList; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.Set; +import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -294,7 +299,127 @@ public final class DynamoDbConditionKeys { * (duplicates preserved), {@code attributes} holds attribute names in first-seen order * with duplicates removed, {@code select} includes Query/Scan defaults, and is otherwise the raw value or {@code null}. */ - public record Result(List leadingKeys, List attributes, String select) {} + public record Result(List leadingKeys, List attributes, String select) { + + /** The condition keys resolved: {@code dynamodb:LeadingKeys}, {@code dynamodb:Attributes} and {@code dynamodb:Select}. */ + public Map> conditionKeys() { + Map> conditions = new LinkedHashMap<>(); + if (!leadingKeys.isEmpty()) { + conditions.put("dynamodb:LeadingKeys", leadingKeys); + } + if (!attributes.isEmpty()) { + conditions.put("dynamodb:Attributes", attributes); + } + if (select != null) { + conditions.put("dynamodb:Select", List.of(select)); + } + return conditions; + } + } + + /** + * One condition context for each mode a single-item write asks for ({@link #returnValues}): {@code context} with + * that mode's {@code dynamodb:ReturnValues}, so every output the request can return is authorized; {@code context} + * alone for any other request. + */ + public static List>> perReturnMode(String action, JsonNode body, + Map> context) { + List modes = returnValues(action, body); + if (modes.isEmpty()) { + return List.of(Map.copyOf(context)); + } + List>> contexts = new ArrayList<>(); + for (String mode : modes) { + Map> withMode = new LinkedHashMap<>(context); + withMode.put("dynamodb:ReturnValues", List.of(mode)); + contexts.add(Map.copyOf(withMode)); + } + return List.copyOf(contexts); + } + + /** + * The request of each table a batch's {@code RequestItems} names, by its reference as written: the request with + * that table's entry alone, so each table's keys are read from its own entry. Empty for a request with no + * {@code RequestItems} object. + */ + public static Map batchTableRequests(JsonNode body) { + Map requests = new LinkedHashMap<>(); + if (body == null || !body.isObject() || !body.path("RequestItems").isObject()) { + return requests; + } + body.path("RequestItems").properties().forEach(entry -> requests.put(entry.getKey(), + batchTableRequest(body, entry.getKey()))); + return requests; + } + + /** + * The request of the table a batch's {@code RequestItems} names as {@code reference}: a shallow copy of the batch, + * sharing its other members, with that table's entry alone. The batch itself is left as it was. + */ + public static ObjectNode batchTableRequest(JsonNode body, String reference) { + ObjectNode single = ((ObjectNode) body).objectNode(); + single.setAll((ObjectNode) body); + single.putObject("RequestItems").set(reference, body.path("RequestItems").get(reference)); + return single; + } + + /** + * The {@code dynamodb:ReturnValues} of a single-item write: each mode its {@code ReturnValues} and + * {@code ReturnValuesOnConditionCheckFailure} ask for, or {@code NONE}; empty for any other request. + */ + public static List returnValues(String action, JsonNode body) { + if (!("dynamodb:PutItem".equals(action) || "dynamodb:UpdateItem".equals(action) + || "dynamodb:DeleteItem".equals(action)) || body == null || !body.isObject()) { + return List.of(); + } + Set modes = new LinkedHashSet<>(); + for (String field : List.of("ReturnValues", "ReturnValuesOnConditionCheckFailure")) { + String mode = body.path(field).asText("NONE"); + if (!"NONE".equals(mode)) { + modes.add(mode); + } + } + return modes.isEmpty() ? List.of("NONE") : List.copyOf(modes); + } + + /** + * The condition keys of one part of a request {@code enclosing} names, which AWS authorizes as {@code action}: a + * PartiQL statement's, with {@code dynamodb:EnclosingOperation} for a transaction's, or a transaction item's with + * {@code dynamodb:EnclosingOperation} and a write's {@code dynamodb:ReturnValues} on a failed condition. + * + * @param tables the table of a name, for its partition key; null when it has none + * @param region the Region of the request, which a table's ARN must name + */ + public static Map> partConditionKeys(String action, String enclosing, JsonNode part, + Function tables, + String region) { + Map> context = new LinkedHashMap<>(); + if (part.has("Statement")) { + String statement = partiQLStatement(part); + if ("ExecuteTransaction".equals(enclosing)) { + context.put("dynamodb:EnclosingOperation", List.of(enclosing)); + } + context.putAll(extract(action, part, tables.apply(DynamoDbPartiQLParser.extractTable(statement))) + .conditionKeys()); + return context; + } + boolean read = "TransactGetItems".equals(enclosing); + String tableName = part.hasNonNull("TableName") ? part.get("TableName").asText().trim() : ""; + TableDefinition table; + try { + table = tableName.isEmpty() ? null + : tables.apply(DynamoDbTableNames.resolveWithRegion(tableName, region).name()); + } catch (AwsException e) { + // DynamoDB refuses the item itself; without a table its leading key is left out. + table = null; + } + context.put("dynamodb:EnclosingOperation", List.of(enclosing)); + context.putAll((read ? extractTransactionGet(part, table) : extract(action, part, table)).conditionKeys()); + if (!read && part.hasNonNull("ReturnValuesOnConditionCheckFailure")) { + context.put("dynamodb:ReturnValues", List.of(part.path("ReturnValuesOnConditionCheckFailure").asText())); + } + return context; + } // -- Helpers ----------------------------------------------------------------- diff --git a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java index 772b1535ce..141f2eb11e 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java @@ -22,6 +22,7 @@ import io.floci.aws.core.common.AwsPartitions; import io.floci.aws.core.common.CsvParser; import io.floci.aws.core.common.CustomResourceLiveness; import io.floci.aws.core.common.EpochSeconds; +import io.floci.aws.core.common.PassedRoleLookups; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestContext; import io.floci.aws.core.common.RequestScopes; @@ -30,8 +31,8 @@ import io.floci.aws.core.common.XmlParser; import io.floci.aws.services.cloudformation.CloudFormationQueryHandler; import io.floci.aws.services.dynamodb.DynamoDbFacade; import io.floci.aws.services.dynamodb.DynamoDbJsonHandler; -import io.floci.aws.services.dynamodb.backend.DynamoDbItemAccess; import io.floci.aws.services.dynamodb.backend.DynamoDbOperations.Scope; +import io.floci.aws.services.dynamodb.model.TableDefinition; import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ecs.EcsJsonHandler; import io.floci.aws.services.ecs.EcsService; @@ -134,6 +135,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.function.BiConsumer; import java.util.function.Consumer; +import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.LongSupplier; import java.util.function.Supplier; @@ -288,6 +290,7 @@ public class AslExecutor { private final SdkManagementTaskInvoker sdkManagementTaskInvoker; private final EmulatorConfig config; private final RegionResolver regionResolver; + private final PassedRoleLookups passedRoleLookups; private final NestedTaskCredentials nestedTaskCredentials; private final CustomResourceLiveness customResourceLiveness; private final Clock clock; @@ -323,7 +326,7 @@ public class AslExecutor { LambdaTaskAuthorizer lambdaTaskAuthorizer, ApiGatewayTaskInvoker apiGatewayTaskInvoker, EmrTaskInvoker emrTaskInvoker, EmrServerlessTaskInvoker emrServerlessTaskInvoker, SdkManagementTaskInvoker sdkManagementTaskInvoker, EventBridgeInvoker eventBridgeInvoker, - RegionResolver regionResolver) { + RegionResolver regionResolver, PassedRoleLookups passedRoleLookups) { this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler, sqsJsonHandler, snsJsonHandler, cloudFormationHandler, ec2Service, s3Service, ecsService, ecsJsonHandler, @@ -331,7 +334,8 @@ public class AslExecutor { objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness, Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry, nestedTaskCredentials, lambdaTaskAuthorizer, null, null, apiGatewayTaskInvoker, emrTaskInvoker, - emrServerlessTaskInvoker, sdkManagementTaskInvoker, null, eventBridgeInvoker, regionResolver); + emrServerlessTaskInvoker, sdkManagementTaskInvoker, null, eventBridgeInvoker, regionResolver, + passedRoleLookups); } AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver, @@ -351,8 +355,10 @@ public class AslExecutor { Duration expressMaxExecutionTimeOverride, LongSupplier nanoTimeOverride, ApiGatewayTaskInvoker apiGatewayTaskInvoker, EmrTaskInvoker emrTaskInvoker, EmrServerlessTaskInvoker emrServerlessTaskInvoker, SdkManagementTaskInvoker sdkManagementTaskInvoker, - NestedWaiter nestedWaiter, EventBridgeInvoker eventBridgeInvoker, RegionResolver regionResolver) { + NestedWaiter nestedWaiter, EventBridgeInvoker eventBridgeInvoker, RegionResolver regionResolver, + PassedRoleLookups passedRoleLookups) { this.apiGatewayTaskInvoker = apiGatewayTaskInvoker; + this.passedRoleLookups = passedRoleLookups; this.emrTaskInvoker = emrTaskInvoker; this.emrServerlessTaskInvoker = emrServerlessTaskInvoker; this.sdkManagementTaskInvoker = sdkManagementTaskInvoker; @@ -426,7 +432,7 @@ public class AslExecutor { eventBridgeHandler, schedulerService, schedulerController, rdsDataService, objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness, Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null, null, null, null, null, null, - null, null, null, null, null); + null, null, null, null, null, null); } // Kept for tests that do not exercise the Redshift Data API integration. @@ -448,7 +454,7 @@ public class AslExecutor { eventBridgeHandler, schedulerService, schedulerController, rdsDataService, objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSecondsOverride, null, null, null, null, null, null, null, null, null, null, - null, null, null); + null, null, null, null); } AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore, @@ -1281,7 +1287,8 @@ public class AslExecutor { cloudFormationHandler == null ? null : cloudFormationHandler.storedResourceArns(), sdkManagementTaskInvoker == null ? null : sdkManagementTaskInvoker.secretsStoredResourceArns(), sfnService == null || !sfnService.isResolvable() ? null : sfnService.get(), - schedulerService), AwsArnUtils.parse(sm.getStateMachineArn()).accountId()); + schedulerService), new TaskPermissions.RequestLookups(passedRoleLookups, dynamoDbTables(sm)), + AwsArnUtils.parse(sm.getStateMachineArn()).accountId()); if (required.isEmpty()) { return; } @@ -1292,6 +1299,15 @@ public class AslExecutor { required.get().deniedError(), required.get().permissions(), required.get().checksExecutionRole()); } + /** The DynamoDB table of a name in the state machine's Region, as its task's call finds it; null for none. */ + private Function dynamoDbTables(StateMachine sm) { + if (dynamoDb == null) { + return null; + } + Scope scope = dynamoDb.scope(AwsArnUtils.parse(sm.getStateMachineArn()).region()); + return name -> dynamoDb.tables().findTable(scope, name).orElse(null); + } + /** * A Distributed Map's reads and writes are evaluated as its execution role, before the S3 call that needs them. * An execution with a mock test case is evaluated too: a test case cannot mock a Map state, so its S3 calls stay @@ -2719,13 +2735,9 @@ public class AslExecutor { return objectMapper.createObjectNode(); } case "getItem" -> { - JsonNode key = input.path("Key"); - JsonNode item = dynamoDb.items().getItem(scope, tableName, key); - ObjectNode result = objectMapper.createObjectNode(); - if (item != null) { - result.set("Item", item); - } - return result; + // The GetItem request as DynamoDB reads it, so ProjectionExpression and AttributesToGet decide + // which attributes come back, as the dynamodb:Attributes the task was authorized for say. + return dynamoDbRequest("GetItem", input, region, "DynamoDB."); } case "deleteItem" -> { JsonNode key = input.path("Key"); @@ -2739,23 +2751,9 @@ public class AslExecutor { return objectMapper.createObjectNode(); } case "scan" -> { - String filterExpression = input.has("FilterExpression") - ? input.get("FilterExpression").asText() : null; - JsonNode exprAttrNames = input.has("ExpressionAttributeNames") - ? input.get("ExpressionAttributeNames") : null; - JsonNode exprAttrValues = input.has("ExpressionAttributeValues") - ? input.get("ExpressionAttributeValues") : null; - Integer limit = input.has("Limit") ? input.get("Limit").asInt() : null; - JsonNode scanFilter = input.has("ScanFilter") ? input.get("ScanFilter") : null; - DynamoDbItemAccess.ScanPage scanResult = dynamoDb.items().scan( - scope, tableName, filterExpression, exprAttrNames, exprAttrValues, scanFilter, limit, null); - ObjectNode response = objectMapper.createObjectNode(); - ArrayNode items = objectMapper.createArrayNode(); - scanResult.items().forEach(items::add); - response.set("Items", items); - response.put("Count", scanResult.items().size()); - response.put("ScannedCount", scanResult.scannedCount()); - return response; + // As getItem: the Scan request as DynamoDB reads it, so ProjectionExpression, AttributesToGet and + // Select decide what each item returns. + return dynamoDbRequest("Scan", input, region, "DynamoDB."); } case "updateItem" -> { JsonNode key = input.path("Key"); @@ -2789,14 +2787,18 @@ public class AslExecutor { private JsonNode invokeAwsSdkDynamoDb(String camelCaseAction, JsonNode input, String region) { // Convert camelCase to PascalCase (e.g., putItem → PutItem) String pascalAction = Character.toUpperCase(camelCaseAction.charAt(0)) + camelCaseAction.substring(1); + return dynamoDbRequest(pascalAction, input, region, "DynamoDb."); + } + /** One DynamoDB request through its JSON handler, a failure named with {@code errorPrefix}. */ + private JsonNode dynamoDbRequest(String pascalAction, JsonNode input, String region, String errorPrefix) { Response response; try { response = dynamoDbJsonHandler.handle(pascalAction, input, region); } catch (AwsException e) { - throw new FailStateException("DynamoDb." + e.getErrorCode(), e.getMessage()); + throw new FailStateException(errorPrefix + e.getErrorCode(), e.getMessage()); } catch (Exception e) { - throw new FailStateException("DynamoDb.InternalServerError", + throw new FailStateException(errorPrefix + "InternalServerError", e.getMessage() != null ? e.getMessage() : "DynamoDB error"); } @@ -2808,9 +2810,9 @@ public class AslExecutor { String errorName = errorNode.path("__type").asText("UnknownError"); String errorMessage = errorNode.path("message").asText( errorNode.path("Message").asText("DynamoDB operation failed")); - throw new FailStateException("DynamoDb." + errorName, errorMessage); + throw new FailStateException(errorPrefix + errorName, errorMessage); } - throw new FailStateException("DynamoDb.ServiceException", "DynamoDB operation failed"); + throw new FailStateException(errorPrefix + "ServiceException", "DynamoDB operation failed"); } if (entity instanceof JsonNode jsonNode) { 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 03c3c2c34f..a641d1111b 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java @@ -3,12 +3,17 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.PassedRoleLookups; 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.DynamoDbConditionKeys; import io.floci.aws.services.dynamodb.DynamoDbStoredResourceArns; +import io.floci.aws.services.dynamodb.DynamoDbTableNames; +import io.floci.aws.services.dynamodb.model.TableDefinition; import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.iam.IamAuthorizedActions; import io.floci.aws.services.redshiftdata.RedshiftDataTargetSubmitter; @@ -26,6 +31,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.function.Function; /** * What a task's call to its integrated service needs from IAM. A request that names no resource @@ -55,6 +61,7 @@ record TaskPermissions(String deniedError, List permissions, boolean private static final String EMR_SERVERLESS_PREFIX = "EmrServerless."; private static final String LAMBDA_PREFIX = "Lambda."; private static final String SECRETS_MANAGER_PREFIX = "SecretsManager."; + private static final Set DYNAMODB_BATCHES = Set.of("dynamodb:BatchGetItem", "dynamodb:BatchWriteItem"); private static final Set DYNAMODB_OPTIMIZED = Set.of("putItem", "getItem", "deleteItem", "updateItem", "scan"); private static final ObjectMapper MAPPER = new ObjectMapper(); @@ -104,6 +111,24 @@ record TaskPermissions(String deniedError, List permissions, boolean StoredResourceArns states, StoredResourceArns scheduler) { } + /** + * What finds what a task's request names beyond the resources it is checked on, as a direct request's is found, + * reading only. + * + * @param roles the roles IAM holds by name, an instance profile's roles and an ECS task definition's; without it + * a role given by name is the account's of that name and a resource holding roles holds none + * @param tables the DynamoDB table of a name in the state machine's Region, null for none, whose partition key a + * request's {@code dynamodb:LeadingKeys} are read by; without it a request offers none + */ + record RequestLookups(PassedRoleLookups roles, Function tables) { + + static final RequestLookups NONE = new RequestLookups(null, null); + + TableDefinition table(String name) { + return tables == null || name == null ? null : tables.apply(name); + } + } + /** The permissions of a mapped integration, or nothing for one that is not checked. */ static Optional of(StatesIntegration integration, JsonNode input, StateMachine machine) { return of(integration, input, machine, null); @@ -150,25 +175,41 @@ record TaskPermissions(String deniedError, List permissions, boolean static Optional of(StatesIntegration integration, JsonNode input, StateMachine machine, StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback, ControlServices control) { - return of(integration, input, machine, redshiftData, ecs, callback, control, null); + return of(integration, input, machine, redshiftData, ecs, callback, control, RequestLookups.NONE); + } + + /** As the full overload, for a task whose calls run in the state machine's own account. */ + static Optional of(StatesIntegration integration, JsonNode input, StateMachine machine, + StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback, + ControlServices control, RequestLookups lookups) { + return of(integration, input, machine, redshiftData, ecs, callback, control, lookups, null); } /** - * As {@link #of(StatesIntegration, JsonNode, StateMachine, StoredResourceArns, StoredResourceArns, boolean, - * ControlServices)}, for a task whose calls run in the account of {@code machine}, which a {@code Credentials} - * role may have moved from the state machine's own. + * The permissions of a mapped integration, or nothing for one that is not checked, for a task whose calls run in + * the account of {@code machine}, which a {@code Credentials} role may have moved from the state machine's own. * + * @param redshiftData finds the workgroup or the session target a Data API request names; without it a + * workgroup is any workgroup and a session names nothing + * @param ecs finds the task definition revision a reference resolves to and the default cluster, + * reading only; without it a family names any revision and a request naming no cluster any + * cluster + * @param callback whether the state's resource ended in {@code .waitForTaskToken}, which + * {@code integration} no longer shows: EMR and EMR Serverless have no such form, so theirs + * stays unsupported + * @param control finds what a control task's request names + * @param lookups finds what a request names beyond its resources * @param machineAccount the state machine's own account, or null when {@code machine} is in it */ static Optional of(StatesIntegration integration, JsonNode input, StateMachine machine, StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback, - ControlServices control, String machineAccount) { + ControlServices control, RequestLookups lookups, String machineAccount) { if (integration.isSdkService("scheduler") && SCHEDULER.contains(integration.api())) { - return Optional.of(scheduler(integration.api(), input, machine, control.scheduler())); + return Optional.of(scheduler(integration.api(), input, machine, control.scheduler(), lookups)); } if (integration.isSdkService("cloudformation") && servedByCloudFormation(integration.api())) { return Optional.of(cloudFormation(AslExecutor.capitalizeFirst(integration.api()), input, machine, - control.cloudFormation())); + control.cloudFormation(), lookups)); } if (integration.is("http", "invoke")) { return Optional.of(httpInvoke(input, machine)); @@ -191,18 +232,18 @@ record TaskPermissions(String deniedError, List permissions, boolean } if (integration.isAnySuffix("ecs", "runTask") && (integration.suffix().isEmpty() || ".sync".equals(integration.suffix()))) { - return Optional.of(accessDenied(ECS_OPTIMIZED_PREFIX, ecs("RunTask", input, machine, ecs))); + return Optional.of(accessDenied(ECS_OPTIMIZED_PREFIX, ecs("RunTask", input, machine, ecs, lookups))); } if (integration.isSdkService("ecs") && SdkManagementTaskInvoker.supports(integration)) { return Optional.of(accessDenied(ECS_SDK_PREFIX, - ecs(AslExecutor.capitalizeFirst(integration.api()), input, machine, ecs))); + ecs(AslExecutor.capitalizeFirst(integration.api()), input, machine, ecs, lookups))); } if (!callback && integration.isOptimizedService("elasticmapreduce") && EmrTaskInvoker.serves(integration)) { - return Optional.of(emr(integration.api(), input, machine)); + return Optional.of(emr(integration.api(), input, machine, lookups)); } if (!callback && integration.isOptimizedService("emr-serverless") && EmrServerlessTaskInvoker.serves(integration)) { - return Optional.of(emrServerless(integration.api(), input, machine)); + return Optional.of(emrServerless(integration.api(), input, machine, lookups)); } if (integration.is("sqs", "sendMessage")) { return Optional.of(sqsSendMessage("SQS.", input, machine)); @@ -220,10 +261,10 @@ record TaskPermissions(String deniedError, List permissions, boolean return Optional.of(eventsPutEvents(input, machine, machineAccount)); } if (integration.isOptimizedService("dynamodb") && DYNAMODB_OPTIMIZED.contains(integration.api())) { - return Optional.of(dynamoDbOptimized(integration.api(), input, machine)); + return Optional.of(dynamoDbOptimized(integration.api(), input, machine, lookups)); } if (integration.isSdkService("dynamodb")) { - return Optional.of(dynamoDbSdk(AslExecutor.capitalizeFirst(integration.api()), input, machine)); + return Optional.of(dynamoDbSdk(AslExecutor.capitalizeFirst(integration.api()), input, machine, lookups)); } if (integration.is("s3", "putObject") || integration.isSdk("s3", "putObject")) { return Optional.of(s3PutObject(input, machine)); @@ -294,47 +335,93 @@ record TaskPermissions(String deniedError, List permissions, boolean } /** - * The action on the table the request names, as the request-resources table reads it, or nothing for a request - * naming none, which DynamoDB answers. + * The action on the table the request names, as the request-resources table reads it, with the condition keys a + * direct request offers ({@link #dynamoDbConditionKeys}), or nothing for a request naming none, which DynamoDB + * answers. */ - private static TaskPermissions dynamoDbOptimized(String api, JsonNode input, StateMachine machine) { + private static TaskPermissions dynamoDbOptimized(String api, JsonNode input, StateMachine machine, + RequestLookups lookups) { String action = "dynamodb:" + AslExecutor.capitalizeFirst(api); AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); + List>> contexts = dynamoDbConditionKeys(action, input, owner.region(), lookups); return accessDenied(DYNAMODB_OPTIMIZED_PREFIX, RequestResources.ofBody(action, input, owner.partition(), owner.region(), owner.accountId(), null).stream() .filter(AwsArnUtils::isArn) - .map(resource -> new Permission(action, resource)) + .flatMap(resource -> contexts.stream().map(context -> new Permission(action, resource, context))) .toList()); } + /** + * The DynamoDB condition keys a direct request for {@code action} offers: {@code dynamodb:LeadingKeys} by the + * partition key of the table it names, which a table DynamoDB does not have leaves out, {@code dynamodb:Attributes} + * and {@code dynamodb:Select}, and a single-item write's {@code dynamodb:ReturnValues}. A write asking for two + * return modes gets one context for each, as {@code IamConditionContextResolver.resolveRemainingTargets} gives the + * direct request, so every output it can return is authorized. + */ + private static List>> dynamoDbConditionKeys(String action, JsonNode request, + String region, RequestLookups lookups) { + return DynamoDbConditionKeys.perReturnMode(action, request, DynamoDbConditionKeys.extract(action, request, + dynamoDbTable(request.path("TableName"), region, lookups)).conditionKeys()); + } + + /** The table a name or an ARN in {@code region} names; null when it names none DynamoDB has. */ + private static TableDefinition dynamoDbTable(JsonNode reference, String region, RequestLookups lookups) { + String name = text(reference); + if (name == null) { + return null; + } + try { + return lookups.table(DynamoDbTableNames.resolveWithRegion(name.trim(), region).name()); + } catch (AwsException expected) { + LOG.debugv("The DynamoDB table {0} names no table: {1}", name, expected.getMessage()); + return null; + } + } + /** * The check a direct request of the operation gets, as the request-resources table reads it: one whose request's * parts each take an action (a transaction's items, each PartiQL statement) by each part's action on what it names, * a transaction's with {@code dynamodb:EnclosingOperation}, and anything else by its action on the resources it * names, every table of a batch. A request whose parts name nothing, or a value that is not an ARN where the - * request names a resource by one, reaches nothing, so DynamoDB answers it. + * request names a resource by one, reaches nothing, so DynamoDB answers it. Each check offers the condition keys + * the same direct request's does: a part's its own, a batch's each table's its entry gives, and any other + * request's its whole body gives ({@link #dynamoDbConditionKeys}). */ - private static TaskPermissions dynamoDbSdk(String operation, JsonNode input, StateMachine machine) { + private static TaskPermissions dynamoDbSdk(String operation, JsonNode input, StateMachine machine, + RequestLookups lookups) { AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); String namedAs = "dynamodb:" + operation; if (RequestResources.checkedByParts(namedAs)) { - boolean transaction = operation.startsWith("Transact") || "ExecuteTransaction".equals(operation); List permissions = new ArrayList<>(); for (RequestResources.Target target : RequestResources.targetsOfBody(namedAs, input, owner.partition(), owner.region(), owner.accountId(), DynamoDbStoredResourceArns.STATEMENTS)) { - Map> context = transaction && target.element() != null - ? Map.of("dynamodb:EnclosingOperation", List.of(operation)) : Map.of(); + Map> context = target.element() == null ? Map.of() + : Map.copyOf(DynamoDbConditionKeys.partConditionKeys(target.action(), operation, + target.element(), lookups::table, owner.region())); target.resources().stream() .filter(resource -> ANY_RESOURCE.equals(resource) || AwsArnUtils.isArn(resource)) .forEach(resource -> permissions.add(new Permission(target.action(), resource, context))); } return accessDenied(DYNAMODB_SDK_PREFIX, permissions); } + if (DYNAMODB_BATCHES.contains(namedAs) && input.path("RequestItems").isObject()) { + List permissions = new ArrayList<>(); + DynamoDbConditionKeys.batchTableRequests(input).forEach((reference, single) -> { + Map> context = Map.copyOf(DynamoDbConditionKeys.extract(namedAs, single, + dynamoDbTable(TextNode.valueOf(reference), owner.region(), lookups)).conditionKeys()); + RequestResources.ofBody(namedAs, single, owner.partition(), owner.region(), owner.accountId(), null) + .stream().filter(AwsArnUtils::isArn) + .forEach(resource -> permissions.add(new Permission(namedAs, resource, context))); + }); + return accessDenied(DYNAMODB_SDK_PREFIX, permissions); + } List named = RequestResources.ofBody(namedAs, input, owner.partition(), owner.region(), owner.accountId(), null); + List>> contexts = input.isObject() + ? dynamoDbConditionKeys(namedAs, input, owner.region(), lookups) : List.of(Map.of()); return accessDenied(DYNAMODB_SDK_PREFIX, (named.isEmpty() ? List.of(ANY_RESOURCE) : named).stream() .filter(resource -> ANY_RESOURCE.equals(resource) || AwsArnUtils.isArn(resource)) - .map(resource -> new Permission(namedAs, resource)) + .flatMap(resource -> contexts.stream().map(context -> new Permission(namedAs, resource, context))) .toList()); } @@ -461,11 +548,33 @@ record TaskPermissions(String deniedError, List permissions, boolean * its request names, its members read in either casing as the integration recases them: {@code RunTask} on the * revision ECS resolves its task definition to, a family alone being its latest, and a service on the cluster the * request names, or the default one. {@code ListServices} acts on no resource type. A request that is no object is - * answered by the service. + * answered by the service. The roles the call passes need {@code iam:PassRole}, as the same call's made directly + * do: a task definition's task role and execution role, and a role override, which the CDK grants for a + * {@code RunTask} task as well. */ private static List ecs(String operation, JsonNode input, StateMachine machine, - StoredResourceArns ecs) { - return requestPermissions("ecs", operation, AslExecutor.recaseKeys(MAPPER, input, false), machine, ecs); + StoredResourceArns ecs, RequestLookups lookups) { + JsonNode request = AslExecutor.recaseKeys(MAPPER, input, false); + return withPassedRoles(requestPermissions("ecs", operation, request, machine, ecs), "ecs", operation, request, + machine, lookups); + } + + /** + * {@code permissions} and, when they are any, {@code iam:PassRole} on each role the request passes, as the same + * request made directly is checked ({@link RequestChecks#passedRoles}). A request needing no permission is left + * to its service, whatever roles it names. + */ + private static List withPassedRoles(List permissions, String namespace, String operation, + JsonNode request, StateMachine machine, RequestLookups lookups) { + if (permissions.isEmpty() || !request.isObject()) { + return permissions; + } + AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); + List checked = new ArrayList<>(permissions); + RequestChecks.passedRoles(namespace + ":" + operation, request, owner.partition(), + owner.region(), owner.accountId(), lookups.roles()) + .forEach(check -> checked.add(new Permission(check.action(), check.resource(), check.context()))); + return checked; } /** @@ -492,10 +601,11 @@ record TaskPermissions(String deniedError, List permissions, boolean /** * The EMR calls the API's {@code start} makes, each checked as the vendored request resources check the same * call made directly: the integration finds the cluster by {@code ClusterId} alone, and hands it to each call - * in the member that call names it by. {@code RunJobFlow} acts on no resource type. A request naming no cluster - * is refused by the integration. + * in the member that call names it by. {@code RunJobFlow} acts on no resource type, and passes the cluster's roles, + * which need {@code iam:PassRole}, as the CDK grants it on the service role, the cluster role and the auto scaling + * role. A request naming no cluster is refused by the integration. */ - private static TaskPermissions emr(String api, JsonNode input, StateMachine machine) { + private static TaskPermissions emr(String api, JsonNode input, StateMachine machine, RequestLookups lookups) { String clusterId = text(input.path("ClusterId")); AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); List permissions = new ArrayList<>(); @@ -514,7 +624,9 @@ record TaskPermissions(String deniedError, List permissions, boolean permissions.add(new Permission(action, resource)); } } - return accessDenied(EMR_PREFIX, permissions); + return accessDenied(EMR_PREFIX, "createCluster".equals(api) + ? withPassedRoles(permissions, "elasticmapreduce", "RunJobFlow", input, machine, lookups) + : permissions); } /** @@ -545,7 +657,8 @@ record TaskPermissions(String deniedError, List permissions, boolean * 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) { + private static TaskPermissions emrServerless(String api, JsonNode input, StateMachine machine, + RequestLookups lookups) { ObjectNode request = EmrServerlessTaskInvoker.apiRequest(api, input); if (!"createApplication".equals(api) && !request.has("applicationId") || "cancelJobRun".equals(api) && !request.has("jobRunId")) { @@ -553,27 +666,28 @@ record TaskPermissions(String deniedError, List permissions, boolean } AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); return accessDenied(EMR_SERVERLESS_PREFIX, RequestChecks.of("emr-serverless:" + AslExecutor.capitalizeFirst(api), - request, owner.partition(), owner.region(), owner.accountId(), null).stream() + request, owner.partition(), owner.region(), owner.accountId(), null, lookups.roles()).stream() .map(check -> new Permission(check.action(), check.resource(), check.context())).toList()); } /** * The action on the schedule the request names, as the request-resources table reads it for a direct Scheduler - * request: its name and group, a group left out being the one {@code stored} gives as Scheduler's default. A request - * naming no schedule is refused by Scheduler. + * request: its name and group, a group left out being the one {@code stored} gives as Scheduler's default, and + * {@code iam:PassRole} on the role its target runs as, which the CDK grants. A request naming no schedule is + * refused by Scheduler. */ private static TaskPermissions scheduler(String api, JsonNode input, StateMachine machine, - StoredResourceArns stored) { + StoredResourceArns stored, RequestLookups lookups) { if (text(input.path("Name")) == null) { return accessDenied(SCHEDULER_PREFIX, List.of()); } String operation = AslExecutor.capitalizeFirst(api); String action = IamAuthorizedActions.actionFor("scheduler", operation); AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); - return accessDenied(SCHEDULER_PREFIX, RequestResources.ofBody("scheduler:" + operation, input, + return accessDenied(SCHEDULER_PREFIX, withPassedRoles(RequestResources.ofBody("scheduler:" + operation, input, owner.partition(), owner.region(), owner.accountId(), stored).stream() .map(resource -> new Permission(action, resource)) - .toList()); + .toList(), "scheduler", operation, input, machine, lookups)); } /** @@ -587,14 +701,15 @@ record TaskPermissions(String deniedError, List permissions, boolean /** * The check the vendored request resources give the same call made directly ({@link #requestPermissions}), * {@code stored} finding the stack or the stack set a name names; on any resource when the request names none, - * whatever its input is, as a direct request naming none is checked. + * whatever its input is, as a direct request naming none is checked. The service role a stack operation names and + * a StackSet's administration role need {@code iam:PassRole}, as they do made directly. */ private static TaskPermissions cloudFormation(String operation, JsonNode input, StateMachine machine, - StoredResourceArns stored) { + StoredResourceArns stored, RequestLookups lookups) { List permissions = requestPermissions("cloudformation", operation, input, machine, stored); - return accessDenied(CLOUDFORMATION_PREFIX, permissions.isEmpty() + return accessDenied(CLOUDFORMATION_PREFIX, withPassedRoles(permissions.isEmpty() ? List.of(new Permission(IamAuthorizedActions.actionFor("cloudformation", operation), ANY_RESOURCE)) - : permissions); + : permissions, "cloudformation", operation, input, machine, lookups)); } /** diff --git a/src/test/java/io/floci/aws/core/common/PassedRolesTest.java b/src/test/java/io/floci/aws/core/common/PassedRolesTest.java index 11a1d5667b..19fda9b55c 100644 --- a/src/test/java/io/floci/aws/core/common/PassedRolesTest.java +++ b/src/test/java/io/floci/aws/core/common/PassedRolesTest.java @@ -706,7 +706,7 @@ class PassedRolesTest { } @Test - void anEmrClusterPassesItsInstanceProfilesRolesToEc2AndItsRolesByNameToTheirServices() { + void anEmrClusterPassesItsInstanceProfilesRolesToEc2AndItsRolesByNameToTheirServices() throws Exception { // JobFlowRole names an instance profile, whose roles go to EC2; the service role, given by its name, to EMR, and // the automatic scaling role to Application Auto Scaling. The steps' runtime role is not passed. String request = """ @@ -724,9 +724,9 @@ class PassedRolesTest { assertEquals(List.of(passed("numbered-instance", EC2), passed("123456", "elasticmapreduce.amazonaws.com")), PassedRoles.of("elasticmapreduce:RunJobFlow", json("{\"JobFlowRole\":123456,\"ServiceRole\":123456}"), LOOKUPS)); - // A call that is no request of its own has no instance profile lookup, so it is refused. - assertThrows(IllegalArgumentException.class, () -> PassedRoles.ofBody("elasticmapreduce:RunJobFlow", - new ObjectMapper().createObjectNode(), name -> ROLES + name)); + // A call that is no request of its own, a state machine's task, passes the same roles. + assertEquals(PassedRoles.of("elasticmapreduce:RunJobFlow", json(request), LOOKUPS), + PassedRoles.ofBody("elasticmapreduce:RunJobFlow", new ObjectMapper().readTree(request), LOOKUPS)); } @Test diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeysTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeysTest.java index 45899e70cf..0f13c7494f 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeysTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeysTest.java @@ -16,6 +16,7 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; class DynamoDbConditionKeysTest { @@ -489,4 +490,24 @@ class DynamoDbConditionKeysTest { assertNull(DynamoDbConditionKeys.partiQLStatement(json("{\"Statement\":1}"))); assertNull(DynamoDbConditionKeys.partiQLStatement(json("\"not-an-object\""))); } + + /** + * Each table's request is the batch with that table's entry alone, sharing the batch's other members rather than + * copying the whole body for every table, and leaving the batch as it was. + */ + @Test + void aBatchTablesRequestSharesTheBatchsOtherMembers() throws Exception { + JsonNode batch = new ObjectMapper().readTree(""" + {"RequestItems":{"orders":{"Keys":[{"pk":{"S":"o-1"}}]},"other":{"Keys":[{"id":{"S":"x"}}]}}, + "ReturnConsumedCapacity":"TOTAL","Extra":{"nested":true}}"""); + + JsonNode orders = DynamoDbConditionKeys.batchTableRequest(batch, "orders"); + + assertEquals(1, orders.path("RequestItems").size()); + assertTrue(orders.path("RequestItems").has("orders")); + assertSame(batch.get("Extra"), orders.get("Extra")); + assertSame(batch.path("RequestItems").get("orders"), orders.path("RequestItems").get("orders")); + assertEquals(2, batch.path("RequestItems").size()); + } + } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorFixture.java b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorFixture.java index 8510a49a5a..521d1881dc 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorFixture.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/AslExecutorFixture.java @@ -309,7 +309,7 @@ final class AslExecutorFixture { redshiftDataHandler, serviceRegistry, mock(NestedTaskCredentials.class), lambdaTaskAuthorizer, expressMaxExecutionTime, nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker, null, nestedWaiter, - eventBridgeInvoker, null); + eventBridgeInvoker, null, null); } } } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java index 09c94ea0cd..01b66bdcd1 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsControlTaskIamIntegrationTest.java @@ -61,12 +61,17 @@ class StepFunctionsControlTaskIamIntegrationTest { private static final String REGION = "us-east-1"; private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String READ_ONLY = allow("*", "sns:ListTopics"); + private static final String CLOUDFORMATION_TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"cloudformation.amazonaws.com"}}]} + """; private static final String ASSUME = allow("*", "sts:AssumeRole"); private static final String ANY_RESOURCE = "*"; private static final String TEMPLATE = "{\"Resources\":{\"Handle\":{\"Type\":\"AWS::CloudFormation::WaitConditionHandle\"}}}"; private static final String CHILD_DEFINITION = "{\"StartAt\":\"Done\",\"States\":{\"Done\":{\"Type\":\"Pass\",\"End\":true}}}"; private static final Check NOTHING_TO_READ = () -> { }; + private static final String SCHEDULE_ROLE = "arn:aws:iam::" + ACCOUNT + ":role/scheduler"; private static final AtomicInteger HTTP_CALLS = new AtomicInteger(); private static HttpServer httpServer; @@ -271,6 +276,42 @@ class StepFunctionsControlTaskIamIntegrationTest { .path("taskFailedEventDetails").path("error").asText()); } + /** + * A schedule passes the role its target runs as, and a stack operation the service role it names, as the same + * request made directly does: a role allowed the action alone is refused, which the CDK's grants avoid. + */ + @ParameterizedTest + @ValueSource(strings = {"aws-sdk:scheduler:createSchedule", "aws-sdk:scheduler:updateSchedule", + "aws-sdk:cloudformation:createStack", "aws-sdk:cloudformation:createStackSet"}) + void aRoleTheRequestPassesNeedsPassRole(String integration) throws Exception { + Target target = passingARole(target(integration)); + + Response refused = terminal(start(machine("sfn-control-" + UUID.randomUUID(), jsonPathTask(target, null), + role(STATES_TRUST, allow(target.resourceArn(), target.action()))), "{}")); + assertFailed(refused, target.error()); + String cause = refused.jsonPath().getString("cause"); + assertTrue(cause.contains("iam:PassRole") && cause.contains(target.passedRole()), cause); + target.notReached().check(); + + Response allowed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), jsonPathTask(target, null), + role(STATES_TRUST, target.grant())), "{}")); + assertAnsweredByTheService(allowed, target); + target.reached().check(); + } + + /** {@code target} naming a service role when it is a stack it creates, which the others already pass. */ + private Target passingARole(Target target) { + if (!"aws-sdk:cloudformation:createStack".equals(target.integration())) { + return target; + } + String serviceRole = role(CLOUDFORMATION_TRUST, READ_ONLY); + Map arguments = new LinkedHashMap<>(target.arguments()); + arguments.put("RoleARN", serviceRole); + return new Target(target.integration(), target.machineName(), arguments, target.action(), + target.resourceArn(), target.error(), target.serviceError(), target.reached(), target.notReached(), + serviceRole); + } + /** Every integration mapped to a permission serves its callback form, and refuses it the same way. */ @ParameterizedTest @CsvSource(delimiter = '|', value = { @@ -647,14 +688,15 @@ class StepFunctionsControlTaskIamIntegrationTest { yield target(integration, machine, scheduleRequest(name, "rate(1 hour)"), "scheduler:CreateSchedule", scheduleArn(name), "Scheduler.AccessDeniedException", null, () -> assertEquals(200, scheduler("GET", name, null).statusCode()), - () -> assertEquals(404, scheduler("GET", name, null).statusCode())); + () -> assertEquals(404, scheduler("GET", name, null).statusCode()), SCHEDULE_ROLE); } case "aws-sdk:scheduler:updateSchedule" -> { String name = existingSchedule(); yield target(integration, machine, scheduleRequest(name, "rate(2 hours)"), "scheduler:UpdateSchedule", scheduleArn(name), "Scheduler.AccessDeniedException", null, () -> assertEquals("rate(2 hours)", scheduler("GET", name, null).jsonPath().getString("ScheduleExpression")), - () -> assertEquals("rate(1 hour)", scheduler("GET", name, null).jsonPath().getString("ScheduleExpression"))); + () -> assertEquals("rate(1 hour)", scheduler("GET", name, null).jsonPath().getString("ScheduleExpression")), + SCHEDULE_ROLE); } case "aws-sdk:scheduler:deleteSchedule" -> { String name = existingSchedule(); @@ -697,7 +739,8 @@ class StepFunctionsControlTaskIamIntegrationTest { yield target(integration, machine, Map.of("StackSetName", name, "TemplateBody", TEMPLATE), "cloudformation:CreateStackSet", ANY_RESOURCE, "CloudFormation.AccessDeniedException", null, () -> assertEquals(200, cloudFormation("DescribeStackSet", Map.of("StackSetName", name)).statusCode()), - () -> assertEquals(404, cloudFormation("DescribeStackSet", Map.of("StackSetName", name)).statusCode())); + () -> assertEquals(404, cloudFormation("DescribeStackSet", Map.of("StackSetName", name)).statusCode()), + "arn:aws:iam::" + ACCOUNT + ":role/AWSCloudFormationStackSetAdministrationRole"); } case "http:invoke" -> target(integration, machine, Map.of("ApiEndpoint", httpEndpoint(), "Method", "GET", "InvocationConfig", Map.of("ConnectionArn", connection())), @@ -770,14 +813,28 @@ class StepFunctionsControlTaskIamIntegrationTest { private static Target target(String integration, String machine, Map arguments, String action, String resourceArn, String error, String serviceError, Check reached, Check notReached) { - return new Target(integration, machine, arguments, action, resourceArn, error, serviceError, reached, notReached); + return target(integration, machine, arguments, action, resourceArn, error, serviceError, reached, notReached, + null); } - private record Target(String integration, String machineName, Map arguments, String action, - String resourceArn, String error, String serviceError, Check reached, Check notReached) { + private static Target target(String integration, String machine, Map arguments, String action, + String resourceArn, String error, String serviceError, Check reached, Check notReached, + String passedRole) { + return new Target(integration, machine, arguments, action, resourceArn, error, serviceError, reached, notReached, + passedRole); + } + /** @param passedRole the role the request passes, which needs {@code iam:PassRole}; null when it passes none */ + private record Target(String integration, String machineName, Map arguments, String action, + String resourceArn, String error, String serviceError, Check reached, Check notReached, + String passedRole) { + + /** The action on the resource, and {@code iam:PassRole} on the role the request passes, if any. */ String grant() { - return allow(resourceArn, action); + Map onResource = Map.of("Effect", "Allow", "Action", List.of(action), + "Resource", List.of(resourceArn)); + return policy(passedRole == null ? List.of(onResource) : List.of(onResource, Map.of("Effect", "Allow", + "Action", List.of("iam:PassRole"), "Resource", List.of(passedRole)))); } /** {@link #reached}, for a task whose execution has not finished: the call happens after the task starts. */ @@ -823,8 +880,7 @@ class StepFunctionsControlTaskIamIntegrationTest { private static Map scheduleRequest(String name, String expression) { return Map.of("Name", name, "ScheduleExpression", expression, "FlexibleTimeWindow", Map.of("Mode", "OFF"), - "Target", Map.of("Arn", "arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":q", - "RoleArn", "arn:aws:iam::" + ACCOUNT + ":role/scheduler")); + "Target", Map.of("Arn", "arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":q", "RoleArn", SCHEDULE_ROLE)); } private static String scheduleArn(String name) { diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java index 4664b94f46..20fad50bac 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java @@ -414,6 +414,34 @@ class StepFunctionsDataTaskIamIntegrationTest { assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); } + /** + * {@code dynamodb:LeadingKeys} reaches the policy, as it does for a direct request: a role allowed {@code GetItem} + * only on its own partition key reads that item and is refused another, in both forms of the task. + */ + @ParameterizedTest + @CsvSource({"dynamodb:getItem,DynamoDB.AccessDeniedException", "aws-sdk:dynamodb:getItem,DynamoDb.AccessDeniedException"}) + void aPolicyOnTheLeadingKeysReachesTheItemsItNames(String integration, String error) throws Exception { + String table = table(); + putItem(table, "mine"); + putItem(table, "theirs"); + String policy = MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", List.of( + Map.of("Effect", "Allow", "Action", "dynamodb:GetItem", "Resource", tableArn(table), "Condition", + Map.of("ForAllValues:StringEquals", Map.of("dynamodb:LeadingKeys", List.of("mine")), + "Null", Map.of("dynamodb:LeadingKeys", "false")))))); + String role = role(STATES_TRUST, policy); + + Response allowed = terminal(start(machine(getItemTask(integration, table, "mine"), role), "{}")); + Response refused = terminal(start(machine(getItemTask(integration, table, "theirs"), role), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertFailed(refused, error); + } + + private static Map getItemTask(String integration, String table, String key) { + return Map.of("Type", "Task", "Resource", "arn:aws:states:::" + integration, + "Parameters", Map.of("TableName", table, "Key", Map.of("pk", Map.of("S", key))), "End", true); + } + @Test void listTablesNeedsItsRegionalCollection() throws Exception { String collection = "arn:aws:dynamodb:" + REGION + ":" + ACCOUNT + ":table/*"; diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDynamoDbIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDynamoDbIntegrationTest.java index 57bc76690e..f68d66fa57 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDynamoDbIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDynamoDbIntegrationTest.java @@ -521,6 +521,51 @@ class StepFunctionsDynamoDbIntegrationTest { assertEquals("hello", result.path("Item").path("value").path("S").asText()); } + /** + * The optimized getItem takes the GetItem request, so its ProjectionExpression decides which attributes come + * back: a policy on dynamodb:Attributes is only as narrow as the item the task returns. + */ + @Test + @Order(73) + void optimizedGetItemReturnsOnlyTheProjectedAttributes() throws Exception { + String output = executeSfnOptimized("opt-get-projected", "dynamodb:getItem", """ + { + "TableName": "%s", + "Key": { + "pk": {"S": "opt-get-test"}, + "sk": {"S": "row"} + }, + "ProjectionExpression": "pk, sk" + } + """.formatted(TABLE_NAME)); + + JsonNode item = mapper.readTree(output).path("Item"); + assertEquals("opt-get-test", item.path("pk").path("S").asText()); + assertFalse(item.has("value"), output); + } + + /** + * The optimized scan takes the Scan request too, so its ProjectionExpression decides which attributes each item + * returns. + */ + @Test + @Order(74) + void optimizedScanReturnsOnlyTheProjectedAttributes() throws Exception { + String output = executeSfnOptimized("opt-scan-projected", "dynamodb:scan", """ + { + "TableName": "%s", + "FilterExpression": "pk = :pk", + "ExpressionAttributeValues": {":pk": {"S": "opt-get-test"}}, + "ProjectionExpression": "pk, sk" + } + """.formatted(TABLE_NAME)); + + JsonNode items = mapper.readTree(output).path("Items"); + assertEquals(1, items.size(), output); + assertEquals("opt-get-test", items.get(0).path("pk").path("S").asText()); + assertFalse(items.get(0).has("value"), output); + } + @Test @Order(72) void optimized_getItem_notFound_returnsEmptyObject() throws Exception { 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 d16aba42be..ce11e90cd7 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsJobTaskIamIntegrationTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.testing.EnforcementFixtures; import io.floci.aws.testing.IamEnforcementProfile; import io.floci.aws.testing.PartitionCleanup; import io.floci.aws.testing.RestAssuredJsonUtils; @@ -58,6 +59,9 @@ class StepFunctionsJobTaskIamIntegrationTest { {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", "Principal":{"Service":"emr-serverless.amazonaws.com"}}]} """; + private static final String ECS_TASKS_TRUST = trust("ecs-tasks.amazonaws.com"); + private static final String EMR_TRUST = trust("elasticmapreduce.amazonaws.com"); + private static final String EC2_TRUST = trust("ec2.amazonaws.com"); private static final String READ_ONLY = allow("*", "sns:ListTopics"); private static final String ASSUME = allow("*", "sts:AssumeRole"); private static final String ALLOW_ALL = @@ -234,6 +238,74 @@ class StepFunctionsJobTaskIamIntegrationTest { target.notReached().check(); } + /** + * A task started from a definition with a task role passes it to ECS, as a direct {@code RunTask} does, so the role + * the task runs as needs {@code iam:PassRole} on it beside {@code ecs:RunTask}, which the CDK grants. + */ + @Test + void aRunTaskNeedsPassRoleOnItsTaskDefinitionsRole() throws Exception { + String taskRole = role(ECS_TASKS_TRUST, READ_ONLY); + String family = "sfn-jobs-" + UUID.randomUUID(); + ecs("RegisterTaskDefinition", Map.of("family", family, "taskRoleArn", taskRole, "containerDefinitions", + List.of(Map.of("name", "runner", "image", "floci-test/runner:latest", "memory", 128)))) + .then().statusCode(200); + cleanup.register(() -> { + ecs("DeregisterTaskDefinition", Map.of("taskDefinition", family + ":1")).then().statusCode(200); + ecs("DeleteTaskDefinitions", Map.of("taskDefinitions", List.of(family + ":1"))).then().statusCode(200); + }); + String cluster = ecsCluster(); + Map task = task("ecs:runTask", Map.of("Cluster", cluster, "TaskDefinition", family)); + Map runTask = Map.of("Effect", "Allow", "Action", List.of("ecs:RunTask"), + "Resource", List.of(taskDefinitionArn(family, 1))); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, policy(List.of(runTask)))), "{}")); + assertFailed(refused, "ECS.AccessDeniedException"); + String cause = refused.jsonPath().getString("cause"); + assertTrue(cause.contains("iam:PassRole") && cause.contains(taskRole), cause); + assertEquals(List.of(), runningTasks(cluster)); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, policy(List.of(runTask, + Map.of("Effect", "Allow", "Action", List.of("iam:PassRole"), "Resource", List.of(taskRole)))))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertEquals(1, runningTasks(cluster).size()); + } + + /** + * A cluster passes its service role to EMR and the role of its instance profile to EC2, so the role the task runs as + * needs {@code iam:PassRole} on both, which the CDK grants, and AWS's managed EMR policy grants for those services. + */ + @Test + void createClusterNeedsPassRoleOnItsServiceRoleAndItsInstanceProfilesRole() throws Exception { + String serviceRole = role(EMR_TRUST, READ_ONLY); + String clusterRole = role(EC2_TRUST, READ_ONLY); + String profile = instanceProfile(clusterRole); + Target untagged = createClusterTarget(); + Map arguments = new LinkedHashMap<>(untagged.arguments()); + arguments.put("ServiceRole", serviceRole.substring(serviceRole.lastIndexOf('/') + 1)); + arguments.put("JobFlowRole", profile); + Target target = new Target(untagged.integration(), untagged.error(), untagged.resourceArn(), arguments, + untagged.reached(), untagged.notReached(), untagged.actions()); + Map runJobFlow = Map.of("Effect", "Allow", "Action", List.of("elasticmapreduce:RunJobFlow"), + "Resource", List.of(ANY_RESOURCE)); + Map passService = Map.of("Effect", "Allow", "Action", List.of("iam:PassRole"), + "Resource", List.of(serviceRole), "Condition", + Map.of("StringEquals", Map.of("iam:PassedToService", "elasticmapreduce.amazonaws.com"))); + + Response refused = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, + policy(List.of(runJobFlow, passService)))), "{}")); + assertFailed(refused, target.error()); + String cause = refused.jsonPath().getString("cause"); + assertTrue(cause.contains("iam:PassRole") && cause.contains(clusterRole), cause); + target.notReached().check(); + + Response created = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, policy(List.of( + runJobFlow, passService, Map.of("Effect", "Allow", "Action", List.of("iam:PassRole"), + "Resource", List.of(clusterRole), "Condition", + Map.of("StringEquals", Map.of("iam:PassedToService", "ec2.amazonaws.com"))))))), "{}")); + assertEquals("SUCCEEDED", created.jsonPath().getString("status"), created.asString()); + target.reached().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. @@ -975,6 +1047,23 @@ class StepFunctionsJobTaskIamIntegrationTest { .getString("jobRun.state"); } + /** An instance profile holding {@code roleArn}, removed again by the cleanup. */ + private String instanceProfile(String roleArn) { + String name = "sfn-jobs-" + UUID.randomUUID(); + String authorization = auth(ACCOUNT, "iam"); + iam(authorization, "CreateInstanceProfile", Map.of("InstanceProfileName", name)); + cleanup.register(() -> EnforcementFixtures.removeInstanceProfile(baseUri.getPort(), authorization, name)); + iam(authorization, "AddRoleToInstanceProfile", Map.of("InstanceProfileName", name, + "RoleName", roleArn.substring(roleArn.lastIndexOf('/') + 1))); + return name; + } + + private void iam(String authorization, String action, Map parameters) { + given().port(baseUri.getPort()).header("Authorization", authorization) + .contentType("application/x-www-form-urlencoded").formParam("Action", action) + .formParam("Version", "2010-05-08").formParams(parameters).post("/").then().statusCode(200); + } + private String jobRole() { return role(EMR_SERVERLESS_TRUST, READ_ONLY); } @@ -1012,6 +1101,11 @@ class StepFunctionsJobTaskIamIntegrationTest { assertEquals(error, completed.jsonPath().getString("error"), completed.asString()); } + private static String trust(String service) { + return "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"sts:AssumeRole\"," + + "\"Principal\":{\"Service\":\"" + service + "\"}}]}"; + } + private String role(String trust, String policy) { return sfn().role(ACCOUNT, "sfn-jobs-", trust, policy); } 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 96529ebb5f..f8635ab434 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java @@ -3,7 +3,14 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.PassedRoleLookups; import io.floci.aws.core.common.StoredResourceArns; +import io.floci.aws.services.dynamodb.model.KeySchemaElement; +import io.floci.aws.services.dynamodb.model.TableDefinition; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.iam.PassedRoleLookup; +import io.floci.aws.services.iam.model.IamRole; +import io.floci.aws.services.iam.model.InstanceProfile; import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission; import io.floci.aws.services.stepfunctions.model.StateMachine; import io.floci.aws.testing.ParallelLocks; @@ -15,9 +22,11 @@ import org.junit.jupiter.params.provider.ValueSource; import java.nio.file.Files; import java.nio.file.Path; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -191,9 +200,11 @@ class TaskPermissionsTest { @ParameterizedTest @CsvSource({"putItem,PutItem", "getItem,GetItem", "deleteItem,DeleteItem", "updateItem,UpdateItem", "scan,Scan"}) void anOptimizedDynamoDbTaskNeedsItsActionOnTheTable(String api, String operation) throws Exception { - assertEquals(TaskPermissions.accessDenied("DynamoDB.", List.of(new Permission("dynamodb:" + operation, table("orders")))), - TaskPermissions.of(integration("dynamodb:" + api), json("{\"TableName\":\"orders\"}"), machine("aws")) - .orElseThrow()); + TaskPermissions permissions = TaskPermissions.of(integration("dynamodb:" + api), + json("{\"TableName\":\"orders\"}"), machine("aws")).orElseThrow(); + assertEquals("DynamoDB.AccessDeniedException", permissions.deniedError()); + assertEquals(List.of(new Permission("dynamodb:" + operation, table("orders"))), + withoutItemKeys(permissions.permissions())); } @ParameterizedTest @@ -215,8 +226,88 @@ class TaskPermissionsTest { List both = List.of(new Permission("dynamodb:PutItem", arn), new Permission("dynamodb:PutItem", table("orders"))); assertEquals(both, sdkPermissions("putItem", "{\"TableName\":\"" + arn + "\"}")); - assertEquals(both, TaskPermissions.of(integration("dynamodb:putItem"), json("{\"TableName\":\"" + arn + "\"}"), - machine("aws")).orElseThrow().permissions()); + assertEquals(both, withoutItemKeys(TaskPermissions.of(integration("dynamodb:putItem"), + json("{\"TableName\":\"" + arn + "\"}"), machine("aws")).orElseThrow().permissions())); + } + + /** + * A task's item request offers the keys a direct one does: the partition key's value, by the table's key schema, + * the attributes it names and what it selects, and a write's return values. + */ + @ParameterizedTest + @ValueSource(strings = {"dynamodb:getItem", "aws-sdk:dynamodb:getItem"}) + void anItemRequestOffersItsLeadingKeysAttributesAndSelect(String tail) throws Exception { + assertEquals(List.of(new Permission("dynamodb:GetItem", table("orders"), Map.of( + "dynamodb:LeadingKeys", List.of("o-1"), "dynamodb:Attributes", List.of("pk", "total"), + "dynamodb:Select", List.of("SPECIFIC_ATTRIBUTES")))), + dynamoDbPermissions(tail, """ + {"TableName":"orders","Key":{"pk":{"S":"o-1"}},"ProjectionExpression":"total"}""")); + } + + @Test + void aWriteOffersItsReturnValues() throws Exception { + assertEquals(List.of("ALL_OLD"), dynamoDbPermissions("dynamodb:putItem", """ + {"TableName":"orders","Item":{"pk":{"S":"o-1"}},"ReturnValues":"ALL_OLD"}""") + .getFirst().conditionKeys().get("dynamodb:ReturnValues")); + } + + /** + * A write asking for two return modes is checked once per mode, as a direct request is, so a policy refusing the + * mode returned on a failed condition refuses the task. + */ + @ParameterizedTest + @ValueSource(strings = {"dynamodb:updateItem", "aws-sdk:dynamodb:updateItem"}) + void aWriteWithTwoReturnModesIsCheckedForEach(String resource) throws Exception { + List permissions = dynamoDbPermissions(resource, """ + {"TableName":"orders","Key":{"pk":{"S":"o-1"}},"UpdateExpression":"SET total = :t", + "ExpressionAttributeValues":{":t":{"N":"1"}},"ReturnValues":"UPDATED_NEW", + "ReturnValuesOnConditionCheckFailure":"ALL_OLD"}"""); + + assertEquals(List.of(List.of("UPDATED_NEW"), List.of("ALL_OLD")), + permissions.stream().map(permission -> permission.conditionKeys().get("dynamodb:ReturnValues")).toList()); + assertEquals(List.of(table("orders"), table("orders")), + permissions.stream().map(Permission::resourceArn).toList()); + } + + /** A table DynamoDB does not have has no partition key to read, so the request offers no leading key. */ + @Test + void aTableDynamoDbDoesNotHaveOffersNoLeadingKeys() throws Exception { + assertFalse(dynamoDbPermissions("dynamodb:getItem", "{\"TableName\":\"other\",\"Key\":{\"pk\":{\"S\":\"o-1\"}}}") + .getFirst().conditionKeys().containsKey("dynamodb:LeadingKeys")); + } + + /** Each table of a batch is checked with the keys its own entry names. */ + @Test + void eachTableOfABatchOffersItsOwnEntrysKeys() throws Exception { + List permissions = dynamoDbPermissions("aws-sdk:dynamodb:batchGetItem", """ + {"RequestItems":{"orders":{"Keys":[{"pk":{"S":"o-1"}}]},"other":{"Keys":[{"id":{"S":"x"}}]}}}"""); + + assertEquals(List.of(table("orders"), table("other")), + permissions.stream().map(Permission::resourceArn).toList()); + assertEquals(List.of("o-1"), permissions.get(0).conditionKeys().get("dynamodb:LeadingKeys")); + assertEquals(List.of("pk"), permissions.get(0).conditionKeys().get("dynamodb:Attributes")); + assertEquals(List.of("id"), permissions.get(1).conditionKeys().get("dynamodb:Attributes")); + } + + /** A transaction's item offers its own keys beside the enclosing operation. */ + @Test + void aTransactionItemOffersItsOwnKeys() throws Exception { + assertEquals(List.of(new Permission("dynamodb:PutItem", table("orders"), Map.of( + "dynamodb:EnclosingOperation", List.of("TransactWriteItems"), + "dynamodb:LeadingKeys", List.of("o-1"), "dynamodb:Attributes", List.of("pk")))), + dynamoDbPermissions("aws-sdk:dynamodb:transactWriteItems", """ + {"TransactItems":[{"Put":{"TableName":"orders","Item":{"pk":{"S":"o-1"}}}}]}""")); + } + + /** DynamoDB's table {@code orders}, keyed by {@code pk}. */ + private static List dynamoDbPermissions(String tail, String request) throws Exception { + TableDefinition orders = new TableDefinition(); + orders.setTableName("orders"); + orders.setKeySchema(List.of(new KeySchemaElement("pk", "HASH"))); + return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, null, false, + new TaskPermissions.ControlServices(null, null, null, null), + new TaskPermissions.RequestLookups(null, name -> "orders".equals(name) ? orders : null)) + .orElseThrow().permissions(); } @Test @@ -650,6 +741,120 @@ class TaskPermissionsTest { .orElseThrow().permissions()); } + private static final String TASK_ROLE = "arn:aws:iam::111122223333:role/task"; + private static final String EXECUTION_ROLE = "arn:aws:iam::111122223333:role/execution"; + private static final Map> TO_ECS_TASKS = + Map.of("iam:PassedToService", List.of("ecs-tasks.amazonaws.com")); + + /** + * RunTask passes its task definition's task role and execution role and a role override, as a direct RunTask + * does, a role given by name being the account's of that name. + */ + @ParameterizedTest + @ValueSource(strings = {"ecs:runTask", "ecs:runTask.sync"}) + void runTaskNeedsPassRoleOnTheTaskDefinitionsRolesAndAnOverride(String tail) throws Exception { + assertEquals(List.of(new Permission("ecs:RunTask", TASK_DEFINITION), + new Permission("iam:PassRole", TASK_ROLE, TO_ECS_TASKS), + new Permission("iam:PassRole", EXECUTION_ROLE, TO_ECS_TASKS), + new Permission("iam:PassRole", "arn:aws:iam::111122223333:role/override", TO_ECS_TASKS)), + TaskPermissions.of(integration(tail), + json("{\"TaskDefinition\":\"orders\",\"Overrides\":{\"TaskRoleArn\":\"override\"}}"), + machine("aws"), null, ecs(), false, new TaskPermissions.ControlServices(null, null, null, null), + roles()).orElseThrow().permissions()); + } + + /** A request ECS answers needs nothing, whatever roles it names. */ + @Test + void aRunTaskNamingNoDefinitionNeedsNoPassRole() throws Exception { + assertEquals(List.of(), TaskPermissions.of(integration("ecs:runTask"), + json("{\"Overrides\":{\"TaskRoleArn\":\"override\"}}"), machine("aws"), null, ecs(), false, + new TaskPermissions.ControlServices(null, null, null, null), roles()).orElseThrow().permissions()); + } + + @ParameterizedTest + @ValueSource(strings = {"createSchedule", "updateSchedule"}) + void aScheduleNeedsPassRoleOnItsTargetsRole(String api) throws Exception { + String role = "arn:aws:iam::111122223333:role/scheduler"; + List permissions = control("aws-sdk:scheduler:" + api, + "{\"Name\":\"n\",\"Target\":{\"Arn\":\"q\",\"RoleArn\":\"" + role + "\"}}").permissions(); + + assertEquals(new Permission("iam:PassRole", role, Map.of("iam:PassedToService", + List.of("scheduler.amazonaws.com"))), permissions.getLast()); + assertEquals(2, permissions.size()); + } + + @ParameterizedTest + @ValueSource(strings = {"createStack", "updateStack", "deleteStack", "createChangeSet", "continueUpdateRollback"}) + void aStackOperationNeedsPassRoleOnTheServiceRoleItNames(String api) throws Exception { + String role = "arn:aws:iam::111122223333:role/deployer"; + assertEquals(List.of(new Permission("iam:PassRole", role, + Map.of("iam:PassedToService", List.of("cloudformation.amazonaws.com")))), + passedRoles(control("aws-sdk:cloudformation:" + api, + "{\"StackName\":\"s\",\"ChangeSetName\":\"c\",\"RoleARN\":\"" + role + "\"}", + stacks(), null, null, false))); + } + + /** A self-managed StackSet naming no administration role passes the default one, as a direct create does. */ + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "{\"StackSetName\":\"n\"}|arn:aws:iam::111122223333:role/AWSCloudFormationStackSetAdministrationRole", + "{\"StackSetName\":\"n\",\"AdministrationRoleARN\":\"arn:aws:iam::111122223333:role/admin\"}" + + "|arn:aws:iam::111122223333:role/admin", + "{\"StackSetName\":\"n\",\"PermissionModel\":\"SERVICE_MANAGED\"}|"}) + void aStackSetPassesItsAdministrationRole(String request, String role) throws Exception { + assertEquals(role == null ? List.of() : List.of(new Permission("iam:PassRole", role, + Map.of("iam:PassedToService", List.of("cloudformation.amazonaws.com")))), + passedRoles(control("aws-sdk:cloudformation:createStackSet", request))); + } + + /** + * A cluster passes its service role, its instance profile's role and its auto scaling role, each to the service + * the vendored EMR role source passes it to, a role given by name being the one IAM holds under it. + */ + @ParameterizedTest + @ValueSource(strings = {"elasticmapreduce:createCluster", "elasticmapreduce:createCluster.sync"}) + void createClusterNeedsPassRoleOnTheClustersRoles(String tail) throws Exception { + assertEquals(List.of(new Permission("elasticmapreduce:RunJobFlow", "*"), + new Permission("iam:PassRole", "arn:aws:iam::111122223333:role/scaling", + Map.of("iam:PassedToService", List.of("application-autoscaling.amazonaws.com"))), + new Permission("iam:PassRole", "arn:aws:iam::111122223333:role/cluster", + Map.of("iam:PassedToService", List.of("ec2.amazonaws.com"))), + new Permission("iam:PassRole", "arn:aws:iam::111122223333:role/emr/service", + Map.of("iam:PassedToService", List.of("elasticmapreduce.amazonaws.com")))), + TaskPermissions.of(integration(tail), json(""" + {"Name":"c","ServiceRole":"service","JobFlowRole":"cluster-profile", + "AutoScalingRole":"arn:aws:iam::111122223333:role/scaling"}"""), machine("aws"), null, + null, false, new TaskPermissions.ControlServices(null, null, null, null), roles()) + .orElseThrow().permissions()); + } + + /** IAM's role {@code service}, under a path, and the profile holding {@code cluster}; ECS's roles of {@code orders}. */ + private static TaskPermissions.RequestLookups roles() { + IamService iam = mock(IamService.class); + IamRole service = new IamRole(); + service.setArn("arn:aws:iam::111122223333:role/emr/service"); + when(iam.findRole(ACCOUNT, "service")).thenReturn(Optional.of(service)); + IamRole cluster = new IamRole(); + cluster.setArn("arn:aws:iam::111122223333:role/cluster"); + when(iam.findRole(ACCOUNT, "cluster")).thenReturn(Optional.of(cluster)); + InstanceProfile profile = new InstanceProfile(); + profile.setRoleNames(List.of("cluster")); + when(iam.findInstanceProfile(ACCOUNT, "cluster-profile")).thenReturn(Optional.of(profile)); + PassedRoleLookup taskDefinitions = new PassedRoleLookup() { + @Override + public List taskDefinitionRoles(String reference, String region) { + return "orders".equals(reference) && "eu-west-1".equals(region) + ? List.of(TASK_ROLE, EXECUTION_ROLE) : List.of(); + } + }; + return new TaskPermissions.RequestLookups(new PassedRoleLookups(iam, List.of(taskDefinitions)), null); + } + + private static List passedRoles(TaskPermissions permissions) { + return permissions.permissions().stream().filter(permission -> "iam:PassRole".equals(permission.action())) + .toList(); + } + private static final String STACK = "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stack/s/id"; private static final String STACK_SET = "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stackset/ss:id"; @@ -762,8 +967,10 @@ class TaskPermissionsTest { @ValueSource(strings = {"validateTemplate", "listStacks", "listExports", "describeOrganizationsAccess", "activateOrganizationsAccess", "createStackSet", "listStackSets"}) void aCloudFormationActionWithNoResourceTypeIsOnAnyResource(String api) throws Exception { - assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), "*")), - control("aws-sdk:cloudformation:" + api, "{}").permissions()); + assertEquals(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), "*"), + control("aws-sdk:cloudformation:" + api, "{}").permissions().getFirst()); + assertEquals(List.of(), passedRoles(control("aws-sdk:cloudformation:" + api, + "{\"PermissionModel\":\"SERVICE_MANAGED\"}"))); } /** A task whose input is no object still needs its action, on any resource, as a direct request naming none. */ @@ -1083,8 +1290,21 @@ class TaskPermissionsTest { }; } + /** The permissions of a DynamoDB SDK task, without the item keys the tests of those keys pin. */ private static List sdkPermissions(String api, String request) throws Exception { - return TaskPermissions.of(integration("aws-sdk:dynamodb:" + api), json(request), machine("aws")).orElseThrow().permissions(); + return withoutItemKeys(TaskPermissions.of(integration("aws-sdk:dynamodb:" + api), json(request), machine("aws")) + .orElseThrow().permissions()); + } + + /** {@code permissions} without the keys a request's items and projection give, which their own tests pin. */ + private static List withoutItemKeys(List permissions) { + Set itemKeys = Set.of("dynamodb:LeadingKeys", "dynamodb:Attributes", "dynamodb:Select", + "dynamodb:ReturnValues"); + return permissions.stream().map(permission -> { + Map> kept = new LinkedHashMap<>(permission.conditionKeys()); + kept.keySet().removeAll(itemKeys); + return new Permission(permission.action(), permission.resourceArn(), kept); + }).toList(); } private static List redshiftPermissions(String api, String request, StoredResourceArns stored) throws Exception {