From 87eaaab92dfa8d688ce8d87a33aa6688211f58c5 Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Sat, 7 Nov 2026 07:16:40 -0600 Subject: [PATCH] feat(stepfunctions): evaluate the execution role on DynamoDB, S3, RDS Data and Redshift Data tasks (#7722) Under IAM enforcement, these tasks are now authorized as the execution role, or as the Credentials role a state names. DynamoDB is checked as a direct request is: batches on each table, transactions by each item's own action, ListTables on its regional collection and statements by what they do. S3 putObject is checked on the object in the bucket's own partition, and a bucket policy can grant or deny. RDS Data needs the action on the cluster and GetSecretValue on the secret. Redshift Data needs what an EventBridge target needs, and its statement operations are checked on any resource. A request naming nothing it can reach is left to its service. With enforcement off nothing changes. Signed-off-by: Hector Ventura --- docs/services/step-functions.md | 81 +- .../aws/core/common/RequestResources.java | 20 + .../aws/services/iam/ResourceArnBuilder.java | 9 +- .../services/iam/ResourcePolicyProviders.java | 13 + .../redshiftdata/RedshiftDataJsonHandler.java | 6 + .../RedshiftDataTargetSubmitter.java | 29 +- .../services/stepfunctions/AslExecutor.java | 3 +- .../stepfunctions/LambdaTaskAuthorizer.java | 11 +- .../stepfunctions/TaskPermissions.java | 184 ++++ .../LambdaTaskAuthorizerTest.java | 19 + ...epFunctionsDataTaskIamIntegrationTest.java | 894 ++++++++++++++++++ ...nctionsTaskCredentialsIntegrationTest.java | 55 ++ .../stepfunctions/TaskPermissionsTest.java | 242 ++++- .../aws/testing/StepFunctionsTestClient.java | 20 +- 14 files changed, 1563 insertions(+), 23 deletions(-) create mode 100644 src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index c15bdd72c9..83daa91e33 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -90,10 +90,11 @@ With IAM enforcement enabled, the existing task authorizer checks the execution permission to assume the task role, its trust policy, and the task role's permission to start the child. Account routing also works with enforcement disabled. The `.sync` polling and cancellation paths retain the task account; their additional IAM permissions -are not evaluated. Lambda, API Gateway, SQS, SNS and EventBridge tasks evaluate `Credentials` -themselves ([Lambda](#lambda-tasks-under-iam-enforcement), -[messaging](#messaging-tasks-under-iam-enforcement)); other integrations retain their existing -credential handling. +are not evaluated. Lambda, API Gateway, SQS, SNS, EventBridge, DynamoDB, S3 `putObject`, RDS Data and +Redshift Data tasks evaluate `Credentials` themselves +([Lambda](#lambda-tasks-under-iam-enforcement), [messaging](#messaging-tasks-under-iam-enforcement), +[data](#data-tasks-under-iam-enforcement)); other integrations retain their existing credential +handling. A foreign state-machine ARN without task credentials grants no account access. A missing or mismatched task role fails with `States.TaskFailed`. A target account @@ -642,8 +643,73 @@ account. With enforcement off nothing here is evaluated. Floci has no `aws-sdk:eventbridge:putEvents` integration: that resource fails with `States.TaskFailed` and "Unsupported resource" whether or not enforcement is on. -Integrations other than these, Lambda, API Gateway and nested executions are not evaluated yet: they -run in the state machine's account whatever the execution role's policies say. +## Data tasks under IAM enforcement + +These tasks and their `.waitForTaskToken` forms are evaluated with +[IAM enforcement](iam.md#resource-based-policies) on, in the same steps and with the same role errors +as [messaging tasks](#messaging-tasks-under-iam-enforcement): + +| Resource | Action | Resource evaluated | Refused with | +|---|---|---|---| +| `arn:aws:states:::dynamodb:putItem`, `getItem`, `deleteItem`, `updateItem`, `scan` | `dynamodb:PutItem` and so on | The table `TableName` names | `DynamoDB.AccessDeniedException` | +| `arn:aws:states:::aws-sdk:dynamodb:` | See below | See below | `DynamoDb.AccessDeniedException` | +| `arn:aws:states:::s3:putObject`, `arn:aws:states:::aws-sdk:s3:putObject` | `s3:PutObject` | `arn::s3:::/` | `S3.AccessDeniedException` | +| `arn:aws:states:::aws-sdk:rdsdata:executeStatement` | `rds-data:ExecuteStatement`, `secretsmanager:GetSecretValue` | `ResourceArn`, `SecretArn` | `RdsData.AccessDeniedException` | +| `arn:aws:states:::aws-sdk:redshiftdata:` | `redshift-data:` and what authenticates the call | See below | `RedshiftData.AccessDeniedException` | + +The `aws-sdk:dynamodb` form is checked as a direct DynamoDB request under enforcement is: + +- **Most APIs:** `dynamodb:` on the table, stream or other resource the request names, an ARN as + given, or on `*` when it names none, which includes a `putItem` with no `TableName`. +- **`batchGetItem`, `batchWriteItem`:** the API's action on each table in `RequestItems`. +- **`transactWriteItems`, `transactGetItems`:** no action of their own. Each item needs its own, one of + `dynamodb:PutItem`, `DeleteItem`, `UpdateItem`, `ConditionCheckItem` or `GetItem`, on its table, with + `dynamodb:EnclosingOperation` available to the policy. A table named by ARN counts for its name, as + execution reads it in the state machine's account. +- **`listTables`:** its action on the Region's `table/*` collection. +- **`executeStatement`:** `dynamodb:PartiQLSelect`, `PartiQLInsert`, `PartiQLUpdate` or `PartiQLDelete`, + by what the statement does. `batchExecuteStatement` and `executeTransaction` are checked under their + own names on each table a statement names, as a direct request is. + +Every permission is evaluated before the call, so one refused table in a batch or a transaction writes +nothing. + +The `aws-sdk:redshiftdata` form's statement operations (`describeStatement`, `cancelStatement`, +`getStatementResult`, `getStatementResultV2`, `listStatements`, `listSessions`) act on no resource in +the service reference, so they are checked on `*`. The others are checked on the cluster +`ClusterIdentifier` names, the workgroup `WorkgroupName` names, or the target of the session +`SessionId` names, with what an [EventBridge target](eventbridge.md) needs to authenticate: +`secretsmanager:GetSecretValue` on `SecretArn`, `redshift-serverless:GetCredentials` on the workgroup, +or `redshift:GetClusterCredentials` on the `dbuser` and `dbname` of a `DbUser`. A workgroup Floci does +not hold is evaluated on `workgroup/*`. + +`secretsmanager:GetSecretValue` on an RDS Data `SecretArn` follows AWS's `AmazonRDSDataFullAccess` +managed policy and the CDK's `grantDataApiAccess`, which grant it along with the Data API actions. + +A request whose member names nothing it can reach has only the role checks, and its service answers +it: no `TableName` in an optimized task or no recognised item in a transaction, a transaction's table +ARN that is malformed or in another Region, a DynamoDB `ResourceArn` or similar that is not an ARN, no +`Bucket` or `Key`, an RDS Data `ResourceArn` that is not an ARN, or a Redshift Data request naming no +target. An API a form does not serve keeps its existing answer: `dynamodb:query` and +`aws-sdk:rdsdata:beginTransaction` are "Unsupported" whether or not enforcement is on, and +`aws-sdk:redshiftdata` answers its own `ValidationException` for an operation it does not have. + +The S3 bucket is resolved as a direct request resolves it. A bucket name is one namespace across +partitions, so a task can reach a bucket of another partition, and the object's ARN is evaluated in the +bucket's partition, not the state machine's. A bucket policy takes part as it does for a direct +request: it can grant `s3:PutObject` to a role of the bucket's account with no identity policy, and a +Deny in it refuses a role its identity policy allows. Another account's bucket is `S3.NoSuchBucket` to +an allowed role unless `floci.services.s3.global-bucket-namespace` is on, and with it on both the +role's policy and the bucket's have to allow. A DynamoDB table named by an ARN of another account is +refused, since no table policy can grant it here. + +`.AccessDeniedException` is Floci's reading for these too and has not been verified against +AWS. Apart from `dynamodb:EnclosingOperation`, only global condition keys are available to the +policies: `dynamodb:LeadingKeys`, `dynamodb:Attributes` and the like are absent. Global tables are not +treated apart. With enforcement off nothing here is evaluated. + +Integrations other than these, the messaging tasks, Lambda, API Gateway and nested executions are not +evaluated yet: they run in the state machine's account whatever the execution role's policies say. ## Task credentials in history @@ -707,7 +773,8 @@ direct ECS API. Lambda mapping tasks currently return an unpaginated list; `Marker` and `MaxItems` are rejected with `Lambda.InvalidParameterValueException` instead of being silently ignored. These six integrations do not evaluate the state-machine execution role's per-action IAM policies; among the task integrations, Lambda, API -Gateway, nested executions and the [messaging tasks](#messaging-tasks-under-iam-enforcement) do. Name-based lookups use the +Gateway, nested executions, the [messaging tasks](#messaging-tasks-under-iam-enforcement) and the +[data tasks](#data-tasks-under-iam-enforcement) do. Name-based lookups use the execution scope; explicit ARNs retain the underlying service's cross-account lookup behavior. The underlying services' validation still applies. They implement request-response calls, without job-completion polling. diff --git a/src/main/java/io/floci/aws/core/common/RequestResources.java b/src/main/java/io/floci/aws/core/common/RequestResources.java index fcb7f3e3c1..a49d1bdd7d 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResources.java +++ b/src/main/java/io/floci/aws/core/common/RequestResources.java @@ -104,6 +104,26 @@ public final class RequestResources { return named(resources, formats(table, operation), form, body, partition, region, accountId, stored); } + /** + * The ARNs of the resources a JSON request body names, for a call that is not an HTTP request of its own, as a + * state machine's task to its integrated service: as {@link #of} reads the same request, whatever endpoint it + * would have reached. + */ + public static List ofBody(String operation, JsonNode body, String partition, String region, + String accountId, StoredResourceArns stored) { + RequestResourceMembers.Table table = RequestResourceMembers.table(); + List resources = operation == null ? null : table.operations().get(operation); + if (resources == null || resources.isEmpty()) { + return List.of(); + } + return named(resources, formats(table, operation), Map.of(), body, partition, region, accountId, stored); + } + + /** Whether the table holds the operation as one with no resource of its own, which is checked on {@code *}. */ + public static boolean actsOnNoResource(String operation) { + return reads(operation) && RequestResourceMembers.table().operations().get(operation).isEmpty(); + } + /** The ARNs of the resources the request names, as {@link #of} reads them. */ private static List named(List resources, Map formats, Map form, diff --git a/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java b/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java index 00404f055e..2549c4ae2f 100644 --- a/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java @@ -1577,7 +1577,14 @@ public class ResourceArnBuilder { } private List buildDynamoDbArns(ContainerRequestContext ctx, String region, String accountId) { - JsonNode json = readJsonBody(ctx); + return dynamoDbArns(readJsonBody(ctx), region, accountId); + } + + /** + * The resources a DynamoDB request names, read from its body alone: the tables, or the stream, export, + * import or other resource it gives, each as given when it gives an ARN, and {@code *} when it names none. + */ + public static List dynamoDbArns(JsonNode json, String region, String accountId) { if (json != null && json.isObject()) { if (json.hasNonNull("TableName")) { String tableName = json.get("TableName").asText().trim(); diff --git a/src/main/java/io/floci/aws/services/iam/ResourcePolicyProviders.java b/src/main/java/io/floci/aws/services/iam/ResourcePolicyProviders.java index 92dd0b127e..0904b374b4 100644 --- a/src/main/java/io/floci/aws/services/iam/ResourcePolicyProviders.java +++ b/src/main/java/io/floci/aws/services/iam/ResourcePolicyProviders.java @@ -24,6 +24,19 @@ public final class ResourcePolicyProviders { return policiesFor(providers, credentialScope, null, resourceArn); } + /** The ARN policies are evaluated on for {@code resourceArn}, as each provider resolves it. */ + public static String resolveResourceArn(Instance providers, String credentialScope, + String resourceArn) { + if (providers == null || providers.isUnsatisfied()) { + return resourceArn; + } + String resolved = resourceArn; + for (ResourcePolicyProvider provider : providers) { + resolved = provider.resolveResourceArn(credentialScope, resolved); + } + return resolved; + } + /** The policies applying to an action, as determined by each resource-owning service. */ public static List policiesFor( Instance providers, String credentialScope, String action, String resourceArn) { diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataJsonHandler.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataJsonHandler.java index c9fcc88bc5..b3e34ec213 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataJsonHandler.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataJsonHandler.java @@ -2,6 +2,7 @@ package io.floci.aws.services.redshiftdata; import com.fasterxml.jackson.databind.JsonNode; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.StoredResourceArns; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Response; @@ -16,6 +17,11 @@ public class RedshiftDataJsonHandler { this.service = service; } + /** The workgroups and session targets the service finds, for a caller naming the resources of a request. */ + public StoredResourceArns storedResourceArns() { + return service; + } + public Response handle(String action, JsonNode request, String region) { return switch (action) { case "ExecuteStatement" -> Response.ok(service.executeStatement(request, region)).build(); diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataTargetSubmitter.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataTargetSubmitter.java index 892bb8fe92..88b0199462 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataTargetSubmitter.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataTargetSubmitter.java @@ -1,5 +1,6 @@ package io.floci.aws.services.redshiftdata; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -110,9 +111,24 @@ public class RedshiftDataTargetSubmitter { ? AwsArnUtils.Arn.of("redshift", region, account, "cluster:" + request.path("ClusterIdentifier").asText()).toString() : targetArn; + List permissions = permissions( + batch ? "redshift-data:BatchExecuteStatement" : "redshift-data:ExecuteStatement", + statementTarget, request, account, region); + Optional refusal = roleCheck.refusal(permissions); + if (refusal.isPresent()) { + throw new AwsException("AccessDeniedException", refusal.get(), 403); + } + } + + /** + * What a Data API call on {@code target} needs: its action there and whatever authenticates it, read from the + * request. A call on a session's target, which names neither a cluster nor a workgroup, has a session's own + * credentials, so it needs only the action. + */ + public static List permissions(String action, String target, JsonNode request, String account, + String region) { List permissions = new ArrayList<>(); - permissions.add(new Permission( - batch ? "redshift-data:BatchExecuteStatement" : "redshift-data:ExecuteStatement", statementTarget)); + permissions.add(new Permission(action, target)); // The Data API ignores a blank value, so it picks the credentials the same way. String secret = request.path("SecretArn").asText(""); if (!secret.isBlank()) { @@ -122,8 +138,8 @@ public class RedshiftDataTargetSubmitter { permissions.add(new Permission("secretsmanager:GetSecretValue", secret)); } } else if (request.has("WorkgroupName")) { - permissions.add(new Permission("redshift-serverless:GetCredentials", targetArn)); - } else if (!request.path("DbUser").asText("").isBlank()) { + permissions.add(new Permission("redshift-serverless:GetCredentials", target)); + } else if (request.has("ClusterIdentifier") && !request.path("DbUser").asText("").isBlank()) { String cluster = request.path("ClusterIdentifier").asText(); permissions.add(new Permission("redshift:GetClusterCredentials", AwsArnUtils.Arn.of("redshift", region, account, @@ -132,10 +148,7 @@ public class RedshiftDataTargetSubmitter { AwsArnUtils.Arn.of("redshift", region, account, "dbname:" + cluster + "/" + request.path("Database").asText()).toString())); } - Optional refusal = roleCheck.refusal(permissions); - if (refusal.isPresent()) { - throw new AwsException("AccessDeniedException", refusal.get(), 403); - } + return permissions; } private static void putIfPresent(ObjectNode request, String field, String value) { 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 a08912ee3a..a2e47be66c 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java @@ -1259,7 +1259,8 @@ public class AslExecutor { /** Integrations {@link TaskPermissions} does not map stay unchecked, Lambda and API Gateway check their own. */ private void authorizeTask(StatesIntegration integration, JsonNode input, StateMachine sm, JsonNode credentials) { - Optional required = TaskPermissions.of(integration, input, sm); + Optional required = TaskPermissions.of(integration, input, sm, + redshiftDataHandler == null ? null : redshiftDataHandler.storedResourceArns()); if (required.isEmpty()) { return; } diff --git a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java index a57ff4eba9..bd80ebde46 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizer.java @@ -115,7 +115,7 @@ public class LambdaTaskAuthorizer { effectiveRoleArn = credentialsRoleArn; } for (Permission permission : permissions) { - Optional refusal = refusal(effectiveRoleArn, permission.action(), permission.resourceArn(), + Optional refusal = refusal(effectiveRoleArn, permission.action(), evaluatedOn(permission.resourceArn()), owner.region(), permission.conditionKeys()); if (refusal.isPresent()) { throw new AslExecutor.FailStateException(deniedError, refusal.get()); @@ -123,6 +123,15 @@ public class LambdaTaskAuthorizer { } } + /** + * The ARN a permission is evaluated on, the one a direct request is: S3's global bucket namespace reaches a + * bucket in another partition, whose ARN is in the bucket's partition and not the state machine's. + */ + private String evaluatedOn(String resourceArn) { + return ANY_RESOURCE.equals(resourceArn) ? resourceArn : ResourcePolicyProviders.resolveResourceArn( + resourcePolicies, AwsArnUtils.parse(resourceArn).service(), resourceArn); + } + /** * Returns why {@code roleArn} may not invoke {@code functionArn}, as Lambda's access denied * message words it, or nothing when it may. 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 569b237fc0..40e53eef4b 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java @@ -1,14 +1,26 @@ package io.floci.aws.services.stepfunctions; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import io.floci.aws.core.common.AwsArnUtils; +import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.RequestResources; +import io.floci.aws.core.common.StoredResourceArns; +import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser; +import io.floci.aws.services.dynamodb.DynamoDbTableNames; import io.floci.aws.services.eventbridge.EventBridgeService; +import io.floci.aws.services.iam.IamAuthorizedActions; +import io.floci.aws.services.iam.ResourceArnBuilder; +import io.floci.aws.services.redshiftdata.RedshiftDataTargetSubmitter; import io.floci.aws.services.sqs.SqsService; import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission; import io.floci.aws.services.stepfunctions.model.StateMachine; +import org.jboss.logging.Logger; +import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; +import java.util.Map; import java.util.Optional; import java.util.Set; @@ -22,8 +34,34 @@ import java.util.Set; */ record TaskPermissions(String deniedError, List permissions) { + /** The permissions of an integration whose refusal is its prefix and {@code AccessDeniedException}. */ + static TaskPermissions accessDenied(String errorPrefix, List permissions) { + return new TaskPermissions(errorPrefix + "AccessDeniedException", permissions); + } + + private static final Logger LOG = Logger.getLogger(TaskPermissions.class); + private static final String ANY_RESOURCE = "*"; + private static final String DYNAMODB_OPTIMIZED_PREFIX = "DynamoDB."; + private static final String DYNAMODB_SDK_PREFIX = "DynamoDb."; + private static final String REDSHIFT_DATA_PREFIX = "RedshiftData."; + private static final String RDS_DATA_PREFIX = "RdsData."; + private static final Set DYNAMODB_OPTIMIZED = + Set.of("putItem", "getItem", "deleteItem", "updateItem", "scan"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + /** 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); + } + + /** + * The permissions of a mapped integration, or nothing for one that is not checked. + * + * @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 + */ + static Optional of(StatesIntegration integration, JsonNode input, StateMachine machine, + StoredResourceArns redshiftData) { if (integration.is("sqs", "sendMessage")) { return Optional.of(sqsSendMessage("SQS.", input, machine)); } @@ -39,6 +77,22 @@ record TaskPermissions(String deniedError, List permissions) { if (integration.is("events", "putEvents")) { return Optional.of(eventsPutEvents(input, machine)); } + if (integration.isOptimizedService("dynamodb") && DYNAMODB_OPTIMIZED.contains(integration.api())) { + return Optional.of(dynamoDbOptimized(integration.api(), input, machine)); + } + if (integration.isSdkService("dynamodb")) { + return Optional.of(dynamoDbSdk(AslExecutor.capitalizeFirst(integration.api()), input, machine)); + } + if (integration.is("s3", "putObject") || integration.isSdk("s3", "putObject")) { + return Optional.of(s3PutObject(input, machine)); + } + if (integration.isSdkService("redshiftdata") && integration.suffix().isEmpty()) { + return Optional.of(redshiftData(AslExecutor.capitalizeFirst(integration.api()), input, machine, + redshiftData)); + } + if (integration.isSdkService("rdsdata") && "executeStatement".equals(integration.api())) { + return Optional.of(rdsDataExecuteStatement(input)); + } return Optional.empty(); } @@ -92,4 +146,134 @@ record TaskPermissions(String deniedError, List permissions) { return new TaskPermissions("EventBridge.AccessDeniedException", buses.stream().map(bus -> new Permission("events:PutEvents", bus)).toList()); } + + /** The action on the table {@code TableName} gives, or nothing without one, which DynamoDB answers. */ + private static TaskPermissions dynamoDbOptimized(String api, JsonNode input, StateMachine machine) { + String tableName = input.path("TableName").asText("").trim(); + if (tableName.isEmpty()) { + return accessDenied(DYNAMODB_OPTIMIZED_PREFIX, List.of()); + } + AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); + return accessDenied(DYNAMODB_OPTIMIZED_PREFIX, List.of(new Permission( + "dynamodb:" + AslExecutor.capitalizeFirst(api), + ResourceArnBuilder.toDynamoDbTableArn(tableName, owner.region(), owner.accountId())))); + } + + /** + * The check a direct request of the operation gets: a transaction by each item's own action on its table, + * and anything else by its action on the resources it names, every table of a batch. A value that is not an + * ARN where the request names a resource by one reaches nothing, so DynamoDB answers it. + */ + private static TaskPermissions dynamoDbSdk(String operation, JsonNode input, StateMachine machine) { + AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); + if ("TransactWriteItems".equals(operation) || "TransactGetItems".equals(operation)) { + return accessDenied(DYNAMODB_SDK_PREFIX, dynamoDbTransaction(operation, input, owner)); + } + String namedAs = "dynamodb:" + operation; + List named = RequestResources.reads(namedAs) + ? RequestResources.ofBody(namedAs, input, owner.partition(), owner.region(), owner.accountId(), null) + : ResourceArnBuilder.dynamoDbArns(input, owner.region(), owner.accountId()); + String action = dynamoDbAction(operation, input); + return accessDenied(DYNAMODB_SDK_PREFIX, named.stream() + .filter(resource -> ANY_RESOURCE.equals(resource) || AwsArnUtils.isArn(resource)) + .map(resource -> new Permission(action, resource)) + .toList()); + } + + /** {@code ExecuteStatement} is authorized by what its statement does, as a direct request is. */ + private static String dynamoDbAction(String operation, JsonNode input) { + String statementAction = "ExecuteStatement".equals(operation) + ? DynamoDbPartiQLParser.iamAction(input.path("Statement").asText(null)) : null; + return statementAction != null ? statementAction : "dynamodb:" + operation; + } + + /** + * Each item's own action on the table it names, resolved within the state machine's account as execution + * resolves it, the same for a table named by its ARN. An item DynamoDB would refuse, whose table name does not + * resolve or which names no table, needs nothing here: the service answers for the whole transaction. + */ + private static List dynamoDbTransaction(String operation, JsonNode input, AwsArnUtils.Arn owner) { + boolean read = "TransactGetItems".equals(operation); + List kinds = read ? List.of("Get") : List.of("Put", "Delete", "Update", "ConditionCheck"); + Map> enclosing = Map.of("dynamodb:EnclosingOperation", List.of(operation)); + List permissions = new ArrayList<>(); + JsonNode items = input.path("TransactItems"); + if (!items.isArray()) { + return permissions; + } + for (JsonNode item : items) { + for (String kind : kinds) { + String tableName = item.path(kind).path("TableName").asText("").trim(); + if (tableName.isEmpty()) { + continue; + } + try { + String table = DynamoDbTableNames.resolveWithRegion(tableName, owner.region()).name(); + permissions.add(new Permission("dynamodb:" + kind + "Item", + ResourceArnBuilder.toDynamoDbTableArn(table, owner.region(), owner.accountId()), enclosing)); + } catch (AwsException expected) { + LOG.debugv("Transaction item names a table DynamoDB will refuse: {0}", tableName); + } + } + } + return permissions; + } + + /** + * {@code s3:PutObject} on the object, in the state machine's partition: the authorizer moves it to the + * bucket's own. A request naming no bucket or key is answered by the integration. + */ + private static TaskPermissions s3PutObject(JsonNode input, StateMachine machine) { + String bucket = input.path("Bucket").asText(""); + String key = input.path("Key").asText(null); + if (bucket.isBlank() || key == null) { + return accessDenied("S3.", List.of()); + } + String partition = AwsArnUtils.parse(machine.getStateMachineArn()).partition(); + return accessDenied("S3.", List.of(new Permission("s3:PutObject", + AwsArnUtils.Arn.global(partition, "s3", "", bucket + "/" + key).toString()))); + } + + /** + * The check an EventBridge target of the Data API gets, on what the request names: its cluster, its workgroup + * or its session's target. An operation on no resource, as statement operations are in the service reference, + * is checked on {@code *}. A request that names nothing it needs, or an operation the Data API does not + * have, is answered by the service. + */ + private static TaskPermissions redshiftData(String operation, JsonNode input, StateMachine machine, + StoredResourceArns stored) { + String namedAs = "redshift-data:" + operation; + String action = IamAuthorizedActions.actionFor("redshift-data", operation); + if (!input.isObject() || !RequestResources.reads(namedAs)) { + return accessDenied(REDSHIFT_DATA_PREFIX, List.of()); + } + if (RequestResources.actsOnNoResource(namedAs)) { + return accessDenied(REDSHIFT_DATA_PREFIX, List.of(new Permission(action, ANY_RESOURCE))); + } + AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); + List permissions = new ArrayList<>(); + for (String target : RequestResources.ofBody(namedAs, input, owner.partition(), owner.region(), + owner.accountId(), stored)) { + RedshiftDataTargetSubmitter.permissions(action, target, input, owner.accountId(), owner.region()) + .forEach(required -> permissions.add(new Permission(required.action(), required.resourceArn()))); + } + return accessDenied(REDSHIFT_DATA_PREFIX, permissions); + } + + /** + * {@code rds-data:ExecuteStatement} on the cluster and, since the Data API reads the database's credentials + * from it as the caller, {@code secretsmanager:GetSecretValue} on the secret. The members are read in either + * casing, as the task's request is recased. A request with no ARN for the cluster is answered by the service. + */ + private static TaskPermissions rdsDataExecuteStatement(JsonNode input) { + JsonNode request = AslExecutor.recaseKeys(MAPPER, input, false); + String resourceArn = request.path("resourceArn").asText(null); + if (!AwsArnUtils.isArn(resourceArn)) { + return accessDenied(RDS_DATA_PREFIX, List.of()); + } + String secretArn = request.path("secretArn").asText(null); + Permission execute = new Permission("rds-data:ExecuteStatement", resourceArn); + return accessDenied(RDS_DATA_PREFIX, AwsArnUtils.isArn(secretArn) + ? List.of(execute, new Permission("secretsmanager:GetSecretValue", secretArn)) : List.of(execute)); + } } diff --git a/src/test/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizerTest.java b/src/test/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizerTest.java index f75d7a047a..7b41b6fb18 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizerTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/LambdaTaskAuthorizerTest.java @@ -80,8 +80,10 @@ class LambdaTaskAuthorizerTest { when(functionPolicies.getResourcePolicies("lambda", OWN_FUNCTION)) .thenReturn(List.of(new ResourcePolicy(null, SFN_ACCOUNT))); when(functionPolicies.getResourcePolicies(anyString(), anyString(), anyString())).thenCallRealMethod(); + when(functionPolicies.resolveResourceArn(anyString(), anyString())).thenCallRealMethod(); bucketPolicies = mock(ResourcePolicyProvider.class); when(bucketPolicies.getResourcePolicies(anyString(), anyString(), anyString())).thenReturn(List.of()); + when(bucketPolicies.resolveResourceArn(anyString(), anyString())).thenCallRealMethod(); Instance providers = mock(Instance.class); when(providers.iterator()).thenAnswer(call -> List.of(functionPolicies, bucketPolicies).iterator()); ObjectMapper mapper = new ObjectMapper(); @@ -437,6 +439,23 @@ class LambdaTaskAuthorizerTest { + "because no identity-based policy allows the states:DescribeRegions action", refused.cause); } + /** The ARN the policies see is the one the resource's provider resolves, as a direct request's is. */ + @Test + void aPermissionIsEvaluatedOnTheArnItsProviderResolves() { + String moved = "arn:aws-cn:s3:::orders"; + when(bucketPolicies.resolveResourceArn("s3", BUCKET)).thenReturn(moved); + roleWithPolicies(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:PutObject","Resource":"%s"}]}""".formatted(BUCKET)); + executionRole(STATES_TRUST); + + AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, + () -> authorizer.authorize(machine(), null, "S3.AccessDeniedException", List.of(new Permission("s3:PutObject", BUCKET)))); + + assertEquals("S3.AccessDeniedException", refused.error); + assertTrue(refused.cause.contains(moved), refused.cause); + } + /** An S3 ARN has no account segment: with no owner known, it is not another account's resource. */ @Test void anS3ArnWithNoAccountIsNotCrossAccount() { diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java new file mode 100644 index 0000000000..02affe1274 --- /dev/null +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsDataTaskIamIntegrationTest.java @@ -0,0 +1,894 @@ +package io.floci.aws.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.floci.aws.services.rdsdata.RdsDataService; +import io.floci.aws.services.redshiftdata.RedshiftDataService; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.floci.aws.testing.RestAssuredJsonUtils; +import io.floci.aws.testing.StepFunctionsTestClient; +import io.quarkus.test.InjectMock; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.net.URI; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static io.floci.aws.testing.StepFunctionsTestClient.LAMBDA_TRUST; +import static io.floci.aws.testing.StepFunctionsTestClient.STATES_TRUST; +import static io.floci.aws.testing.StepFunctionsTestClient.trusting; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.timeout; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * DynamoDB, S3, RDS Data and Redshift Data tasks under IAM enforcement. DynamoDB and S3 run for real, so the tests + * read what a task wrote. The Data APIs need database containers, so their services are mocked, as + * {@code StepFunctionsRdsDataIntegrationTest} and {@code StepFunctionsRedshiftDataIntegrationTest} mock them, and + * reaching the service is what is observed. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class StepFunctionsDataTaskIamIntegrationTest { + private static final String ACCOUNT = "000000000461"; + private static final String OTHER_ACCOUNT = "000000000462"; + 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 ASSUME = allow("*", "sts:AssumeRole"); + private static final String SECRET = "arn:aws:secretsmanager:" + REGION + ":" + ACCOUNT + ":secret:db-AbCdEf"; + private static final String CLUSTER = "arn:aws:rds:" + REGION + ":" + ACCOUNT + ":cluster:orders"; + private static final String REDSHIFT_CLUSTER = "arn:aws:redshift:" + REGION + ":" + ACCOUNT + ":cluster:orders"; + + @TestHTTPResource + URI baseUri; + + @InjectMock + RdsDataService rdsDataService; + + @InjectMock + RedshiftDataService redshiftDataService; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @BeforeEach + void stubDataApis() { + when(rdsDataService.executeStatement(any(JsonNode.class), anyString())) + .thenAnswer(call -> MAPPER.createObjectNode()); + when(redshiftDataService.executeStatement(any(JsonNode.class), anyString())) + .thenAnswer(call -> MAPPER.createObjectNode().put("Id", "statement")); + when(redshiftDataService.describeStatement(any(JsonNode.class))) + .thenAnswer(call -> MAPPER.createObjectNode().put("Id", "statement")); + } + + static Stream integrations() { + return Stream.of("dynamodb:putItem", "aws-sdk:dynamodb:putItem", "s3:putObject", "aws-sdk:s3:putObject", + "aws-sdk:rdsdata:executeStatement", "aws-sdk:redshiftdata:executeStatement"); + } + + static Stream integrationsInBothLanguages() { + return integrations().flatMap(integration -> Stream.of(Arguments.of(integration, "jsonpath"), + Arguments.of(integration, "jsonata"))); + } + + @ParameterizedTest + @MethodSource("integrations") + void anExecutionRoleAllowedTheActionOnTheResourceReachesTheService(String integration) throws Exception { + Target target = target(integration); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, target.grant())), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + target.reached().check(); + } + + @ParameterizedTest + @MethodSource("integrationsInBothLanguages") + void anExecutionRoleNotAllowedTheActionIsRefused(String integration, String form) throws Exception { + Target target = target(integration); + Map task = "jsonata".equals(form) ? jsonataTask(target, null) : jsonPathTask(target, null); + + Response completed = terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + assertFailed(completed, target.error()); + String cause = completed.jsonPath().getString("cause"); + assertTrue(cause.contains(target.action()), cause); + assertTrue(cause.contains(target.resourceArn()), cause); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("integrations") + void theActionOnAnotherResourceDoesNotCount(String integration) throws Exception { + Target target = target(integration); + String role = role(STATES_TRUST, allow(target.resourceArn() + "-elsewhere", target.action())); + + assertFailed(terminal(start(machine(jsonPathTask(target, null), role), "{}")), target.error()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("integrations") + void anExecutionRoleThatDoesNotTrustStepFunctionsIsRefusedWhateverItsPolicies(String integration) throws Exception { + Target target = target(integration); + String role = role(LAMBDA_TRUST, target.grant()); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(completed, "States.Permissions"); + assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("integrations") + void anExecutionRoleThatDoesNotExistIsRefused(String integration) throws Exception { + Target target = target(integration); + String role = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID(); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(completed, "States.Permissions"); + assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("integrationsInBothLanguages") + void credentialsReachTheServiceAsTheirRoleWithoutTheExecutionRolesPermission(String integration, String form) + throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, ASSUME); + String taskRole = role(trusting(executionRole), target.grant()); + Map task = "jsonata".equals(form) ? jsonataTask(target, "{% $states.input.role %}") + : jsonPathTask(target, taskRole); + + String execution = start(machine(task, executionRole), MAPPER.writeValueAsString(Map.of("role", taskRole))); + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + target.reached().check(); + assertEquals(taskRole, eventsOfType(execution, "TaskScheduled").getFirst() + .path("taskScheduledEventDetails").path("taskCredentials").path("roleArn").asText()); + } + + @ParameterizedTest + @MethodSource("integrations") + void aRoleTheExecutionRoleCannotAssumeFailsInTheNestedForm(String integration) throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, target.grant()); + String taskRole = role(STATES_TRUST, target.grant()); + + Response completed = terminal(start(machine(jsonPathTask(target, taskRole), executionRole), "{}")); + + assertFailed(completed, "States.TaskFailed"); + assertTrue(completed.jsonPath().getString("cause").contains("is not authorized to assume"), completed.asString()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("integrations") + void aCredentialsRoleNotAllowedTheActionIsRefusedEvenIfTheExecutionRoleIs(String integration) throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, allowAll()); + String taskRole = role(trusting(executionRole), READ_ONLY); + + assertFailed(terminal(start(machine(jsonPathTask(target, taskRole), executionRole), "{}")), target.error()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("integrations") + void waitForTaskTokenRefusedDoesNotWaitAndReachesNothing(String integration) throws Exception { + Target target = target(integration); + Map task = new LinkedHashMap<>(jsonPathTask(target, null)); + task.put("Resource", "arn:aws:states:::" + integration + ".waitForTaskToken"); + task.put("TimeoutSeconds", 60); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), target.error()); + target.notReached().check(); + } + + @ParameterizedTest + @MethodSource("integrations") + void waitForTaskTokenAllowedReachesTheServiceAndWaits(String integration) throws Exception { + Target target = target(integration); + Map task = new LinkedHashMap<>(Map.of("Type", "Task", + "Resource", "arn:aws:states:::" + integration + ".waitForTaskToken", + "Parameters", target.tokenArguments(), "TimeoutSeconds", 60, "End", true)); + + String execution = start(machine(task, role(STATES_TRUST, target.grant())), "{}"); + String token = target.token().read(); + request("SendTaskSuccess", Map.of("taskToken", token, "output", "{\"done\":true}")).then().statusCode(200); + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + } + + @ParameterizedTest + @MethodSource("integrations") + void aRefusalCanBeRetriedAndCaught(String integration) throws Exception { + Target target = target(integration); + Map task = new LinkedHashMap<>(jsonPathTask(target, null)); + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + task.put("Catch", List.of(Map.of("ErrorEquals", List.of(target.error()), "Next", "Recovered"))); + String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task, + "Recovered", Map.of("Type", "Pass", "End", true)))); + String execution = start(machineWithDefinition(definition, role(STATES_TRUST, READ_ONLY)), "{}"); + + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals(2, eventsOfType(execution, "TaskFailed").size()); + assertEquals(target.error(), eventsOfType(execution, "TaskFailed").getLast() + .path("taskFailedEventDetails").path("error").asText()); + } + + /** Each optimized API needs its own action: the same role with every other one is refused. */ + @ParameterizedTest + @CsvSource({"getItem,GetItem", "deleteItem,DeleteItem", "updateItem,UpdateItem", "scan,Scan"}) + void anOptimizedOperationNeedsItsOwnAction(String api, String operation) throws Exception { + String table = table(); + Map arguments = "scan".equals(api) ? Map.of("TableName", table) + : Map.of("TableName", table, "Key", Map.of("pk", Map.of("S", "a"))); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::dynamodb:" + api, + "Parameters", arguments, "End", true); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(table), "dynamodb:" + operation))), "{}")); + Response refused = terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(table), "dynamodb:PutItem"))), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertFailed(refused, "DynamoDB.AccessDeniedException"); + } + + @Test + void anOptimizedApiFlociDoesNotHaveStaysAnUnsupportedResource() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::dynamodb:query", + "Parameters", Map.of("TableName", "any"), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "States.TaskFailed"); + } + + @ParameterizedTest + @CsvSource({"getItem,GetItem", "deleteItem,DeleteItem", "updateItem,UpdateItem", "scan,Scan", "query,Query"}) + void anSdkOperationNeedsItsOwnAction(String api, String operation) throws Exception { + String table = table(); + Map arguments = switch (api) { + case "scan" -> Map.of("TableName", table); + case "query" -> Map.of("TableName", table, "KeyConditionExpression", "pk = :k", + "ExpressionAttributeValues", Map.of(":k", Map.of("S", "a"))); + default -> Map.of("TableName", table, "Key", Map.of("pk", Map.of("S", "a"))); + }; + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:dynamodb:" + api, + "Parameters", arguments, "End", true); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(table), "dynamodb:" + operation))), "{}")); + Response refused = terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(table), "dynamodb:PutItem"))), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertFailed(refused, "DynamoDb.AccessDeniedException"); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void aBatchWriteOnTwoTablesIsRefusedWhenOneIsDeniedAndWritesNothing(boolean firstDenied) throws Exception { + String first = table(); + String second = table(); + Map task = sdkTask("batchWriteItem", Map.of("RequestItems", Map.of( + first, List.of(Map.of("PutRequest", Map.of("Item", Map.of("pk", Map.of("S", "batch"))))), + second, List.of(Map.of("PutRequest", Map.of("Item", Map.of("pk", Map.of("S", "batch")))))))); + String allowedTable = firstDenied ? second : first; + + Response refused = terminal(start(machine(task, role(STATES_TRUST, + allow(tableArn(allowedTable), "dynamodb:BatchWriteItem"))), "{}")); + + assertFailed(refused, "DynamoDb.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains(tableArn(firstDenied ? first : second)), refused.asString()); + assertFalse(hasItem(first, "batch")); + assertFalse(hasItem(second, "batch")); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, + allowEach(List.of(tableArn(first), tableArn(second)), "dynamodb:BatchWriteItem"))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertTrue(hasItem(first, "batch")); + assertTrue(hasItem(second, "batch")); + } + + @Test + void aBatchGetNeedsItsActionOnEachTable() throws Exception { + String first = table(); + String second = table(); + Map keys = Map.of("Keys", List.of(Map.of("pk", Map.of("S", "a")))); + Map task = sdkTask("batchGetItem", Map.of("RequestItems", Map.of(first, keys, second, keys))); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(first), "dynamodb:BatchGetItem"))), "{}")), + "DynamoDb.AccessDeniedException"); + Response allowed = terminal(start(machine(task, role(STATES_TRUST, + allowEach(List.of(tableArn(first), tableArn(second)), "dynamodb:BatchGetItem"))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + /** Authorized as each item's own action, never as the transaction's. */ + @Test + void aTransactWriteNeedsEachItemsActionOnItsTableAndWritesNothingWhenOneIsDenied() throws Exception { + String first = table(); + String second = table(); + putItem(second, "gone"); + Map task = sdkTask("transactWriteItems", Map.of("TransactItems", List.of( + Map.of("Put", Map.of("TableName", first, "Item", Map.of("pk", Map.of("S", "written")))), + Map.of("Delete", Map.of("TableName", second, "Key", Map.of("pk", Map.of("S", "gone"))))))); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, allowEachAction(Map.of( + "dynamodb:PutItem", tableArn(first), "dynamodb:DeleteItem", tableArn(first))))), "{}")); + assertFailed(refused, "DynamoDb.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains("dynamodb:DeleteItem"), refused.asString()); + assertTrue(refused.jsonPath().getString("cause").contains(tableArn(second)), refused.asString()); + assertFalse(hasItem(first, "written")); + assertTrue(hasItem(second, "gone")); + + Response transactVerbOnly = terminal(start(machine(task, role(STATES_TRUST, + allow("*", "dynamodb:TransactWriteItems"))), "{}")); + assertFailed(transactVerbOnly, "DynamoDb.AccessDeniedException"); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allowEachAction(Map.of( + "dynamodb:PutItem", tableArn(first), "dynamodb:DeleteItem", tableArn(second))))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertTrue(hasItem(first, "written")); + assertFalse(hasItem(second, "gone")); + } + + @Test + void aTransactGetNeedsGetItemOnEachTable() throws Exception { + String first = table(); + String second = table(); + Map key = Map.of("pk", Map.of("S", "a")); + Map task = sdkTask("transactGetItems", Map.of("TransactItems", List.of( + Map.of("Get", Map.of("TableName", first, "Key", key)), + Map.of("Get", Map.of("TableName", second, "Key", key))))); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(first), "dynamodb:GetItem"))), "{}")); + assertFailed(refused, "DynamoDb.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains(tableArn(second)), refused.asString()); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, + allowEach(List.of(tableArn(first), tableArn(second)), "dynamodb:GetItem"))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + /** {@code dynamodb:EnclosingOperation} reaches the policy, as it does for a direct transaction. */ + @Test + void aTransactionsEnclosingOperationReachesThePolicy() throws Exception { + String table = table(); + Map task = sdkTask("transactWriteItems", Map.of("TransactItems", List.of( + Map.of("Put", Map.of("TableName", table, "Item", Map.of("pk", Map.of("S", "conditioned"))))))); + String policy = MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", List.of( + Map.of("Effect", "Allow", "Action", "dynamodb:PutItem", "Resource", tableArn(table), "Condition", + Map.of("StringEquals", Map.of("dynamodb:EnclosingOperation", "TransactWriteItems")))))); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, policy)), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + @Test + void listTablesNeedsItsRegionalCollection() throws Exception { + String collection = "arn:aws:dynamodb:" + REGION + ":" + ACCOUNT + ":table/*"; + Map task = sdkTask("listTables", Map.of()); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(collection, "dynamodb:ListTables"))), "{}")); + Response refused = terminal(start(machine(task, role(STATES_TRUST, + allow("arn:aws:dynamodb:" + REGION + ":" + ACCOUNT + ":table/one", "dynamodb:ListTables"))), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertFailed(refused, "DynamoDb.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains(collection), refused.asString()); + } + + @Test + void aStatementIsAuthorizedByWhatItDoes() throws Exception { + String table = table(); + Map task = sdkTask("executeStatement", Map.of("Statement", "SELECT * FROM \"" + table + "\"")); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(table), "dynamodb:PartiQLSelect"))), "{}")); + Response refused = terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(table), "dynamodb:ExecuteStatement"))), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertFailed(refused, "DynamoDb.AccessDeniedException"); + } + + @ParameterizedTest + @CsvSource({"dynamodb:putItem,DynamoDB.", "aws-sdk:dynamodb:putItem,DynamoDb."}) + void aTableNamedByItsArnNeedsThePermissionOnThatArn(String integration, String prefix) throws Exception { + String table = table(); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::" + integration, + "Parameters", Map.of("TableName", tableArn(table), "Item", Map.of("pk", Map.of("S", "by-arn"))), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(table) + "x", "dynamodb:PutItem"))), "{}")), + prefix + "AccessDeniedException"); + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(tableArn(table), "dynamodb:PutItem"))), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + /** No table policy can grant it, so the role's own policy on that ARN is not enough. */ + @Test + void aTableArnOfAnotherAccountIsRefused() throws Exception { + String arn = "arn:aws:dynamodb:" + REGION + ":" + OTHER_ACCOUNT + ":table/" + table(); + Map task = sdkTask("putItem", Map.of("TableName", arn, "Item", Map.of("pk", Map.of("S", "a")))); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow(arn, "dynamodb:PutItem"))), "{}")), + "DynamoDb.AccessDeniedException"); + } + + @Test + void anOptimizedRequestNamingNoTableIsAnsweredByDynamoDb() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::dynamodb:putItem", + "Parameters", Map.of("Item", Map.of("pk", Map.of("S", "a"))), "End", true); + + Response completed = terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString()); + assertFalse(completed.jsonPath().getString("error").endsWith("AccessDeniedException"), completed.asString()); + } + + @Test + void aTransactionWithNoItemsIsAnsweredByDynamoDb() throws Exception { + Map task = sdkTask("transactWriteItems", Map.of("TransactItems", "not-a-list")); + + Response completed = terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString()); + assertFalse(completed.jsonPath().getString("error").endsWith("AccessDeniedException"), completed.asString()); + } + + @ParameterizedTest + @ValueSource(strings = {"s3:putObject", "aws-sdk:s3:putObject"}) + void aRequestNamingNoBucketIsAnsweredByTheIntegration(String integration) throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::" + integration, + "Parameters", Map.of("Key", "a"), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "S3.InvalidRequest"); + } + + @ParameterizedTest + @ValueSource(strings = {"s3:putObject", "aws-sdk:s3:putObject"}) + void aBucketPolicyGrantsARoleWithNoIdentityPermission(String integration) throws Exception { + Target target = target(integration); + String role = role(STATES_TRUST, READ_ONLY); + setBucketPolicy(target.bucket(), bucketStatement("Allow", role, target.bucket())); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + target.reached().check(); + } + + @ParameterizedTest + @ValueSource(strings = {"s3:putObject", "aws-sdk:s3:putObject"}) + void aBucketPolicyDenyRefusesARoleItsIdentityPolicyAllows(String integration) throws Exception { + Target target = target(integration); + String role = role(STATES_TRUST, target.grant()); + setBucketPolicy(target.bucket(), bucketStatement("Deny", role, target.bucket())); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(completed, "S3.AccessDeniedException"); + assertTrue(completed.jsonPath().getString("cause").contains("resource-based policy"), completed.asString()); + target.notReached().check(); + } + + /** + * Buckets are per account unless the global namespace is on, so another account's is not one the task reaches. + * With it on, {@code LambdaTaskAuthorizerTest} pins that the bucket's owner makes the call a cross-account one. + */ + @Test + void aBucketOfAnotherAccountIsAnsweredByS3OnceTheRoleIsAllowed() throws Exception { + String bucket = bucket(OTHER_ACCOUNT, REGION); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::s3:putObject", + "Parameters", Map.of("Bucket", bucket, "Key", "a", "Body", "hello"), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "S3.AccessDeniedException"); + assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow("arn:aws:s3:::" + bucket + "/a", "s3:PutObject"))), "{}")), + "S3.NoSuchBucket"); + } + + /** S3's one namespace reaches a bucket of another partition, whose ARN is the one a direct request is checked on. */ + @Test + void aBucketInAnotherPartitionIsEvaluatedInItsOwn() throws Exception { + String bucket = bucket(ACCOUNT, "cn-north-1"); + String key = "partitioned"; + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::s3:putObject", + "Parameters", Map.of("Bucket", bucket, "Key", key, "Body", "hello"), "End", true); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, + allow("arn:aws:s3:::" + bucket + "/" + key, "s3:PutObject"))), "{}")); + Response allowed = terminal(start(machine(task, role(STATES_TRUST, + allow("arn:aws-cn:s3:::" + bucket + "/" + key, "s3:PutObject"))), "{}")); + + assertFailed(refused, "S3.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains("arn:aws-cn:s3:::" + bucket), refused.asString()); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + @Test + void aMissingBucketIsAnsweredByS3OnceTheRoleIsAllowed() throws Exception { + String bucket = "sfn-iam-missing-" + UUID.randomUUID(); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::s3:putObject", + "Parameters", Map.of("Bucket", bucket, "Key", "a"), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow("arn:aws:s3:::" + bucket + "/a", "s3:PutObject"))), "{}")), + "S3.NoSuchBucket"); + } + + /** The secret is the caller's to read, as AWS's own {@code AmazonRDSDataFullAccess} policy has it. */ + @Test + void anRdsDataStatementNeedsTheSecretToo() throws Exception { + Target target = target("aws-sdk:rdsdata:executeStatement"); + + Response refused = terminal(start(machine(jsonPathTask(target, null), role(STATES_TRUST, + allow(CLUSTER, "rds-data:ExecuteStatement"))), "{}")); + + assertFailed(refused, "RdsData.AccessDeniedException"); + String cause = refused.jsonPath().getString("cause"); + assertTrue(cause.contains("secretsmanager:GetSecretValue"), cause); + assertTrue(cause.contains(SECRET), cause); + target.notReached().check(); + } + + @ParameterizedTest + @CsvSource({"resourceArn,secretArn", "ResourceArn,SecretArn"}) + void anRdsDataRequestIsReadInEitherCasing(String resourceMember, String secretMember) throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:rdsdata:executeStatement", + "Parameters", Map.of(resourceMember, CLUSTER, secretMember, SECRET, "Sql", "select 1"), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "RdsData.AccessDeniedException"); + } + + @Test + void anRdsDataRequestNamingNoClusterIsAnsweredByTheService() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:rdsdata:executeStatement", + "Parameters", Map.of("ResourceArn", "not-an-arn", "SecretArn", SECRET, "Sql", "select 1"), "End", true); + + terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + verify(rdsDataService, timeout(5000)).executeStatement(any(JsonNode.class), anyString()); + } + + /** The Data API's statement operations act on no resource in the service reference. */ + @Test + void aRedshiftDataStatementOperationIsCheckedOnAnyResource() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:redshiftdata:describeStatement", + "Parameters", Map.of("Id", "statement"), "End", true); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, + allow(REDSHIFT_CLUSTER, "redshift-data:DescribeStatement"))), "{}")); + Response allowed = terminal(start(machine(task, role(STATES_TRUST, + allow("*", "redshift-data:DescribeStatement"))), "{}")); + + assertFailed(refused, "RedshiftData.AccessDeniedException"); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + /** The credentials a cluster call authenticates with are the role's to get, as an EventBridge target's are. */ + @Test + void aRedshiftDataCallAsADatabaseUserNeedsItsClusterCredentials() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:redshiftdata:executeStatement", + "Parameters", Map.of("ClusterIdentifier", "orders", "Database", "dev", "DbUser", "admin", "Sql", "select 1"), + "End", true); + + Response refused = terminal(start(machine(task, role(STATES_TRUST, + allow(REDSHIFT_CLUSTER, "redshift-data:ExecuteStatement"))), "{}")); + + assertFailed(refused, "RedshiftData.AccessDeniedException"); + assertTrue(refused.jsonPath().getString("cause").contains("redshift:GetClusterCredentials"), refused.asString()); + verify(redshiftDataService, never()).executeStatement(any(JsonNode.class), anyString()); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allowEachAction(Map.of( + "redshift-data:ExecuteStatement", REDSHIFT_CLUSTER, "redshift:GetClusterCredentials", "*")))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + @Test + void aRedshiftDataRequestNamingNoTargetIsAnsweredByTheService() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:redshiftdata:executeStatement", + "Parameters", Map.of("Sql", "select 1"), "End", true); + + terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + verify(redshiftDataService, timeout(5000)).executeStatement(any(JsonNode.class), anyString()); + } + + private static String allow(String resource, String... actions) { + return allowEach(List.of(resource), actions); + } + + private static String allowEach(List resources, String... actions) { + return policy(List.of(Map.of("Effect", "Allow", "Action", List.of(actions), "Resource", resources))); + } + + private static String allowEachAction(Map resourceOfAction) { + List> statements = new ArrayList<>(); + resourceOfAction.forEach((action, resource) -> statements.add( + Map.of("Effect", "Allow", "Action", action, "Resource", resource))); + return policy(statements); + } + + private static String allowAll() { + return allow("*", "dynamodb:*", "s3:*", "rds-data:*", "redshift-data:*", "secretsmanager:*", "sts:AssumeRole"); + } + + private static String policy(List> statements) { + try { + return MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", statements)); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + + private static String bucketStatement(String effect, String principal, String bucket) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"%s"}, + "Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"}]} + """.formatted(effect, principal, bucket); + } + + private static void assertFailed(Response completed, String error) { + assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals(error, completed.jsonPath().getString("error"), completed.asString()); + } + + @FunctionalInterface + private interface Check { + void check() throws Exception; + } + + @FunctionalInterface + private interface TokenRead { + String read() throws Exception; + } + + /** + * What a task acts on and how to observe it. + * + * @param grant the policy that allows everything the call needs + */ + private record Target(String integration, String error, String action, String resourceArn, String grant, + Map arguments, Map tokenArguments, Check reached, + Check notReached, TokenRead token, String bucket) { + } + + private Target target(String integration) { + return switch (integration) { + case "dynamodb:putItem" -> tableTarget(integration, "DynamoDB."); + case "aws-sdk:dynamodb:putItem" -> tableTarget(integration, "DynamoDb."); + case "s3:putObject", "aws-sdk:s3:putObject" -> objectTarget(integration); + case "aws-sdk:rdsdata:executeStatement" -> rdsDataTarget(integration); + case "aws-sdk:redshiftdata:executeStatement" -> redshiftDataTarget(integration); + default -> throw new IllegalArgumentException(integration); + }; + } + + private Target tableTarget(String integration, String prefix) { + String table = table(); + return new Target(integration, prefix + "AccessDeniedException", "dynamodb:PutItem", tableArn(table), + allow(tableArn(table), "dynamodb:PutItem"), + Map.of("TableName", table, "Item", Map.of("pk", Map.of("S", "hello"))), + Map.of("TableName", table, "Item", Map.of("pk", Map.of("S.$", "$$.Task.Token"))), + () -> assertTrue(hasItem(table, "hello")), + () -> assertFalse(hasItem(table, "hello")), + () -> awaitScannedKey(table), null); + } + + private Target objectTarget(String integration) { + String bucket = bucket(ACCOUNT, REGION); + String key = "orders/a+b:c.txt"; + String objectArn = "arn:aws:s3:::" + bucket + "/" + key; + return new Target(integration, "S3.AccessDeniedException", "s3:PutObject", objectArn, + allow(objectArn, "s3:PutObject"), + Map.of("Bucket", bucket, "Key", key, "Body", "hello"), + Map.of("Bucket", bucket, "Key", key, "Body.$", "$$.Task.Token"), + () -> assertEquals("hello", object(bucket, key).asString()), + () -> assertEquals(404, object(bucket, key).statusCode()), + () -> awaitObject(bucket, key), bucket); + } + + private Target rdsDataTarget(String integration) { + return new Target(integration, "RdsData.AccessDeniedException", "rds-data:ExecuteStatement", CLUSTER, + allowEachAction(Map.of("rds-data:ExecuteStatement", CLUSTER, "secretsmanager:GetSecretValue", SECRET)), + Map.of("ResourceArn", CLUSTER, "SecretArn", SECRET, "Sql", "select 1"), + Map.of("ResourceArn", CLUSTER, "SecretArn", SECRET, "Sql.$", "$$.Task.Token"), + () -> verify(rdsDataService, timeout(5000)).executeStatement(any(JsonNode.class), anyString()), + () -> verify(rdsDataService, never()).executeStatement(any(JsonNode.class), anyString()), + () -> { + ArgumentCaptor sent = ArgumentCaptor.forClass(JsonNode.class); + verify(rdsDataService, timeout(5000)).executeStatement(sent.capture(), anyString()); + return sent.getValue().path("sql").asText(); + }, null); + } + + private Target redshiftDataTarget(String integration) { + return new Target(integration, "RedshiftData.AccessDeniedException", "redshift-data:ExecuteStatement", + REDSHIFT_CLUSTER, allowEachAction(Map.of("redshift-data:ExecuteStatement", REDSHIFT_CLUSTER, + "secretsmanager:GetSecretValue", SECRET)), + Map.of("ClusterIdentifier", "orders", "SecretArn", SECRET, "Database", "dev", "Sql", "select 1"), + Map.of("ClusterIdentifier", "orders", "SecretArn", SECRET, "Database", "dev", "Sql.$", "$$.Task.Token"), + () -> verify(redshiftDataService, timeout(5000)).executeStatement(any(JsonNode.class), anyString()), + () -> verify(redshiftDataService, never()).executeStatement(any(JsonNode.class), anyString()), + () -> { + ArgumentCaptor sent = ArgumentCaptor.forClass(JsonNode.class); + verify(redshiftDataService, timeout(5000)).executeStatement(sent.capture(), anyString()); + return sent.getValue().path("Sql").asText(); + }, null); + } + + private String table() { + String name = "sfn-iam-" + UUID.randomUUID(); + dynamoDb("CreateTable", Map.of("TableName", name, "BillingMode", "PAY_PER_REQUEST", + "AttributeDefinitions", List.of(Map.of("AttributeName", "pk", "AttributeType", "S")), + "KeySchema", List.of(Map.of("AttributeName", "pk", "KeyType", "HASH")))); + cleanup.register(() -> dynamoDb("DeleteTable", Map.of("TableName", name))); + return name; + } + + private static String tableArn(String table) { + return "arn:aws:dynamodb:" + REGION + ":" + ACCOUNT + ":table/" + table; + } + + private void putItem(String table, String key) { + dynamoDb("PutItem", Map.of("TableName", table, "Item", Map.of("pk", Map.of("S", key)))); + } + + private boolean hasItem(String table, String key) throws Exception { + Response found = dynamoDb("GetItem", Map.of("TableName", table, "Key", Map.of("pk", Map.of("S", key)))); + return MAPPER.readTree(found.asString()).has("Item"); + } + + private String awaitScannedKey(String table) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + do { + JsonNode items = MAPPER.readTree(dynamoDb("Scan", Map.of("TableName", table)).asString()).path("Items"); + if (!items.isEmpty()) { + return items.get(0).path("pk").path("S").asText(); + } + Thread.sleep(25); + } while (System.nanoTime() < deadline); + fail("Nothing reached " + table); + return null; + } + + private Response dynamoDb(String action, Map input) { + Response response = sfn().json(ACCOUNT, "dynamodb", "DynamoDB_20120810." + action, "application/x-amz-json-1.0", input); + response.then().statusCode(200); + return response; + } + + private String bucket(String account, String region) { + String name = "sfn-iam-" + UUID.randomUUID(); + String authorization = auth(account, region, "s3"); + given().port(baseUri.getPort()).header("Authorization", authorization) + .body(REGION.equals(region) ? "" : "" + region + + "") + .put("/" + name).then().statusCode(200); + cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(), authorization, name)); + return name; + } + + private void setBucketPolicy(String bucket, String policy) { + given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "s3")).body(policy) + .queryParam("policy", "").put("/" + bucket).then().statusCode(200); + } + + private Response object(String bucket, String key) { + return given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "s3")) + .urlEncodingEnabled(false).get("/" + bucket + "/" + key.replace("+", "%2B").replace(":", "%3A")); + } + + private String awaitObject(String bucket, String key) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + do { + Response found = object(bucket, key); + if (found.statusCode() == 200) { + return found.asString(); + } + Thread.sleep(25); + } while (System.nanoTime() < deadline); + fail("Nothing reached " + bucket + "/" + key); + return null; + } + + private static Map sdkTask(String api, Map arguments) { + return Map.of("Type", "Task", "Resource", "arn:aws:states:::aws-sdk:dynamodb:" + api, + "Parameters", arguments, "End", true); + } + + private Map jsonPathTask(Target target, String taskRole) { + Map task = new LinkedHashMap<>(Map.of("Type", "Task", + "Resource", "arn:aws:states:::" + target.integration(), + "Parameters", target.arguments(), "End", true)); + if (taskRole != null) { + task.put("Credentials", Map.of("RoleArn", taskRole)); + } + return task; + } + + private Map jsonataTask(Target target, String roleExpression) { + Map task = new LinkedHashMap<>(Map.of("Type", "Task", "QueryLanguage", "JSONata", + "Resource", "arn:aws:states:::" + target.integration(), + "Arguments", target.arguments(), "End", true)); + if (roleExpression != null) { + task.put("Credentials", Map.of("RoleArn", roleExpression)); + } + return task; + } + + private String role(String trust, String policy) { + return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", + "sfn-data-" + UUID.randomUUID(), trust, policy); + } + + private String machine(Map task, String role) throws Exception { + return machineWithDefinition(MAPPER.writeValueAsString( + Map.of("StartAt", "Send", "States", Map.of("Send", task))), role); + } + + private String machineWithDefinition(String definition, String role) { + return sfn().createMachine(ACCOUNT, "sfn-data-iam-", definition, "STANDARD", role); + } + + private String start(String machine, String input) { + return sfn().start(ACCOUNT, machine, input); + } + + private Response terminal(String execution) throws Exception { + return sfn().terminal(ACCOUNT, execution, 10); + } + + private List eventsOfType(String execution, String type) throws Exception { + return sfn().eventsOfType(ACCOUNT, execution, type); + } + + private Response request(String action, Map input) { + return sfn().request(ACCOUNT, action, input); + } + + private StepFunctionsTestClient sfn() { + return new StepFunctionsTestClient(baseUri.getPort(), cleanup); + } +} diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java index 8eb78a685d..80beff0333 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java @@ -33,6 +33,7 @@ import java.util.UUID; import static io.floci.aws.testing.EnforcementFixtures.auth; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; @@ -256,6 +257,60 @@ class StepFunctionsTaskCredentialsIntegrationTest { assertEquals(taskRole, taskScheduled(execution).path("taskCredentials").path("roleArn").asText()); } + /** Nothing evaluates a role that does not exist, nor a writer no policy allows. */ + @ParameterizedTest + @ValueSource(strings = {"dynamodb:putItem", "aws-sdk:dynamodb:putItem", "s3:putObject", "aws-sdk:s3:putObject"}) + void dataCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception { + String name = "credentials-" + UUID.randomUUID(); + Map arguments; + if (integration.contains("dynamodb")) { + dynamoDb("CreateTable", Map.of("TableName", name, "BillingMode", "PAY_PER_REQUEST", + "AttributeDefinitions", List.of(Map.of("AttributeName", "pk", "AttributeType", "S")), + "KeySchema", List.of(Map.of("AttributeName", "pk", "KeyType", "HASH")))); + cleanup.register(() -> dynamoDb("DeleteTable", Map.of("TableName", name))); + arguments = Map.of("TableName", name, "Item", Map.of("pk", Map.of("S", "a"))); + } else { + given().port(baseUri.getPort()).header("Authorization", auth(SOURCE, "s3")).put("/" + name) + .then().statusCode(200); + cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(), auth(SOURCE, "s3"), name)); + arguments = Map.of("Bucket", name, "Key", "a", "Body", "hello"); + } + assertDataTaskIsNotEvaluated(integration, arguments, "SUCCEEDED"); + } + + /** Past authorization, the service answers: these name a database nothing has, so they fail with its own error. */ + @ParameterizedTest + @ValueSource(strings = {"aws-sdk:rdsdata:executeStatement", "aws-sdk:redshiftdata:executeStatement"}) + void dataApiCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception { + Map arguments = integration.contains("rdsdata") + ? Map.of("ResourceArn", "arn:aws:rds:us-east-1:" + SOURCE + ":cluster:no-such-cluster", + "SecretArn", "arn:aws:secretsmanager:us-east-1:" + SOURCE + ":secret:no-such-secret", + "Sql", "select 1") + : Map.of("ClusterIdentifier", "no-such-cluster", "Database", "dev", "Sql", "select 1"); + assertDataTaskIsNotEvaluated(integration, arguments, "FAILED"); + } + + private void assertDataTaskIsNotEvaluated(String integration, Map arguments, String status) + throws Exception { + String taskRole = "arn:aws:iam::" + TARGET + ":role/no-such-role"; + String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", Map.of( + "Type", "Task", "Resource", "arn:aws:states:::" + integration, + "Credentials", Map.of("RoleArn", taskRole), "Parameters", arguments, "End", true)))); + + String execution = start(machine(SOURCE, definition, "STANDARD"), "{}"); + Response done = terminal(SOURCE, execution); + + assertEquals(status, done.jsonPath().getString("status"), done.asString()); + String error = String.valueOf(done.jsonPath().getString("error")); + assertFalse(error.endsWith("AccessDeniedException") || "States.Permissions".equals(error), done.asString()); + assertEquals(taskRole, taskScheduled(execution).path("taskCredentials").path("roleArn").asText()); + } + + private void dynamoDb(String action, Map input) { + sfn().json(SOURCE, "dynamodb", "DynamoDB_20120810." + action, "application/x-amz-json-1.0", input) + .then().statusCode(200); + } + @Test void credentialsThatDoNotResolveStillPassWithEnforcementOff() throws Exception { SqsTestQueue queue = SqsTestQueue.create(sqsService, SOURCE, "us-east-1", "credentials-"); 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 bb7655566c..7f3655f07e 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.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.core.common.StoredResourceArns; import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission; import io.floci.aws.services.stepfunctions.model.StateMachine; import org.junit.jupiter.api.Test; @@ -14,12 +15,16 @@ import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; class TaskPermissionsTest { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String ACCOUNT = "111122223333"; private static final String TOPIC = "arn:aws:sns:eu-west-1:111122223333:orders"; + private static final String REDSHIFT_CLUSTER = "arn:aws:redshift:eu-west-1:111122223333:cluster:orders"; private static final String ENDPOINT = "arn:aws:sns:eu-west-1:111122223333:endpoint/GCM/app/id"; /** Each form resolves in the state machine's Region, whichever host it names, as the queue lookup does. */ @@ -61,7 +66,7 @@ class TaskPermissionsTest { @ParameterizedTest @ValueSource(strings = {"lambda:invoke", "apigateway:invoke", "aws-sdk:sqs:receiveMessage", "aws-sdk:sns:listTopics", "sns:publishBatch", "aws-sdk:eventbridge:putEvents", "events:listRules", "states:startExecution", - "dynamodb:putItem", "http:invoke"}) + "dynamodb:query", "http:invoke"}) void integrationsNotMappedStayUnchecked(String integration) { assertEquals(Optional.empty(), TaskPermissions.of(integration(integration), input("orders"), machine("aws"))); } @@ -168,6 +173,241 @@ class TaskPermissionsTest { eventsPermissions("{\"Entries\":[7,{\"EventBusName\":\"arn:aws:events:\"},{\"EventBusName\":\"a\"}]}")); } + @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()); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"TableName\":\" \"}", "{\"TableName\":{}}"}) + void anOptimizedDynamoDbTaskNamingNoTableNeedsNoPermission(String request) throws Exception { + assertEquals(TaskPermissions.accessDenied("DynamoDB.", List.of()), + TaskPermissions.of(integration("dynamodb:putItem"), json(request), machine("aws")).orElseThrow()); + } + + @Test + void anOptimizedDynamoDbApiNotServedStaysUnchecked() throws Exception { + assertEquals(Optional.empty(), TaskPermissions.of(integration("dynamodb:query"), json("{\"TableName\":\"t\"}"), machine("aws"))); + } + + @Test + void aTableNamedByItsArnIsEvaluatedAsGiven() throws Exception { + String arn = "arn:aws:dynamodb:eu-west-1:444455556666:table/orders"; + assertEquals(List.of(new Permission("dynamodb:PutItem", arn)), sdkPermissions("putItem", "{\"TableName\":\"" + arn + "\"}")); + assertEquals(List.of(new Permission("dynamodb:PutItem", arn)), + TaskPermissions.of(integration("dynamodb:putItem"), json("{\"TableName\":\"" + arn + "\"}"), machine("aws")) + .orElseThrow().permissions()); + } + + @Test + void anSdkDynamoDbTaskNamesItsOwnPrefix() throws Exception { + assertEquals("DynamoDb.AccessDeniedException", TaskPermissions.of(integration("aws-sdk:dynamodb:getItem"), + json("{}"), machine("aws")).orElseThrow().deniedError()); + } + + @Test + void aBatchNeedsItsActionOnEachTable() throws Exception { + assertEquals(List.of(new Permission("dynamodb:BatchWriteItem", table("a")), + new Permission("dynamodb:BatchWriteItem", table("b"))), + sdkPermissions("batchWriteItem", "{\"RequestItems\":{\"a\":[],\"b\":[]}}")); + assertEquals(List.of(new Permission("dynamodb:BatchGetItem", table("a")), + new Permission("dynamodb:BatchGetItem", table("b"))), + sdkPermissions("batchGetItem", "{\"RequestItems\":{\"a\":{},\"b\":{}}}")); + } + + @Test + void aTransactWriteNeedsEachItemsOwnActionOnItsTable() throws Exception { + Map> enclosing = Map.of("dynamodb:EnclosingOperation", List.of("TransactWriteItems")); + assertEquals(List.of(new Permission("dynamodb:PutItem", table("aaa"), enclosing), + new Permission("dynamodb:DeleteItem", table("bbb"), enclosing), + new Permission("dynamodb:UpdateItem", table("aaa"), enclosing), + new Permission("dynamodb:ConditionCheckItem", table("ccc"), enclosing)), + sdkPermissions("transactWriteItems", """ + {"TransactItems":[{"Put":{"TableName":"aaa"}},{"Delete":{"TableName":"bbb"}}, + {"Update":{"TableName":"aaa"}},{"ConditionCheck":{"TableName":"ccc"}}]}""")); + } + + @Test + void aTransactGetNeedsGetItemOnEachTable() throws Exception { + Map> enclosing = Map.of("dynamodb:EnclosingOperation", List.of("TransactGetItems")); + assertEquals(List.of(new Permission("dynamodb:GetItem", table("aaa"), enclosing), + new Permission("dynamodb:GetItem", table("bbb"), enclosing)), + sdkPermissions("transactGetItems", "{\"TransactItems\":[{\"Get\":{\"TableName\":\"aaa\"}},{\"Get\":{\"TableName\":\"bbb\"}}]}")); + } + + /** Execution resolves an ARN within the request's account, so that is the table the item is checked on. */ + @Test + void aTransactItemNamedByAnArnIsTheTableItsExecutionReaches() throws Exception { + assertEquals(List.of(new Permission("dynamodb:PutItem", table("aaa"), + Map.of("dynamodb:EnclosingOperation", List.of("TransactWriteItems")))), + sdkPermissions("transactWriteItems", """ + {"TransactItems":[{"Put":{"TableName":"arn:aws:dynamodb:eu-west-1:444455556666:table/aaa"}}]}""")); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"TransactItems\":\"x\"}", "{\"TransactItems\":[{\"Put\":{}}]}", + "{\"TransactItems\":[{\"Get\":{\"TableName\":\"aaa\"}}]}", + "{\"TransactItems\":[{\"Put\":{\"TableName\":\"arn:aws:dynamodb:ap-south-1:444455556666:table/aaa\"}}]}", + "{\"TransactItems\":[{\"Put\":{\"TableName\":\"a\"}}]}", + "{\"TransactItems\":[{\"Put\":{\"TableName\":\"arn:aws:s3:::aaa\"}}]}"}) + void aTransactionNamingNoTableItCanReachNeedsNoPermission(String request) throws Exception { + assertEquals(List.of(), sdkPermissions("transactWriteItems", request)); + } + + @Test + void listTablesNeedsItsRegionalCollection() throws Exception { + assertEquals(List.of(new Permission("dynamodb:ListTables", table("*"))), sdkPermissions("listTables", "{}")); + } + + @Test + void anOperationNamingNoTableIsCheckedOnAnyResource() throws Exception { + assertEquals(List.of(new Permission("dynamodb:DescribeLimits", "*")), sdkPermissions("describeLimits", "{}")); + } + + @Test + void aStatementIsAuthorizedByWhatItDoes() throws Exception { + assertEquals(List.of(new Permission("dynamodb:PartiQLSelect", table("a"))), + sdkPermissions("executeStatement", "{\"Statement\":\"SELECT * FROM \\\"a\\\"\"}")); + assertEquals(List.of(new Permission("dynamodb:PartiQLInsert", table("a"))), + sdkPermissions("executeStatement", "{\"Statement\":\"INSERT INTO \\\"a\\\" VALUE {'pk':'x'}\"}")); + } + + @Test + void aResourceThatIsNotAnArnNeedsNoPermission() throws Exception { + assertEquals(List.of(), sdkPermissions("tagResource", "{\"ResourceArn\":\"not-an-arn\"}")); + } + + @ParameterizedTest + @ValueSource(strings = {"s3:putObject", "aws-sdk:s3:putObject"}) + void anS3PutNeedsThePermissionOnTheObjectInTheMachinesPartition(String tail) throws Exception { + String request = "{\"Bucket\":\"orders\",\"Key\":\"a/b:c+d.txt\"}"; + assertEquals(TaskPermissions.accessDenied("S3.", List.of(new Permission("s3:PutObject", "arn:aws:s3:::orders/a/b:c+d.txt"))), + TaskPermissions.of(integration(tail), json(request), machine("aws")).orElseThrow()); + assertEquals(List.of(new Permission("s3:PutObject", "arn:aws-cn:s3:::orders/a/b:c+d.txt")), + TaskPermissions.of(integration(tail), json(request), machine("aws-cn")).orElseThrow().permissions()); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"Bucket\":\"orders\"}", "{\"Key\":\"a\"}", "{\"Bucket\":\"\",\"Key\":\"a\"}", + "{\"Bucket\":null,\"Key\":\"a\"}", "{\"Bucket\":\"orders\",\"Key\":null}"}) + void anS3PutNamingNoObjectNeedsNoPermission(String request) throws Exception { + assertEquals(TaskPermissions.accessDenied("S3.", List.of()), + TaskPermissions.of(integration("s3:putObject"), json(request), machine("aws")).orElseThrow()); + } + + @Test + void anS3ApiNotServedStaysUnchecked() throws Exception { + assertEquals(Optional.empty(), TaskPermissions.of(integration("s3:getObject"), json("{}"), machine("aws"))); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"ResourceArn\":\"%s\",\"SecretArn\":\"%s\"}", "{\"resourceArn\":\"%s\",\"secretArn\":\"%s\"}"}) + void anRdsDataStatementNeedsItsActionOnTheClusterAndTheSecret(String template) throws Exception { + String cluster = "arn:aws:rds:eu-west-1:" + ACCOUNT + ":cluster:orders"; + String secret = "arn:aws:secretsmanager:eu-west-1:" + ACCOUNT + ":secret:db"; + assertEquals(TaskPermissions.accessDenied("RdsData.", List.of(new Permission("rds-data:ExecuteStatement", cluster), + new Permission("secretsmanager:GetSecretValue", secret))), + TaskPermissions.of(integration("aws-sdk:rdsdata:executeStatement"), json(template.formatted(cluster, secret)), + machine("aws")).orElseThrow()); + } + + @Test + void anRdsDataStatementWithNoSecretArnNeedsOnlyItsAction() throws Exception { + String cluster = "arn:aws:rds:eu-west-1:" + ACCOUNT + ":cluster:orders"; + assertEquals(List.of(new Permission("rds-data:ExecuteStatement", cluster)), + TaskPermissions.of(integration("aws-sdk:rdsdata:executeStatement"), + json("{\"ResourceArn\":\"" + cluster + "\",\"SecretArn\":\"db\"}"), machine("aws")) + .orElseThrow().permissions()); + } + + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"ResourceArn\":\"orders\",\"SecretArn\":\"arn:aws:secretsmanager:eu-west-1:1:secret:db\"}"}) + void anRdsDataStatementNamingNoClusterNeedsNoPermission(String request) throws Exception { + assertEquals(TaskPermissions.accessDenied("RdsData.", List.of()), + TaskPermissions.of(integration("aws-sdk:rdsdata:executeStatement"), json(request), machine("aws")).orElseThrow()); + } + + @Test + void anRdsDataApiNotServedStaysUnchecked() throws Exception { + assertEquals(Optional.empty(), TaskPermissions.of(integration("aws-sdk:rdsdata:beginTransaction"), json("{}"), machine("aws"))); + } + + @ParameterizedTest + @CsvSource({"describeStatement,DescribeStatement", "cancelStatement,CancelStatement", + "getStatementResult,GetStatementResult", "getStatementResultV2,GetStatementResult", + "listStatements,ListStatements", "listSessions,ListSessions"}) + void aRedshiftDataOperationOnNoResourceIsCheckedOnAnyResource(String api, String action) throws Exception { + assertEquals(TaskPermissions.accessDenied("RedshiftData.", List.of(new Permission("redshift-data:" + action, "*"))), + TaskPermissions.of(integration("aws-sdk:redshiftdata:" + api), json("{\"Id\":\"s\"}"), machine("aws")).orElseThrow()); + } + + @ParameterizedTest + @CsvSource({"executeStatement,ExecuteStatement", "batchExecuteStatement,BatchExecuteStatement", + "listDatabases,ListDatabases", "listSchemas,ListSchemas", "listTables,ListTables", "describeTable,DescribeTable"}) + void aRedshiftDataCallOnAClusterNeedsItsActionAndItsSecret(String api, String operation) throws Exception { + String secret = "arn:aws:secretsmanager:eu-west-1:" + ACCOUNT + ":secret:db"; + assertEquals(List.of(new Permission("redshift-data:" + operation, REDSHIFT_CLUSTER), + new Permission("secretsmanager:GetSecretValue", secret)), + redshiftPermissions(api, "{\"ClusterIdentifier\":\"orders\",\"SecretArn\":\"" + secret + "\"}", null)); + } + + @Test + void aRedshiftDataCallAsADatabaseUserNeedsItsClusterCredentials() throws Exception { + String prefix = "arn:aws:redshift:eu-west-1:" + ACCOUNT; + assertEquals(List.of(new Permission("redshift-data:ExecuteStatement", REDSHIFT_CLUSTER), + new Permission("redshift:GetClusterCredentials", prefix + ":dbuser:orders/admin"), + new Permission("redshift:GetClusterCredentials", prefix + ":dbname:orders/dev")), + redshiftPermissions("executeStatement", + "{\"ClusterIdentifier\":\"orders\",\"DbUser\":\"admin\",\"Database\":\"dev\"}", null)); + } + + @Test + void aRedshiftDataCallOnAWorkgroupIsEvaluatedOnTheOneItsNameFinds() throws Exception { + String workgroup = "arn:aws:redshift-serverless:eu-west-1:" + ACCOUNT + ":workgroup/1234"; + StoredResourceArns stored = mock(StoredResourceArns.class); + when(stored.findByMembers(eq("workgroup"), eq(List.of("analytics")), eq("eu-west-1"))).thenReturn(Optional.of(workgroup)); + assertEquals(List.of(new Permission("redshift-data:ExecuteStatement", workgroup), + new Permission("redshift-serverless:GetCredentials", workgroup)), + redshiftPermissions("executeStatement", "{\"WorkgroupName\":\"analytics\"}", stored)); + } + + @Test + void aRedshiftDataCallOnASessionIsEvaluatedOnItsTarget() throws Exception { + StoredResourceArns stored = mock(StoredResourceArns.class); + when(stored.through("SessionId", "session", "eu-west-1")).thenReturn(List.of(REDSHIFT_CLUSTER)); + assertEquals(List.of(new Permission("redshift-data:ExecuteStatement", REDSHIFT_CLUSTER)), + redshiftPermissions("executeStatement", "{\"SessionId\":\"session\"}", stored)); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = {"executeStatement|{}", "executeStatement|[]", "executeSql|{\"ClusterIdentifier\":\"c\"}", + "noSuchOperation|{}"}) + void aRedshiftDataCallNamingNothingItNeedsNeedsNoPermission(String api, String request) throws Exception { + assertEquals(TaskPermissions.accessDenied("RedshiftData.", List.of()), + TaskPermissions.of(integration("aws-sdk:redshiftdata:" + api), json(request), machine("aws")).orElseThrow()); + } + + @Test + void aRedshiftDataSuffixIsNotServedAndStaysUnchecked() throws Exception { + assertEquals(Optional.empty(), TaskPermissions.of(integration("aws-sdk:redshiftdata:executeStatement.sync"), json("{}"), machine("aws"))); + } + + private static List sdkPermissions(String api, String request) throws Exception { + return TaskPermissions.of(integration("aws-sdk:dynamodb:" + api), json(request), machine("aws")).orElseThrow().permissions(); + } + + private static List redshiftPermissions(String api, String request, StoredResourceArns stored) throws Exception { + return TaskPermissions.of(integration("aws-sdk:redshiftdata:" + api), json(request), machine("aws"), stored) + .orElseThrow().permissions(); + } + + private static String table(String name) { + return "arn:aws:dynamodb:eu-west-1:" + ACCOUNT + ":table/" + name; + } + private static List snsPermissions(String request) throws Exception { return TaskPermissions.of(integration("sns:publish"), json(request), machine("aws")).orElseThrow().permissions(); } diff --git a/src/test/java/io/floci/aws/testing/StepFunctionsTestClient.java b/src/test/java/io/floci/aws/testing/StepFunctionsTestClient.java index 72185a1f87..f41499c172 100644 --- a/src/test/java/io/floci/aws/testing/StepFunctionsTestClient.java +++ b/src/test/java/io/floci/aws/testing/StepFunctionsTestClient.java @@ -40,14 +40,26 @@ public final class StepFunctionsTestClient { } public Response request(String account, String action, Map input) { - return given().port(port).header("Authorization", auth(account, "states")) - .header("X-Amz-Target", "AWSStepFunctions." + action) - .contentType("application/x-amz-json-1.0").body(MAPPER.valueToTree(input).toString()).post("/"); + return json(account, "states", "AWSStepFunctions." + action, "application/x-amz-json-1.0", input); + } + + /** + * A JSON-protocol request to the service a task calls, signed as {@code account} for {@code signingName}, so a + * test reads and sets up the resources a task reaches in the account its execution runs in. + */ + public Response json(String account, String signingName, String target, String contentType, Map body) { + return given().port(port).header("Authorization", auth(account, signingName)) + .header("X-Amz-Target", target) + .contentType(contentType).body(MAPPER.valueToTree(body).toString()).post("/"); } /** Creates a state machine in us-east-1, which the end of the test stops and deletes. */ public String createMachine(String account, String namePrefix, String definition, String type, String role) { - String name = namePrefix + UUID.randomUUID(); + return createMachineNamed(account, namePrefix + UUID.randomUUID(), definition, type, role); + } + + /** {@link #createMachine} under the exact {@code name}, for a test that needs the machine's ARN up front. */ + public String createMachineNamed(String account, String name, String definition, String type, String role) { String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name; cleanup.register(() -> removeMachine(account, arn)); Response created = request(account, "CreateStateMachine", Map.of(