From bd65477927d17bd144eff1a224f87d4f0e8167ca Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 5 Nov 2026 09:50:01 -0600 Subject: [PATCH] feat(stepfunctions): evaluate the execution role on SQS tasks (#7574) * feat(stepfunctions): evaluate the execution role on SQS tasks Under IAM enforcement an SQS task now requires the execution role to exist and trust Step Functions, assumes the role its Credentials name, and checks sqs:SendMessage on the queue as the role it ends up with. LambdaTaskAuthorizer gains a general authorize() that later integrations map onto through TaskPermissions; it reads any service's resource policy and accepts resource * and an S3 ARN's empty account. Lambda, API Gateway and nested tasks keep their own paths and errors. TaskScheduled and LambdaFunctionScheduled record taskCredentials when a task declares Credentials. With enforcement off they are read softly, so a RoleArn that does not resolve is omitted and the task still runs. Signed-off-by: Hector Ventura * fix(stepfunctions): let a queue's policy decide SQS task and direct calls SQS had no resource policy provider, so a task's call to a queue in another account could never be granted. Add one reading the queue's Policy attribute, which IAM enforcement and the task authorizer both read, and build a direct request's ARN from the account its QueueUrl names so the right queue's policy is read. Credentials read only for history now tolerate only a resolution failure, and the Step Functions integration tests share one client. Signed-off-by: Hector Ventura --------- Signed-off-by: Hector Ventura --- docs/services/sqs.md | 8 + docs/services/step-functions.md | 44 +- .../services/iam/ResourceArnBuilder.java | 4 +- .../sqs/SqsResourcePolicyProvider.java | 41 ++ .../floci/services/sqs/SqsService.java | 25 + .../services/stepfunctions/AslExecutor.java | 59 ++- .../stepfunctions/LambdaTaskAuthorizer.java | 95 +++- .../stepfunctions/NestedTaskCredentials.java | 14 +- .../stepfunctions/TaskPermissions.java | 41 ++ .../services/iam/ResourceArnBuilderTest.java | 6 + ...QueuePolicyEnforcementIntegrationTest.java | 127 +++++ .../sqs/SqsResourcePolicyProviderTest.java | 50 ++ .../ApiGatewayTaskInvokerTest.java | 7 +- .../AslExecutorTaskHistoryEventsTest.java | 103 ++++ .../LambdaTaskAuthorizerTest.java | 188 ++++++- ...FunctionsNestedTaskIamIntegrationTest.java | 48 +- ...tepFunctionsSqsTaskIamIntegrationTest.java | 461 ++++++++++++++++++ ...nctionsTaskCredentialsIntegrationTest.java | 93 ++-- .../stepfunctions/TaskPermissionsTest.java | 79 +++ .../floci/testing/SqsTestQueue.java | 11 + .../testing/StepFunctionsTestClient.java | 93 ++++ 21 files changed, 1489 insertions(+), 108 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/sqs/SqsResourcePolicyProvider.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissions.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/sqs/SqsQueuePolicyEnforcementIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/sqs/SqsResourcePolicyProviderTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissionsTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/testing/StepFunctionsTestClient.java diff --git a/docs/services/sqs.md b/docs/services/sqs.md index e4e85b5241..99485c01a3 100644 --- a/docs/services/sqs.md +++ b/docs/services/sqs.md @@ -212,6 +212,14 @@ The region is the one the request was signed for, and the host carries that regi Under either setting every form is accepted as input. That covers the AWS URL, the Floci URL, any other host whose path ends in `//`, and the bare queue name. A queue is stored by account and name, so a base URL with a path of its own, such as `http://localhost:4566/sqs`, keeps the same queues under either setting. Existing queues, persisted ones included, are reported in the form the current setting and base URL give. +## Queue policies under IAM enforcement + +With `floci.services.iam.enforcement-enabled` on, a queue's `Policy` attribute, written by +`SetQueueAttributes` or `AddPermission`, takes part in the decision as IAM's policy evaluation logic +describes. Within one account either the policy or the caller's identity policies can allow a call, +and an explicit `Deny` in either refuses it. A `QueueUrl` whose path names another account is a +cross-account call: the queue's policy and the caller's identity policies both have to allow it. + ## Storage write failures When the message backend reports a failed write, the queue retains its previously acknowledged diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 9d66b2ad9d..1a325e48ce 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -90,7 +90,9 @@ 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. Other integrations retain their existing credential handling. +are not evaluated. Lambda, API Gateway and SQS tasks evaluate `Credentials` themselves +([Lambda](#lambda-tasks-under-iam-enforcement), [SQS](#sqs-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 @@ -564,6 +566,43 @@ function as `RoleArn.$`, or through JSONata. A role the execution role cannot as with `States.Permissions`, whose cause names the execution role's session and `sts:AssumeRole` on the role. +## SQS tasks under IAM enforcement + +`arn:aws:states:::sqs:sendMessage`, `arn:aws:states:::aws-sdk:sqs:sendMessage` and their +`.waitForTaskToken` forms are evaluated with [IAM enforcement](iam.md#resource-based-policies) on, +each attempt in turn, so `Retry` and `Catch` see a refusal like any other task failure: + +1. The execution role has to exist and to trust `states.amazonaws.com`, or the task fails with + `States.Permissions`. +2. If the task's `Credentials` name a role, the execution role has to be able to assume it, as for a + [Lambda task](#lambda-tasks-under-iam-enforcement). A role it cannot assume, or one that does not + exist, fails the task with `States.TaskFailed` and the cause "The role X is not authorized to + assume the task state's role, Y.", the form AWS answers a nested execution with. `Credentials` + that do not resolve to an object holding only `RoleArn` fail with `States.Runtime`. +3. The role the task ends up with has to be allowed `sqs:SendMessage` on the queue `QueueUrl` names, + or the task fails with `SQS.AccessDeniedException` (`Sqs.AccessDeniedException` for the + `aws-sdk` form), whose cause names the role's session and the kind of policy that refused it. The + queue is the one Floci's lookup reaches: the account and name in the URL's path, in the state + machine's Region. A request with no `QueueUrl` gets SQS's own error once the role has passed. + +The error names `States.Permissions` and `.AccessDeniedException` are Floci's reading: they +have not been verified against AWS. Only global condition keys are available to the policies. The +queue's own policy (`SetQueueAttributes` or `AddPermission`) takes part as it does for a direct SQS +request: within one account it or the role's policies can allow the send, and across accounts both +have to. A role in another account, named by `Credentials`, is authorized as that role but the task +still runs in the state machine's account. Nested executions are the only tasks that run in the +role's account. With enforcement off nothing here is evaluated. + +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. + +## Task credentials in history + +A task that declares `Credentials` records the resolved role in the `taskCredentials.roleArn` of its +`TaskScheduled` or `LambdaFunctionScheduled` event, with enforcement on or off. With enforcement off, +`Credentials` that do not resolve are left out of the event and the task runs as if they were not +there. `ActivityScheduled` has no such member, as in the AWS model. + ## AWS SDK task integrations A resource of the form `arn:aws:states:::aws-sdk::` calls the service's API and @@ -615,7 +654,8 @@ ECS `listServices` supports the same `MaxResults` and opaque `NextToken` as the 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. Name-based lookups use the +state-machine execution role's per-action IAM policies; among the task integrations, Lambda, API +Gateway, nested executions and [SQS](#sqs-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/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java index b5ceb68821..df67862c72 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java @@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.lambda.durable.DurableTokens; import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService; import io.github.hectorvent.floci.services.s3.S3ControlArnUtils; import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService; +import io.github.hectorvent.floci.services.sqs.SqsService; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; @@ -1550,8 +1551,7 @@ public class ResourceArnBuilder { } } if (queueUrl != null && !queueUrl.isEmpty()) { - String queueName = queueUrl.substring(queueUrl.lastIndexOf('/') + 1); - return AwsArnUtils.Arn.of("sqs", region, accountId, queueName).toString(); + return SqsService.queueArn(queueUrl, AwsRegions.partitionFor(region), region, accountId); } return AwsArnUtils.Arn.of("sqs", region, accountId, "*").toString(); } diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsResourcePolicyProvider.java new file mode 100644 index 0000000000..7298f73d99 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsResourcePolicyProvider.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.sqs; + +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.regex.Pattern; + +/** + * Supplies SQS queue policies to IAM policy evaluation, together with the account that owns the + * queue: the one in its ARN, also when the queue does not exist or has no policy, so a call to + * another account's queue is judged as cross-account. + */ +@ApplicationScoped +public class SqsResourcePolicyProvider implements ResourcePolicyProvider { + + private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}"); + + private final SqsService sqsService; + + @Inject + public SqsResourcePolicyProvider(SqsService sqsService) { + this.sqsService = sqsService; + } + + @Override + public List getResourcePolicies(String credentialScope, String resourceArn) { + if (!AwsArnUtils.isArnFor(resourceArn, "sqs")) { + return List.of(); + } + AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn); + // ListQueues and a request with no QueueUrl name every queue, which is not one queue's call. + if (!ACCOUNT_ID.matcher(arn.accountId()).matches() || arn.region().isBlank() + || arn.resource().isBlank() || arn.resource().contains("*")) { + return List.of(); + } + return List.of(new ResourcePolicy(sqsService.findQueuePolicy(resourceArn).orElse(null), arn.accountId())); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java index 3fb30ebe27..85b5d8c7e3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/sqs/SqsService.java @@ -2241,6 +2241,31 @@ public class SqsService implements Resettable, ResourceProvider { return baseUrl + "/" + regionResolver.getAccountId() + "/" + queueUrl; } + /** + * The ARN of the queue {@code queueUrl} reaches from {@code region}, read as the lookups read it: + * the path names the account and the queue, the host does not count, and a value that names no + * account is in {@code defaultAccount}. + */ + public static String queueArn(String queueUrl, String partition, String region, String defaultAccount) { + String url = queueUrl.contains("://") ? queueUrl : "sqs://queue/" + defaultAccount + "/" + queueUrl; + String path = extractQueuePath(url); + String account = accountFromQueueUrl(url); + return new AwsArnUtils.Arn(partition, "sqs", region, account != null ? account : defaultAccount, + path.substring(path.lastIndexOf('/') + 1)).toString(); + } + + /** + * The {@code Policy} attribute of the queue {@code queueArn} names, read from its account and + * Region whichever account the caller is in. Empty when the queue does not exist or has no policy. + */ + public Optional findQueuePolicy(String queueArn) { + AwsArnUtils.Arn arn = AwsArnUtils.parse(queueArn); + String queueUrl = "sqs://queue/" + arn.accountId() + "/" + arn.resource(); + return getQueueByUrl(regionKey(arn.region(), queueUrl), queueUrl) + .map(queue -> queue.getAttributes().get("Policy")) + .filter(policy -> !policy.isBlank()); + } + private String regionKey(String region, String queueUrl) { return region + "::" + extractQueuePath(normalizeQueueUrl(queueUrl)); } diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index 122c5da2a0..d64c2a669c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -982,6 +982,9 @@ public class AslExecutor { JsonNode credentials = null; boolean readCredentials = stateDef.has("Credentials") && (iamEnforcementEnabled() || (mockedInvocation == null && nestedTask)); + // Otherwise only the scheduled event reads them, and what it cannot read it leaves out. + boolean recordCredentialsOnly = stateDef.has("Credentials") && !readCredentials && !isActivity; + JsonNode recordedCredentials = null; if (jsonata) { effectiveInput = input; if (stateDef.has("Arguments")) { @@ -992,17 +995,26 @@ public class AslExecutor { if (readCredentials) { credentials = jsonataEvaluator.resolveTemplate(stateDef.get("Credentials"), "Credentials", buildStatesVar(input, null, context), variables); + } else if (recordCredentialsOnly) { + recordedCredentials = credentialsOrNull(stateName, + () -> jsonataEvaluator.resolveTemplate(stateDef.get("Credentials"), "Credentials", + buildStatesVar(input, null, context), variables)); } } else { effectiveInput = applyInputPath(stateDef, input, context); if (readCredentials) { credentials = resolveParameters(stateDef.get("Credentials"), effectiveInput, context); + } else if (recordCredentialsOnly) { + JsonNode credentialsInput = effectiveInput; + recordedCredentials = credentialsOrNull(stateName, + () -> resolveParameters(stateDef.get("Credentials"), credentialsInput, context)); } if (stateDef.has("Parameters")) { effectiveInput = resolveParameters(stateDef.get("Parameters"), effectiveInput, context); } } - String credentialsRoleArn = credentials == null ? null : credentials.path("RoleArn").asText(null); + JsonNode taskCredentials = credentials; + JsonNode scheduledCredentials = credentials != null ? credentials : recordedCredentials; // Registered after the input template resolved, so a template failure leaves no token behind. CompletableFuture tokenFuture = needsToken ? sfnService.get().registerPendingToken(taskToken, @@ -1014,7 +1026,7 @@ public class AslExecutor { // does not extend the Task's own TimeoutSeconds. long taskDeadlineNanos = taskDeadlineNanos(stateDef); try { - addTaskScheduledEvent(chain, profile, stateDef, effectiveInput, sm); + addTaskScheduledEvent(chain, profile, stateDef, effectiveInput, sm, scheduledCredentials); addTaskStartedEvent(chain, profile); try { String taskAccount = null; @@ -1032,7 +1044,7 @@ public class AslExecutor { effectiveResource, resourceInput, sm, resourceToken, context.path("Execution").path("Id").asText(null), executionDeadlineNanos, taskDeadlineNanos, - jsonata ? null : stateDef.path("Parameters"), credentialsRoleArn, + jsonata ? null : stateDef.path("Parameters"), taskCredentials, jobResponse -> RequestScopes.runAs( AwsArnUtils.parse(sm.getStateMachineArn()).accountId(), () -> addTaskSubmittedEvent(chain, profile, jobResponse)))); @@ -1092,6 +1104,17 @@ public class AslExecutor { } } + /** A task's {@code Credentials} when only the history reads them, so a failure is not the task's. */ + private JsonNode credentialsOrNull(String stateName, Callable resolve) throws Exception { + try { + return resolve.call(); + } catch (FailStateException e) { + LOG.debugv("Task state {0}: Credentials did not resolve, so its history omits them: {1}", + stateName, e.getMessage()); + return null; + } + } + private MockedTaskInvocation findMockedInvocation(JsonNode context, String stateName) { if (activeMocks.isEmpty()) { return null; @@ -1233,6 +1256,19 @@ public class AslExecutor { return colon >= 0 ? fn.substring(colon + 1) : null; } + /** 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); + if (required.isEmpty()) { + return; + } + if (credentials != null) { + NestedTaskCredentials.validateShape(credentials); + } + lambdaTaskAuthorizer.authorize(sm, credentials == null ? null : credentials.path("RoleArn").asText(), + required.get().errorPrefix(), required.get().permissions()); + } + private boolean iamEnforcementEnabled() { return config != null && config.services() != null && config.services().iam() != null && config.services().iam().enforcementEnabled(); @@ -1293,15 +1329,16 @@ public class AslExecutor { } /** - * @param credentialsRoleArn the role the task's {@code Credentials} name, read only under IAM - * enforcement, or null when the task runs as the execution role + * @param credentials the task's resolved {@code Credentials}, read only under IAM enforcement or + * for a nested execution, or null when the task runs as the execution role * @param jobSubmitted called with the response of the call that started a {@code .sync} job, * once it has returned and before the job is waited on */ private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken, String executionArn, long executionDeadlineNanos, long taskDeadlineNanos, - JsonNode rawParameters, String credentialsRoleArn, + JsonNode rawParameters, JsonNode credentials, Consumer jobSubmitted) throws Exception { + String credentialsRoleArn = credentials == null ? null : credentials.path("RoleArn").asText(null); // Support Lambda resources: direct ARN or optimized integration String functionName = null; String functionRef = null; @@ -1415,6 +1452,10 @@ public class AslExecutor { return invokeNonIntegrationResource(resource, input, taskToken); } + if (iamEnforcementEnabled()) { + authorizeTask(integration, input, sm, credentials); + } + if (integration.is("apigateway", "invoke") && integration.suffix().isEmpty()) { try { return apiGatewayTaskInvoker.invoke(input, sm, credentialsRoleArn); @@ -6125,7 +6166,7 @@ public class AslExecutor { } private void addTaskScheduledEvent(HistoryChain chain, TaskEventProfile profile, JsonNode stateDef, - JsonNode effectiveInput, StateMachine sm) { + JsonNode effectiveInput, StateMachine sm, JsonNode credentials) { LinkedHashMap details = new LinkedHashMap<>(); if (profile.resourceType() != null) { details.put("resourceType", profile.resourceType()); @@ -6144,6 +6185,10 @@ public class AslExecutor { if (stateDef.path("HeartbeatSeconds").isNumber()) { details.put("heartbeatInSeconds", stateDef.path("HeartbeatSeconds").asLong()); } + // ActivityScheduledEventDetails has no taskCredentials member. + if (credentials != null && credentials.path("RoleArn").isTextual() && !"Activity".equals(profile.prefix())) { + details.put("taskCredentials", Map.of("roleArn", credentials.path("RoleArn").asText())); + } chain.publish(profile.prefix() + "Scheduled", details); } diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java index d937057dd6..beb6bce10b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.stepfunctions; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.IamConditionContextResolver; +import io.github.hectorvent.floci.core.common.ServicePrincipals; import io.github.hectorvent.floci.services.iam.AccessDeniedMessages; import io.github.hectorvent.floci.services.iam.AccessDeniedMessages.PolicyType; import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator; @@ -14,16 +15,19 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.SimulationDeci import io.github.hectorvent.floci.services.iam.IamService; import io.github.hectorvent.floci.services.iam.IamService.CallerArns; import io.github.hectorvent.floci.services.iam.RequestPrincipal; +import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy; +import io.github.hectorvent.floci.services.iam.ResourcePolicyProviders; import io.github.hectorvent.floci.services.iam.ScpProvider; import io.github.hectorvent.floci.services.iam.model.CallerContext; import io.github.hectorvent.floci.services.iam.model.IamRole; -import io.github.hectorvent.floci.services.lambda.LambdaResourcePolicyProvider; +import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -37,6 +41,9 @@ import java.util.Optional; * resource's policy can allow a call; across accounts, both have to (IAM User Guide, cross-account * policy evaluation logic). The role's permissions boundary and its account's service control * policies limit it, and an explicit Deny in any of them refuses it. + * + *

{@link #authorize} is the same decision for any other integration's call, ahead of which it + * requires the execution role to exist and to trust Step Functions. */ @ApplicationScoped public class LambdaTaskAuthorizer { @@ -44,24 +51,79 @@ public class LambdaTaskAuthorizer { private static final Logger LOG = Logger.getLogger(LambdaTaskAuthorizer.class); private static final String INVOKE = "lambda:InvokeFunction"; private static final String ASSUME_ROLE = "sts:AssumeRole"; + private static final String ANY_RESOURCE = "*"; private final IamService iamService; private final IamPolicyEvaluator evaluator; private final AssumeRolePolicyEvaluator trustEvaluator; - private final LambdaResourcePolicyProvider functionPolicies; + private final Instance resourcePolicies; private final Instance scpProvider; @Inject public LambdaTaskAuthorizer(IamService iamService, IamPolicyEvaluator evaluator, AssumeRolePolicyEvaluator trustEvaluator, - LambdaResourcePolicyProvider functionPolicies, Instance scpProvider) { + Instance resourcePolicies, + Instance scpProvider) { this.iamService = iamService; this.evaluator = evaluator; this.trustEvaluator = trustEvaluator; - this.functionPolicies = functionPolicies; + this.resourcePolicies = resourcePolicies; this.scpProvider = scpProvider; } + /** + * One IAM action a task's call needs. + * + * @param action the IAM action, such as {@code sqs:SendMessage} + * @param resourceArn the resource it acts on, or {@code *} for an action with no resource-level + * permissions. An S3 ARN carries no account: the bucket's owner comes from S3 + * @param conditionKeys the condition keys the integrated service adds to the global ones + */ + public record Permission(String action, String resourceArn, Map> conditionKeys) { + + public Permission(String action, String resourceArn) { + this(action, resourceArn, Map.of()); + } + } + + /** + * Decides a task's call to its integrated service, throwing the failure the task records. The + * execution role has to exist and to trust Step Functions, then to assume the role the task's + * {@code Credentials} name, if any, and the role the task ends up with has to be allowed every + * permission. + * + * @param credentialsRoleArn the role the task's {@code Credentials} resolved to, or null + * @param errorPrefix the integration's error prefix, dot included, such as {@code SQS.} + * @throws AslExecutor.FailStateException {@code States.Permissions} for the execution role, + * {@code States.TaskFailed} for a refused assumption, and + * {@code AccessDeniedException} for a refused permission + */ + void authorize(StateMachine machine, String credentialsRoleArn, String errorPrefix, List permissions) { + AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); + IamRole executionRole = role(machine.getRoleArn()).orElseThrow( + () -> new AslExecutor.FailStateException("States.Permissions", + "The execution role " + machine.getRoleArn() + " does not exist.")); + if (!trustEvaluator.allowsService(executionRole.getAssumeRolePolicyDocument(), ServicePrincipals.of("states"), + machine.getStateMachineArn(), owner.accountId())) { + throw new AslExecutor.FailStateException("States.Permissions", + "The execution role " + machine.getRoleArn() + " does not trust Step Functions."); + } + String effectiveRoleArn = machine.getRoleArn(); + if (credentialsRoleArn != null) { + if (assumeRefusal(machine.getRoleArn(), credentialsRoleArn, machine.getStateMachineArn()).isPresent()) { + throw NestedTaskCredentials.assumptionDenied(machine, credentialsRoleArn); + } + effectiveRoleArn = credentialsRoleArn; + } + for (Permission permission : permissions) { + Optional refusal = refusal(effectiveRoleArn, permission.action(), permission.resourceArn(), + owner.region(), permission.conditionKeys()); + if (refusal.isPresent()) { + throw new AslExecutor.FailStateException(errorPrefix + "AccessDeniedException", refusal.get()); + } + } + } + /** * Returns why {@code roleArn} may not invoke {@code functionArn}, as Lambda's access denied * message words it, or nothing when it may. @@ -74,7 +136,12 @@ public class LambdaTaskAuthorizer { /** Applies the task role's identity policies, boundary and SCPs to the requested action. */ public Optional refusal(String roleArn, String action, String resourceArn) { - AwsArnUtils.Arn resource = AwsArnUtils.parse(resourceArn); + return refusal(roleArn, action, resourceArn, AwsArnUtils.regionOrDefault(resourceArn, null), Map.of()); + } + + private Optional refusal(String roleArn, String action, String resourceArn, String requestedRegion, + Map> conditionKeys) { + AwsArnUtils.Arn resource = ANY_RESOURCE.equals(resourceArn) ? null : AwsArnUtils.parse(resourceArn); Optional invokingRole = role(roleArn); if (invokingRole.isEmpty()) { LOG.infov("Role {0} names no existing role, so it cannot invoke {1}", roleArn, resourceArn); @@ -86,16 +153,18 @@ public class LambdaTaskAuthorizer { AwsArnUtils.Arn roleId = AwsArnUtils.parse(invokingRoleArn); List> scpLevels = scpLevels(roleId.accountId()); - List policies = "lambda".equals(resource.service()) - ? functionPolicies.getResourcePolicies("lambda", resourceArn) : List.of(); - String ownerAccount = policies.isEmpty() ? resource.accountId() : policies.getFirst().ownerAccountId(); + List policies = resource == null ? List.of() + : ResourcePolicyProviders.policiesFor(resourcePolicies, resource.service(), action, resourceArn); + String ownerAccount = policies.isEmpty() + ? (resource == null ? null : resource.accountId()) : policies.getFirst().ownerAccountId(); List documents = policies.stream() .map(ResourcePolicy::policyDocument) .filter(document -> document != null && !document.isBlank()) .toList(); + Map> serviceContext = new LinkedHashMap<>(conditionKeys); + serviceContext.put("aws:PrincipalArn", List.of(invokingRoleArn)); Map> context = IamConditionContextResolver.withGlobalContext( - Map.of("aws:PrincipalArn", List.of(invokingRoleArn)), resourceArn, resource.region(), - roleId.accountId(), ownerAccount); + serviceContext, resourceArn, requestedRegion, roleId.accountId(), ownerAccount); RequestPrincipal session = RequestPrincipal.roleSession(sessionArn(invokingRoleArn), invokingRoleArn); ResourcePolicyDecision functionPolicy = evaluator.evaluateResourcePolicyFor( @@ -191,8 +260,12 @@ public class LambdaTaskAuthorizer { return scpProvider.isResolvable() ? scpProvider.get().effectiveScpLevels(accountId) : null; } + /** + * A resource whose account is unknown, an action on {@code *} or an S3 ARN of a bucket S3 does + * not hold, is judged within the caller's account: nothing says it belongs to another. + */ private static ResourceAccountRelationship relationship(String callerAccount, String resourceAccount) { - return callerAccount.equals(resourceAccount) + return resourceAccount == null || resourceAccount.isBlank() || callerAccount.equals(resourceAccount) ? ResourceAccountRelationship.SAME_ACCOUNT : ResourceAccountRelationship.CROSS_ACCOUNT; } diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentials.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentials.java index b2e706e556..1ffa958348 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentials.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/NestedTaskCredentials.java @@ -30,10 +30,7 @@ public class NestedTaskCredentials { throw new AslExecutor.FailStateException("States.Runtime", "Task Credentials account routing is supported only for nested executions"); } - if (!credentials.isObject() || credentials.size() != 1 || !credentials.path("RoleArn").isTextual()) { - throw new AslExecutor.FailStateException("States.Runtime", - "Task Credentials must resolve to an object containing RoleArn"); - } + validateShape(credentials); String roleArn = credentials.path("RoleArn").asText(); AwsArnUtils.Arn role; try { @@ -70,7 +67,14 @@ public class NestedTaskCredentials { return role.accountId(); } - private static AslExecutor.FailStateException assumptionDenied(StateMachine machine, String roleArn) { + static void validateShape(JsonNode credentials) { + if (!credentials.isObject() || credentials.size() != 1 || !credentials.path("RoleArn").isTextual()) { + throw new AslExecutor.FailStateException("States.Runtime", + "Task Credentials must resolve to an object containing RoleArn"); + } + } + + static AslExecutor.FailStateException assumptionDenied(StateMachine machine, String roleArn) { return new AslExecutor.FailStateException("States.TaskFailed", "The role " + machine.getRoleArn() + " is not authorized to assume the task state's role, " + roleArn + "."); diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissions.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissions.java new file mode 100644 index 0000000000..0b47b4c2e6 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissions.java @@ -0,0 +1,41 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.services.sqs.SqsService; +import io.github.hectorvent.floci.services.stepfunctions.LambdaTaskAuthorizer.Permission; +import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine; + +import java.util.List; +import java.util.Optional; + +/** + * What a task's call to its integrated service needs from IAM. A request that names no resource + * needs no permission here: the integrated service refuses it with its own validation error. + * + * @param errorPrefix the integration's error prefix, dot included + * @param permissions the actions the call performs + */ +record TaskPermissions(String errorPrefix, List permissions) { + + /** The permissions of a mapped integration, or nothing for one that is not checked. */ + static Optional of(StatesIntegration integration, JsonNode input, StateMachine machine) { + if (integration.is("sqs", "sendMessage")) { + return Optional.of(sqsSendMessage("SQS.", input, machine)); + } + if (integration.isSdk("sqs", "sendMessage")) { + return Optional.of(sqsSendMessage("Sqs.", input, machine)); + } + return Optional.empty(); + } + + private static TaskPermissions sqsSendMessage(String errorPrefix, JsonNode input, StateMachine machine) { + JsonNode queueUrl = input.path("QueueUrl"); + if (!queueUrl.isTextual() || queueUrl.asText().isBlank()) { + return new TaskPermissions(errorPrefix, List.of()); + } + AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn()); + return new TaskPermissions(errorPrefix, List.of(new Permission("sqs:SendMessage", + SqsService.queueArn(queueUrl.asText(), owner.partition(), owner.region(), owner.accountId())))); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java index 8d3b2fafd8..3703336f4f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java @@ -1579,6 +1579,12 @@ class ResourceArnBuilderTest { // ── SQS ───────────────────────────────────────────────────────────────────── + @Test + void sqsNamesTheAccountTheQueueUrlNames() { + queryParams.putSingle("QueueUrl", "http://localhost:4566/111122223333/orders"); + assertEquals("arn:aws:sqs:us-east-1:111122223333:orders", builder.build("sqs", ctx, "us-east-1", "000000000000")); + } + @Test void sqsBuildsArnFromJsonQueueName() { setJsonBody("{\"QueueName\":\"order-queue\"}"); diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsQueuePolicyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsQueuePolicyEnforcementIntegrationTest.java new file mode 100644 index 0000000000..d26d4e4005 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsQueuePolicyEnforcementIntegrationTest.java @@ -0,0 +1,127 @@ +package io.github.hectorvent.floci.services.sqs; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testing.SqsTestQueue; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ValidatableResponse; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class SqsQueuePolicyEnforcementIntegrationTest { + private static final String OWNER = "000000000451"; + private static final String OTHER = "000000000452"; + private static final String REGION = "us-east-1"; + private static final String SEND = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sqs:SendMessage","Resource":"*"}]} + """; + private static final String READ_ONLY = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sqs:GetQueueUrl","Resource":"*"}]} + """; + + @TestHTTPResource + URI baseUri; + + @Inject + SqsService sqsService; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @Test + void anotherAccountNeedsTheQueueToGrantIt() { + SqsTestQueue queue = queue(); + String accessKey = user(OTHER, SEND); + + send(accessKey, queue).statusCode(403); + + queue.addPermission("from-other", OTHER, "SendMessage"); + send(accessKey, queue).statusCode(200); + assertEquals("hello", queue.receive().getFirst().getBody()); + } + + @Test + void aQueueGrantDoesNotReplaceTheOtherAccountsOwnPolicy() { + SqsTestQueue queue = queue(); + queue.addPermission("from-other", OTHER, "SendMessage"); + + send(user(OTHER, READ_ONLY), queue).statusCode(403); + } + + @Test + void aQueuePolicyAloneAllowsAUserOfItsOwnAccount() { + SqsTestQueue queue = queue(); + String name = "sqs-policy-" + UUID.randomUUID(); + String accessKey = user(OWNER, name, READ_ONLY); + + send(accessKey, queue).statusCode(403); + + queue.setPolicy(policy("Allow", "arn:aws:iam::" + OWNER + ":user/" + name, queue.arn())); + send(accessKey, queue).statusCode(200); + } + + @Test + void aQueuePolicyDenyRefusesAUserAllowedTheAction() { + SqsTestQueue queue = queue(); + String name = "sqs-policy-" + UUID.randomUUID(); + String accessKey = user(OWNER, name, SEND); + + send(accessKey, queue).statusCode(200); + + queue.setPolicy(policy("Deny", "arn:aws:iam::" + OWNER + ":user/" + name, queue.arn())); + send(accessKey, queue).statusCode(403); + } + + private static String policy(String effect, String principal, String queueArn) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"%s"}, + "Action":"sqs:SendMessage","Resource":"%s"}]} + """.formatted(effect, principal, queueArn); + } + + private SqsTestQueue queue() { + SqsTestQueue queue = SqsTestQueue.create(sqsService, OWNER, REGION, "sqs-policy-"); + cleanup.register(queue::delete); + return queue; + } + + private String user(String account, String policy) { + return user(account, "sqs-policy-" + UUID.randomUUID(), policy); + } + + private String user(String account, String name, String policy) { + String authorization = auth(account, "iam"); + UserCredentials credentials = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), authorization, name); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), authorization, name, "p", policy); + return credentials.accessKeyId(); + } + + private ValidatableResponse send(String accessKey, SqsTestQueue queue) { + return given().port(baseUri.getPort()).header("Authorization", auth(accessKey, "sqs")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "SendMessage").formParam("Version", "2012-11-05") + .formParam("QueueUrl", queue.url()).formParam("MessageBody", "hello") + .post("/").then(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/sqs/SqsResourcePolicyProviderTest.java b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsResourcePolicyProviderTest.java new file mode 100644 index 0000000000..9726b6004e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/sqs/SqsResourcePolicyProviderTest.java @@ -0,0 +1,50 @@ +package io.github.hectorvent.floci.services.sqs; + +import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class SqsResourcePolicyProviderTest { + + private static final String OWNER = "111122223333"; + private static final String QUEUE = "arn:aws:sqs:us-east-1:" + OWNER + ":orders"; + private static final String POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + + private SqsService sqsService; + private SqsResourcePolicyProvider provider; + + @BeforeEach + void setUp() { + sqsService = mock(SqsService.class); + when(sqsService.findQueuePolicy(anyString())).thenReturn(Optional.empty()); + provider = new SqsResourcePolicyProvider(sqsService); + } + + @Test + void aQueueComesWithItsPolicyAndTheAccountInItsArn() { + when(sqsService.findQueuePolicy(QUEUE)).thenReturn(Optional.of(POLICY)); + + assertEquals(List.of(new ResourcePolicy(POLICY, OWNER)), provider.getResourcePolicies("sqs", QUEUE)); + } + + @Test + void aQueueWithNoPolicyStillHasItsOwner() { + assertEquals(List.of(new ResourcePolicy(null, OWNER)), provider.getResourcePolicies("sqs", QUEUE)); + } + + @Test + void anythingThatIsNotOneQueueIsLeftToOtherProviders() { + assertTrue(provider.getResourcePolicies("sqs", "*").isEmpty()); + assertTrue(provider.getResourcePolicies("sqs", "arn:aws:sqs:us-east-1:" + OWNER + ":*").isEmpty()); + assertTrue(provider.getResourcePolicies("sns", "arn:aws:sns:us-east-1:" + OWNER + ":topic").isEmpty()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ApiGatewayTaskInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ApiGatewayTaskInvokerTest.java index d0009634b5..d3429c470f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ApiGatewayTaskInvokerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/ApiGatewayTaskInvokerTest.java @@ -15,10 +15,10 @@ import io.github.hectorvent.floci.services.apigateway.model.RestApi; import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator; import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator; import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; import io.github.hectorvent.floci.services.iam.ScpProvider; import io.github.hectorvent.floci.services.iam.model.CallerContext; import io.github.hectorvent.floci.services.iam.model.IamRole; -import io.github.hectorvent.floci.services.lambda.LambdaResourcePolicyProvider; import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine; import jakarta.enterprise.inject.Instance; import org.junit.jupiter.api.AfterEach; @@ -84,8 +84,9 @@ class ApiGatewayTaskInvokerTest { void setup() throws Exception { IamPolicyEvaluator policies = new IamPolicyEvaluator(mapper); AssumeRolePolicyEvaluator trust = new AssumeRolePolicyEvaluator(mapper, policies); - LambdaTaskAuthorizer authorizer = new LambdaTaskAuthorizer(iam, policies, trust, - mock(LambdaResourcePolicyProvider.class), scps); + Instance resourcePolicies = mock(Instance.class); + when(resourcePolicies.isUnsatisfied()).thenReturn(true); + LambdaTaskAuthorizer authorizer = new LambdaTaskAuthorizer(iam, policies, trust, resourcePolicies, scps); when(config.services().iam().enforcementEnabled()).thenReturn(true); invoker = new ApiGatewayTaskInvoker(api, iam, trust, authorizer, config, mapper, listener); machine = new StateMachine(); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTaskHistoryEventsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTaskHistoryEventsTest.java index 311f3840ae..73e2bf4d13 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTaskHistoryEventsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorTaskHistoryEventsTest.java @@ -22,6 +22,8 @@ import io.vertx.mutiny.core.Vertx; import jakarta.inject.Inject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -49,6 +51,8 @@ class AslExecutorTaskHistoryEventsTest { private static final String REGION = "us-east-2"; private static final String ACCOUNT = "000000000000"; + private static final String SQS_RESOURCE = "arn:aws:states:::aws-sdk:sqs:sendMessage"; + private static final String TASK_ROLE = "arn:aws:iam::000000000000:role/task-role"; private final ObjectMapper objectMapper = new ObjectMapper(); private LambdaExecutorService lambdaExecutor; @@ -69,8 +73,13 @@ class AslExecutorTaskHistoryEventsTest { } private AslExecutor newExecutor(DynamoDbFacade dynamoDb) { + return newExecutor(dynamoDb, false); + } + + private AslExecutor newExecutor(DynamoDbFacade dynamoDb, boolean enforcing) { EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); when(config.services().stepfunctions().maxWaitSeconds()).thenReturn(30); + when(config.services().iam().enforcementEnabled()).thenReturn(enforcing); return AslExecutorFixture.builder() .lambdaExecutor(lambdaExecutor) @@ -151,6 +160,100 @@ class AslExecutorTaskHistoryEventsTest { assertEquals("hello", parameters.path("MessageBody").asText()); } + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void declaredCredentialsAppearInTaskScheduled(boolean enforcing) throws Exception { + executor = newExecutor(mock(DynamoDbFacade.class), enforcing); + + Map details = scheduledDetails("TaskScheduled", SQS_RESOURCE, + "\"Credentials\": {\"RoleArn\": \"" + TASK_ROLE + "\"},", "{}"); + + assertEquals(Map.of("roleArn", TASK_ROLE), details.get("taskCredentials")); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void credentialsResolvedFromTheInputAppearInTaskScheduled(boolean enforcing) throws Exception { + executor = newExecutor(mock(DynamoDbFacade.class), enforcing); + + Map details = scheduledDetails("TaskScheduled", SQS_RESOURCE, + "\"Credentials\": {\"RoleArn.$\": \"$.role\"},", "{\"role\":\"" + TASK_ROLE + "\"}"); + + assertEquals(Map.of("roleArn", TASK_ROLE), details.get("taskCredentials")); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void declaredCredentialsAppearInLambdaFunctionScheduled(boolean enforcing) throws Exception { + executor = newExecutor(mock(DynamoDbFacade.class), enforcing); + + Map details = scheduledDetails("LambdaFunctionScheduled", lambdaArn("worker"), + "\"Credentials\": {\"RoleArn\": \"" + TASK_ROLE + "\"},", "{}"); + + assertEquals(Map.of("roleArn", TASK_ROLE), details.get("taskCredentials")); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void noCredentialsMeansNoTaskCredentials(boolean enforcing) throws Exception { + executor = newExecutor(mock(DynamoDbFacade.class), enforcing); + + assertFalse(scheduledDetails("TaskScheduled", SQS_RESOURCE, "", "{}").containsKey("taskCredentials")); + } + + /** ActivityScheduledEventDetails has no taskCredentials member, so strict SDKs would not expect one. */ + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void anActivityNeverRecordsTaskCredentials(boolean enforcing) throws Exception { + executor = newExecutor(mock(DynamoDbFacade.class), enforcing); + + assertFalse(scheduledDetails("ActivityScheduled", + "arn:aws:states:%s:%s:activity:work".formatted(REGION, ACCOUNT), + "\"Credentials\": {\"RoleArn\": \"" + TASK_ROLE + "\"},", "{}").containsKey("taskCredentials")); + } + + /** With enforcement off Credentials have no effect on a task, so one that cannot resolve must not fail it. */ + @Test + void credentialsThatDoNotResolveAreOmittedWithEnforcementOff() throws Exception { + assertFalse(scheduledDetails("TaskScheduled", SQS_RESOURCE, + "\"Credentials\": {\"RoleArn.$\": \"$.missing\"},", "{}").containsKey("taskCredentials")); + } + + @Test + void jsonataCredentialsThatDoNotResolveAreOmittedWithEnforcementOff() throws Exception { + ArrayList history = new ArrayList<>(); + Execution execution = run(""" + {"QueryLanguage": "JSONata", "StartAt": "Send", "States": {"Send": {"Type": "Task", + "Resource": "arn:aws:states:::aws-sdk:sqs:sendMessage", + "Credentials": {"RoleArn": "{% $missing.role.$error() %}"}, + "Arguments": {"QueueUrl": "q", "MessageBody": "x"}, "End": true}}} + """, "{}", testCase(Map.of("Send", List.of(returnStep(0, 0, "{}")))), history); + + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + assertFalse(detailsOf(history, "TaskScheduled").containsKey("taskCredentials")); + } + + @Test + void credentialsNamingNoRoleAreOmitted() throws Exception { + assertFalse(scheduledDetails("TaskScheduled", SQS_RESOURCE, + "\"Credentials\": {\"RoleArn\": 42},", "{}").containsKey("taskCredentials")); + } + + private Map scheduledDetails(String eventType, String resource, String credentials, String input) + throws Exception { + ArrayList history = new ArrayList<>(); + Execution execution = run(""" + {"StartAt": "Send", "States": {"Send": {"Type": "Task", "Resource": "%s", %s "End": true}}} + """.formatted(resource, credentials), input, + testCase(Map.of("Send", List.of(returnStep(0, 0, "{}")))), history); + assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause()); + return detailsOf(history, eventType); + } + + private static Map detailsOf(List history, String eventType) { + return history.stream().filter(event -> eventType.equals(event.getType())).findFirst().orElseThrow().getDetails(); + } + @Test void retriedMockEmitsTaskEventsPerAttempt() throws Exception { MockedTestCase mocks = testCase(Map.of("Send", List.of( diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java index 5abde88de3..4188beac2f 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java @@ -4,20 +4,27 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator; import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator; import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy; import io.github.hectorvent.floci.services.iam.ScpProvider; import io.github.hectorvent.floci.services.iam.model.CallerContext; import io.github.hectorvent.floci.services.iam.model.IamRole; import io.github.hectorvent.floci.services.lambda.LambdaResourcePolicyProvider; +import io.github.hectorvent.floci.services.stepfunctions.LambdaTaskAuthorizer.Permission; +import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine; import jakarta.enterprise.inject.Instance; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; +import java.util.Map; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -45,8 +52,20 @@ class LambdaTaskAuthorizerTest { {"Version":"2012-10-17","Statement":[ {"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}"""; + private static final String BUCKET = "arn:aws:s3:::orders"; + private static final String PUT_OBJECTS = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}]}"""; + private static final String STATES_DESCRIBE_ANYTHING = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"states:DescribeRegions","Resource":"*"}]}"""; + private static final String STATES_TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"states.amazonaws.com"}}]}"""; + private IamService iamService; private LambdaResourcePolicyProvider functionPolicies; + private ResourcePolicyProvider bucketPolicies; private Instance scpProvider; private LambdaTaskAuthorizer authorizer; @@ -56,14 +75,19 @@ class LambdaTaskAuthorizerTest { iamService = mock(IamService.class); functionPolicies = mock(LambdaResourcePolicyProvider.class); scpProvider = mock(Instance.class); - when(functionPolicies.getResourcePolicies(anyString(), anyString())) + when(functionPolicies.getResourcePolicies(eq("lambda"), anyString())) .thenReturn(List.of(new ResourcePolicy(null, FUNCTION_ACCOUNT))); when(functionPolicies.getResourcePolicies("lambda", OWN_FUNCTION)) .thenReturn(List.of(new ResourcePolicy(null, SFN_ACCOUNT))); + when(functionPolicies.getResourcePolicies(anyString(), anyString(), anyString())).thenCallRealMethod(); + bucketPolicies = mock(ResourcePolicyProvider.class); + when(bucketPolicies.getResourcePolicies(anyString(), anyString(), anyString())).thenReturn(List.of()); + Instance providers = mock(Instance.class); + when(providers.iterator()).thenAnswer(call -> List.of(functionPolicies, bucketPolicies).iterator()); ObjectMapper mapper = new ObjectMapper(); IamPolicyEvaluator evaluator = new IamPolicyEvaluator(mapper); authorizer = new LambdaTaskAuthorizer(iamService, evaluator, new AssumeRolePolicyEvaluator(mapper, evaluator), - functionPolicies, scpProvider); + providers, scpProvider); } @Test @@ -389,6 +413,166 @@ class LambdaTaskAuthorizerTest { authorizer.assumeRefusal(ROLE, OWN_TASK_ROLE, STATE_MACHINE)); } + @Test + void aPermissionOnAnyResourceNeedsAPolicyOnAnyResource() { + roleWithPolicies(STATES_DESCRIBE_ANYTHING); + executionRole(STATES_TRUST); + + authorizer.authorize(machine(), null, "Ec2.", List.of(new Permission("states:DescribeRegions", "*"))); + } + + @Test + void aPolicyOnOneResourceDoesNotCoverAPermissionOnAnyResource() { + roleWithPolicies(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"states:DescribeRegions","Resource":"%s"}]}""".formatted(BUCKET)); + executionRole(STATES_TRUST); + + AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, + () -> authorizer.authorize(machine(), null, "Ec2.", + List.of(new Permission("states:DescribeRegions", "*")))); + + assertEquals("Ec2.AccessDeniedException", refused.error); + assertEquals("User: " + SESSION + " is not authorized to perform: states:DescribeRegions on resource: * " + + "because no identity-based policy allows the states:DescribeRegions action", refused.cause); + } + + /** An S3 ARN has no account segment: with no owner known, it is not another account's resource. */ + @Test + void anS3ArnWithNoAccountIsNotCrossAccount() { + roleWithPolicies(PUT_OBJECTS); + + assertEquals(Optional.empty(), authorizer.refusal(ROLE, "s3:PutObject", BUCKET)); + } + + @Test + void anS3BucketOfAnotherAccountIsCrossAccount() { + roleWithPolicies(PUT_OBJECTS); + when(bucketPolicies.getResourcePolicies("s3", "s3:PutObject", BUCKET)) + .thenReturn(List.of(new ResourcePolicy(null, FUNCTION_ACCOUNT))); + + assertEquals(Optional.of("User: " + SESSION + " is not authorized to perform: s3:PutObject on resource: " + BUCKET + + " because no resource-based policy allows the s3:PutObject action"), + authorizer.refusal(ROLE, "s3:PutObject", BUCKET)); + } + + @Test + void aResourcePolicyOfAnyServiceCanGrantTheRole() { + roleWithPolicies(READ_OBJECTS); + when(bucketPolicies.getResourcePolicies("s3", "s3:PutObject", BUCKET)) + .thenReturn(List.of(new ResourcePolicy(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"%s"}, + "Action":"s3:PutObject","Resource":"%s"}]}""".formatted(ROLE, BUCKET), SFN_ACCOUNT))); + + assertEquals(Optional.empty(), authorizer.refusal(ROLE, "s3:PutObject", BUCKET)); + } + + @Test + void aResourcePolicyOfAnyServiceCanRefuseTheRole() { + roleWithPolicies(PUT_OBJECTS); + when(bucketPolicies.getResourcePolicies("s3", "s3:PutObject", BUCKET)) + .thenReturn(List.of(new ResourcePolicy(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*", + "Action":"s3:PutObject","Resource":"%s"}]}""".formatted(BUCKET), SFN_ACCOUNT))); + + assertEquals(Optional.of("User: " + SESSION + " is not authorized to perform: s3:PutObject on resource: " + BUCKET + + " with an explicit deny in a resource-based policy"), + authorizer.refusal(ROLE, "s3:PutObject", BUCKET)); + } + + @Test + void aPermissionsConditionKeysReachThePolicy() { + roleWithPolicies(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"states:InvokeHTTPEndpoint", + "Resource":"*","Condition":{"StringEquals":{"states:HTTPEndpoint":"https://example.test"}}}]}"""); + executionRole(STATES_TRUST); + + authorizer.authorize(machine(), null, "States.", List.of(new Permission("states:InvokeHTTPEndpoint", "*", + Map.of("states:HTTPEndpoint", List.of("https://example.test"))))); + AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, + () -> authorizer.authorize(machine(), null, "States.", List.of(new Permission( + "states:InvokeHTTPEndpoint", "*", Map.of("states:HTTPEndpoint", List.of("https://other.test")))))); + assertEquals("States.AccessDeniedException", refused.error); + } + + /** An S3 ARN and {@code *} name no Region, and the task's call still goes to the state machine's. */ + @Test + void theRequestedRegionIsTheStateMachinesWhateverTheResourceNames() { + roleWithPolicies(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:PutObject","Resource":"*", + "Condition":{"StringEquals":{"aws:RequestedRegion":"us-east-1"}}}]}"""); + executionRole(STATES_TRUST); + + authorizer.authorize(machine(), null, "S3.", List.of(new Permission("s3:PutObject", BUCKET))); + } + + @Test + void anExecutionRoleThatDoesNotExistRefusesTheTask() { + AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, + () -> authorizer.authorize(machine(), null, "SQS.", List.of())); + + assertEquals("States.Permissions", refused.error); + assertTrue(refused.cause.contains(ROLE), refused.cause); + } + + @Test + void anExecutionRoleThatDoesNotTrustStepFunctionsRefusesTheTaskWhateverItsPolicies() { + roleWithPolicies(PUT_OBJECTS); + executionRole(trust("{\"Service\":\"lambda.amazonaws.com\"}")); + + AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, + () -> authorizer.authorize(machine(), null, "S3.", List.of(new Permission("s3:PutObject", BUCKET)))); + + assertEquals("States.Permissions", refused.error); + assertTrue(refused.cause.contains(ROLE), refused.cause); + } + + @Test + void everyPermissionIsDecidedAsTheRoleTheCredentialsName() { + roleWithPolicies(ASSUME_ANY_ROLE); + executionRole(STATES_TRUST); + taskRole(OWN_TASK_ROLE, trust("{\"AWS\":\"" + ROLE + "\"}")); + when(iamService.resolvePrincipalContext(ROLE)).thenReturn(CallerContext.of(List.of(ASSUME_ANY_ROLE))); + when(iamService.resolvePrincipalContext(OWN_TASK_ROLE)).thenReturn(CallerContext.of(List.of(PUT_OBJECTS))); + + authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of(new Permission("s3:PutObject", BUCKET))); + AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, + () -> authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of( + new Permission("s3:PutObject", BUCKET), new Permission("s3:GetObject", BUCKET)))); + + assertEquals("S3.AccessDeniedException", refused.error); + assertTrue(refused.cause.contains("assumed-role/LambdaRole"), refused.cause); + assertTrue(refused.cause.contains("s3:GetObject"), refused.cause); + } + + @Test + void aRoleTheExecutionRoleCannotAssumeFailsTheTaskInTheNestedForm() { + roleWithPolicies(PUT_OBJECTS); + executionRole(STATES_TRUST); + taskRole(OWN_TASK_ROLE, trust("{\"Service\":\"lambda.amazonaws.com\"}")); + + AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, + () -> authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of())); + + assertEquals("States.TaskFailed", refused.error); + assertEquals("The role " + ROLE + " is not authorized to assume the task state's role, " + OWN_TASK_ROLE + ".", + refused.cause); + } + + private void executionRole(String trustPolicy) { + IamRole role = new IamRole(); + role.setArn(ROLE); + role.setAssumeRolePolicyDocument(trustPolicy); + when(iamService.findRole(SFN_ACCOUNT, "sfn-exec")).thenReturn(Optional.of(role)); + } + + private static StateMachine machine() { + StateMachine machine = new StateMachine(); + machine.setStateMachineArn(STATE_MACHINE); + machine.setRoleArn(ROLE); + return machine; + } + private static Optional denied(String functionArn, String reason) { return Optional.of("User: " + SESSION + " is not authorized to perform: lambda:InvokeFunction on resource: " + functionArn + " " + reason); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedTaskIamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedTaskIamIntegrationTest.java index 23a43cecb5..90339caacd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedTaskIamIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsNestedTaskIamIntegrationTest.java @@ -6,6 +6,7 @@ import io.github.hectorvent.floci.testing.EnforcementFixtures; import io.github.hectorvent.floci.testing.IamEnforcementProfile; import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testing.StepFunctionsTestClient; import io.quarkus.test.common.http.TestHTTPResource; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.TestProfile; @@ -20,14 +21,10 @@ import org.junit.jupiter.params.provider.ValueSource; import java.net.URI; import java.util.Map; import java.util.UUID; -import java.util.concurrent.TimeUnit; -import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; -import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertEquals; 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.eq; import static org.mockito.Mockito.clearInvocations; @@ -166,50 +163,23 @@ class StepFunctionsNestedTaskIamIntegrationTest { } private String machine(String account, String definition, String type, String role) { - String name = "nested-iam-" + UUID.randomUUID(); - String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name; - cleanup.register(() -> { - Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn)); - if (executions.statusCode() == 200) { - for (Map execution : executions.jsonPath().>getList("executions")) { - if ("RUNNING".equals(execution.get("status"))) { - request(account, "StopExecution", Map.of("executionArn", execution.get("executionArn"))) - .then().statusCode(200); - } - } - } - request(account, "DeleteStateMachine", Map.of("stateMachineArn", arn)).then().statusCode(200); - }); - Response created = request(account, "CreateStateMachine", Map.of( - "name", name, "definition", definition, "type", type, "roleArn", role)); - created.then().statusCode(200); - return created.jsonPath().getString("stateMachineArn"); + return sfn().createMachine(account, "nested-iam-", definition, type, role); } private String start(String machine) { - Response started = request(SOURCE, "StartExecution", Map.of("stateMachineArn", machine, "input", "{}")); - started.then().statusCode(200); - return started.jsonPath().getString("executionArn"); + return sfn().start(SOURCE, machine, "{}"); } private Response terminal(String execution) throws Exception { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - do { - Response response = request(SOURCE, "DescribeExecution", Map.of("executionArn", execution)); - response.then().statusCode(200); - if (!"RUNNING".equals(response.jsonPath().getString("status"))) { - return response; - } - Thread.sleep(25); - } while (System.nanoTime() < deadline); - fail("Execution did not terminate: " + execution); - return null; + return sfn().terminal(SOURCE, execution, 5); } private Response request(String account, String action, Map input) { - return given().port(baseUri.getPort()).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 sfn().request(account, action, input); + } + + private StepFunctionsTestClient sfn() { + return new StepFunctionsTestClient(baseUri.getPort(), cleanup); } private record Fixture(String parent, String child, String executionRole, String taskRole) { diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java new file mode 100644 index 0000000000..ba9213678c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java @@ -0,0 +1,461 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.sqs.SqsService; +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testing.SqsTestQueue; +import io.github.hectorvent.floci.testing.StepFunctionsTestClient; +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 jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +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.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URI; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class StepFunctionsSqsTaskIamIntegrationTest { + private static final String ACCOUNT = "000000000441"; + private static final String OTHER_ACCOUNT = "000000000442"; + private static final String REGION = "us-east-1"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String STATES_TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"states.amazonaws.com"}}]} + """; + private static final String LAMBDA_TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"lambda.amazonaws.com"}}]} + """; + private static final String SEND = allow("sqs:SendMessage"); + private static final String READ_ONLY = allow("sqs:GetQueueUrl"); + private static final String ASSUME = allow("sts:AssumeRole"); + + @TestHTTPResource + URI baseUri; + + @Inject + SqsService sqsService; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"}) + void anExecutionRoleAllowedTheActionSends(String integration) throws Exception { + SqsTestQueue queue = queue(); + String machine = machine(jsonPathTask(integration, queue, null), role(STATES_TRUST, SEND)); + + Response completed = terminal(start(machine, "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals("hello", queue.receive().getFirst().getBody()); + } + + @ParameterizedTest + @CsvSource({"sqs:sendMessage,SQS.AccessDeniedException", "aws-sdk:sqs:sendMessage,Sqs.AccessDeniedException"}) + void anExecutionRoleNotAllowedTheActionIsRefused(String integration, String error) throws Exception { + SqsTestQueue queue = queue(); + String machine = machine(jsonPathTask(integration, queue, null), role(STATES_TRUST, READ_ONLY)); + + Response completed = terminal(start(machine, "{}")); + + assertFailed(completed, error); + String cause = completed.jsonPath().getString("cause"); + assertTrue(cause.contains("sqs:SendMessage"), cause); + assertTrue(cause.contains(queue.arn()), cause); + assertEquals(0, queue.receive().size()); + } + + @ParameterizedTest + @ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"}) + void anExecutionRoleThatDoesNotTrustStepFunctionsIsRefusedWhateverItsPolicies(String integration) throws Exception { + SqsTestQueue queue = queue(); + String role = role(LAMBDA_TRUST, SEND); + Response completed = terminal(start(machine(jsonPathTask(integration, queue, null), role), "{}")); + + assertFailed(completed, "States.Permissions"); + assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString()); + assertEquals(0, queue.receive().size()); + } + + @ParameterizedTest + @ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"}) + void anExecutionRoleThatDoesNotExistIsRefused(String integration) throws Exception { + SqsTestQueue queue = queue(); + String role = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID(); + Response completed = terminal(start(machine(jsonPathTask(integration, queue, null), role), "{}")); + + assertFailed(completed, "States.Permissions"); + assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString()); + assertEquals(0, queue.receive().size()); + } + + @ParameterizedTest + @CsvSource({"sqs:sendMessage,jsonpath", "aws-sdk:sqs:sendMessage,jsonpath", "sqs:sendMessage,jsonpath-path", + "sqs:sendMessage,jsonata", "aws-sdk:sqs:sendMessage,jsonata"}) + void credentialsSendAsTheirRoleWithoutTheExecutionRolesPermission(String integration, String form) throws Exception { + SqsTestQueue queue = queue(); + String executionRole = role(STATES_TRUST, ASSUME); + String taskRole = role(trusting(executionRole), SEND); + String machine = machine(task(integration, queue, form, taskRole), executionRole); + + String execution = start(machine, MAPPER.writeValueAsString(Map.of("role", taskRole))); + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals("hello", queue.receive().getFirst().getBody()); + JsonNode scheduled = eventsOfType(execution, "TaskScheduled").getFirst(); + assertEquals(taskRole, scheduled.path("taskScheduledEventDetails").path("taskCredentials").path("roleArn").asText()); + } + + @ParameterizedTest + @CsvSource({"sqs:sendMessage,jsonpath", "aws-sdk:sqs:sendMessage,jsonpath", "sqs:sendMessage,jsonata"}) + void aRoleTheExecutionRoleCannotAssumeFailsInTheNestedForm(String integration, String form) throws Exception { + SqsTestQueue queue = queue(); + String executionRole = role(STATES_TRUST, SEND); + String taskRole = role(LAMBDA_TRUST, SEND); + String machine = machine(task(integration, queue, form, taskRole), executionRole); + + Response completed = terminal(start(machine, MAPPER.writeValueAsString(Map.of("role", taskRole)))); + + assertFailed(completed, "States.TaskFailed"); + assertEquals("The role " + executionRole + " is not authorized to assume the task state's role, " + taskRole + ".", + completed.jsonPath().getString("cause")); + assertEquals(0, queue.receive().size()); + } + + @Test + void aCredentialsRoleThatDoesNotExistFailsAsARefusedAssumption() throws Exception { + SqsTestQueue queue = queue(); + String executionRole = role(STATES_TRUST, SEND); + String taskRole = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID(); + String machine = machine(jsonPathTask("sqs:sendMessage", queue, taskRole), executionRole); + + Response completed = terminal(start(machine, "{}")); + + assertFailed(completed, "States.TaskFailed"); + assertEquals(0, queue.receive().size()); + } + + @ParameterizedTest + @CsvSource({"sqs:sendMessage,SQS.AccessDeniedException", "aws-sdk:sqs:sendMessage,Sqs.AccessDeniedException"}) + void aCredentialsRoleNotAllowedTheActionIsRefusedEvenIfTheExecutionRoleIs(String integration, String error) + throws Exception { + SqsTestQueue queue = queue(); + String executionRole = role(STATES_TRUST, allow("sts:AssumeRole", "sqs:SendMessage")); + String taskRole = role(trusting(executionRole), READ_ONLY); + String machine = machine(jsonPathTask(integration, queue, taskRole), executionRole); + + Response completed = terminal(start(machine, "{}")); + + assertFailed(completed, error); + String cause = completed.jsonPath().getString("cause"); + assertTrue(cause.contains("assumed-role/" + taskRole.substring(taskRole.lastIndexOf('/') + 1)), cause); + assertEquals(0, queue.receive().size()); + } + + @Test + void aForeignCredentialsRoleNeedsTheQueueToGrantIt() throws Exception { + SqsTestQueue queue = queue(); + String executionRole = role(STATES_TRUST, ASSUME); + String foreignRole = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), OTHER_ACCOUNT, "/", + "sfn-sqs-" + UUID.randomUUID(), trusting(executionRole), SEND); + String machine = machine(jsonPathTask("sqs:sendMessage", queue, foreignRole), executionRole); + + Response refused = terminal(start(machine, "{}")); + + assertFailed(refused, "SQS.AccessDeniedException"); + String cause = refused.jsonPath().getString("cause"); + assertTrue(cause.contains("arn:aws:sts::" + OTHER_ACCOUNT + ":assumed-role/"), cause); + assertEquals(0, queue.receive().size()); + + queue.setPolicy(queuePolicy("Allow", foreignRole, queue.arn())); + Response completed = terminal(start(machine, "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals("hello", queue.receive().getFirst().getBody()); + } + + @Test + void aQueueInAnotherAccountNeedsItsOwnGrant() throws Exception { + SqsTestQueue queue = SqsTestQueue.create(sqsService, OTHER_ACCOUNT, REGION, "sfn-sqs-iam-"); + cleanup.register(queue::delete); + String role = role(STATES_TRUST, SEND); + String machine = machine(jsonPathTask("sqs:sendMessage", queue, null), role); + + Response refused = terminal(start(machine, "{}")); + + assertFailed(refused, "SQS.AccessDeniedException"); + assertEquals(0, queue.receive().size()); + + queue.addPermission("from-" + ACCOUNT, ACCOUNT, "SendMessage"); + Response completed = terminal(start(machine, "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals("hello", queue.receive().getFirst().getBody()); + } + + @Test + void aQueueInAnotherAccountCannotGrantWhatTheRoleLacks() throws Exception { + SqsTestQueue queue = SqsTestQueue.create(sqsService, OTHER_ACCOUNT, REGION, "sfn-sqs-iam-"); + cleanup.register(queue::delete); + String role = role(STATES_TRUST, READ_ONLY); + queue.setPolicy(queuePolicy("Allow", role, queue.arn())); + + Response completed = terminal(start(machine(jsonPathTask("sqs:sendMessage", queue, null), role), "{}")); + + assertFailed(completed, "SQS.AccessDeniedException"); + assertEquals(0, queue.receive().size()); + } + + @Test + void aQueuePolicyAloneAllowsARoleOfItsOwnAccount() throws Exception { + SqsTestQueue queue = queue(); + String role = role(STATES_TRUST, READ_ONLY); + queue.setPolicy(queuePolicy("Allow", role, queue.arn())); + + Response completed = terminal(start(machine(jsonPathTask("sqs:sendMessage", queue, null), role), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals("hello", queue.receive().getFirst().getBody()); + } + + @Test + void aQueuePolicyDenyRefusesARoleAllowedTheAction() throws Exception { + SqsTestQueue queue = queue(); + String role = role(STATES_TRUST, SEND); + queue.setPolicy(queuePolicy("Deny", role, queue.arn())); + + Response completed = terminal(start(machine(jsonPathTask("sqs:sendMessage", queue, null), role), "{}")); + + assertFailed(completed, "SQS.AccessDeniedException"); + assertEquals(0, queue.receive().size()); + } + + @Test + void credentialsWithoutARoleArnDoNotFallBackToTheExecutionRole() throws Exception { + SqsTestQueue queue = queue(); + String machine = machine(Map.of("Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage", + "Credentials", Map.of("Role", "x"), + "Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true), + role(STATES_TRUST, SEND)); + + Response completed = terminal(start(machine, "{}")); + + assertFailed(completed, "States.Runtime"); + assertEquals("Task Credentials must resolve to an object containing RoleArn", + completed.jsonPath().getString("cause")); + assertEquals(0, queue.receive().size()); + } + + @Test + void waitForTaskTokenRefusedDoesNotWaitAndLeavesNoMessage() throws Exception { + SqsTestQueue queue = queue(); + String machine = machine(Map.of("Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage.waitForTaskToken", + "Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", Map.of("token.$", "$$.Task.Token")), + "TimeoutSeconds", 60, "End", true), role(STATES_TRUST, READ_ONLY)); + + Response completed = terminal(start(machine, "{}")); + + assertFailed(completed, "SQS.AccessDeniedException"); + assertEquals(0, queue.receive().size()); + } + + @Test + void waitForTaskTokenAllowedSendsAndWaits() throws Exception { + SqsTestQueue queue = queue(); + String executionRole = role(STATES_TRUST, ASSUME); + String taskRole = role(trusting(executionRole), SEND); + String machine = machine(Map.of("Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage.waitForTaskToken", + "Credentials", Map.of("RoleArn", taskRole), + "Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", Map.of("token.$", "$$.Task.Token")), + "TimeoutSeconds", 60, "End", true), executionRole); + + String execution = start(machine, "{}"); + String token = queue.awaitJson(Duration.ofSeconds(5)).path("token").asText(); + 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 + @CsvSource({"sqs:sendMessage,SQS.AccessDeniedException", "aws-sdk:sqs:sendMessage,Sqs.AccessDeniedException"}) + void aRefusalCanBeRetriedAndCaught(String integration, String error) throws Exception { + SqsTestQueue queue = queue(); + Map task = new LinkedHashMap<>(jsonPathTask(integration, queue, null)); + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(error), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + task.put("Catch", List.of(Map.of("ErrorEquals", List.of(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(error, eventsOfType(execution, "TaskFailed").getLast() + .path("taskFailedEventDetails").path("error").asText()); + } + + /** The retry decides again, so a role granted the action between attempts then sends. */ + @Test + void aRetryDecidesAgain() throws Exception { + SqsTestQueue queue = queue(); + String roleName = "sfn-sqs-" + UUID.randomUUID(); + String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", roleName, + STATES_TRUST, READ_ONLY); + Map task = new LinkedHashMap<>(jsonPathTask("sqs:sendMessage", queue, null)); + task.put("Retry", List.of(Map.of("ErrorEquals", List.of("SQS.AccessDeniedException"), "IntervalSeconds", 2, + "BackoffRate", 1.0, "MaxAttempts", 3))); + String execution = start(machine(task, role), "{}"); + + await(execution, "TaskFailed"); + given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "iam")) + .formParam("Action", "PutRolePolicy").formParam("Version", "2010-05-08") + .formParam("RoleName", roleName).formParam("PolicyName", "p").formParam("PolicyDocument", SEND) + .post("/").then().statusCode(200); + Response completed = terminal(execution, 20); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals("hello", queue.receive().getFirst().getBody()); + } + + private static String allow(String... actions) { + try { + return MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", List.of( + Map.of("Effect", "Allow", "Action", List.of(actions), "Resource", "*")))); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static String trusting(String role) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"AWS":"%s"}}]} + """.formatted(role); + } + + private static String queuePolicy(String effect, String principal, String queueArn) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"%s"}, + "Action":"sqs:SendMessage","Resource":"%s"}]} + """.formatted(effect, principal, queueArn); + } + + private static void assertFailed(Response completed, String error) { + assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals(error, completed.jsonPath().getString("error"), completed.asString()); + } + + private Map jsonPathTask(String integration, SqsTestQueue queue, String taskRole) { + Map task = new LinkedHashMap<>(Map.of("Type", "Task", + "Resource", "arn:aws:states:::" + integration, + "Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true)); + if (taskRole != null) { + task.put("Credentials", Map.of("RoleArn", taskRole)); + } + return task; + } + + private Map task(String integration, SqsTestQueue queue, String form, String taskRole) { + return switch (form) { + case "jsonpath" -> jsonPathTask(integration, queue, taskRole); + case "jsonpath-path" -> { + Map task = jsonPathTask(integration, queue, null); + task.put("Credentials", Map.of("RoleArn.$", "$.role")); + yield task; + } + default -> Map.of("Type", "Task", "QueryLanguage", "JSONata", + "Resource", "arn:aws:states:::" + integration, + "Credentials", Map.of("RoleArn", "{% $states.input.role %}"), + "Arguments", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true); + }; + } + + private SqsTestQueue queue() { + SqsTestQueue queue = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "sfn-sqs-iam-"); + cleanup.register(queue::delete); + return queue; + } + + private String role(String trust, String policy) { + return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", + "sfn-sqs-" + 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-sqs-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 terminal(execution, 5); + } + + private Response terminal(String execution, int seconds) throws Exception { + return sfn().terminal(ACCOUNT, execution, seconds); + } + + private void await(String execution, String eventType) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + do { + if (!eventsOfType(execution, eventType).isEmpty()) { + return; + } + Thread.sleep(25); + } while (System.nanoTime() < deadline); + fail("No " + eventType + " event in " + execution); + } + + 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/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java index 50cae43e35..24b260101b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java @@ -5,14 +5,18 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.github.hectorvent.floci.services.lambda.LambdaExecutorService; import io.github.hectorvent.floci.services.lambda.model.InvokeResult; +import io.github.hectorvent.floci.services.sqs.SqsService; import io.github.hectorvent.floci.testing.EnforcementFixtures; import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testing.SqsTestQueue; +import io.github.hectorvent.floci.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.mockito.InjectSpy; import io.restassured.response.Response; +import jakarta.inject.Inject; import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -29,7 +33,6 @@ import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; 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.argThat; import static org.mockito.ArgumentMatchers.eq; @@ -56,6 +59,9 @@ class StepFunctionsTaskCredentialsIntegrationTest { @InjectSpy JsonataEvaluator jsonataEvaluator; + @Inject + SqsService sqsService; + @RegisterExtension final PartitionCleanup cleanup = new PartitionCleanup(); @@ -209,6 +215,46 @@ class StepFunctionsTaskCredentialsIntegrationTest { verify(lambdaExecutor).invoke(argThat(fn -> fn != null && function.equals(fn.getFunctionArn())), any(), any()); } + /** The execution role does not exist, and neither does the Credentials role: nothing evaluates either. */ + @ParameterizedTest + @ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"}) + void sqsCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception { + SqsTestQueue queue = SqsTestQueue.create(sqsService, SOURCE, "us-east-1", "credentials-"); + cleanup.register(queue::delete); + 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", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true)))); + + String execution = start(machine(SOURCE, definition, "STANDARD"), "{}"); + Response done = terminal(SOURCE, execution); + + assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString()); + assertEquals("hello", queue.receive().getFirst().getBody()); + assertEquals(taskRole, taskScheduled(execution).path("taskCredentials").path("roleArn").asText()); + } + + @Test + void credentialsThatDoNotResolveStillPassWithEnforcementOff() throws Exception { + SqsTestQueue queue = SqsTestQueue.create(sqsService, SOURCE, "us-east-1", "credentials-"); + cleanup.register(queue::delete); + String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", Map.of( + "Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage", + "Credentials", Map.of("RoleArn.$", "$.missing"), + "Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true)))); + + String execution = start(machine(SOURCE, definition, "STANDARD"), "{}"); + Response done = terminal(SOURCE, execution); + + assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString()); + assertTrue(taskScheduled(execution).path("taskCredentials").isMissingNode(), done.asString()); + } + + private JsonNode taskScheduled(String execution) throws Exception { + return sfn().eventsOfType(SOURCE, execution, "TaskScheduled").getFirst().path("taskScheduledEventDetails"); + } + @Test void childFailureIsCaughtInParentAccount() throws Exception { String child = machine(TARGET, """ @@ -288,50 +334,23 @@ class StepFunctionsTaskCredentialsIntegrationTest { } private String machine(String account, String definition, String type) throws Exception { - String name = "credentials-" + UUID.randomUUID(); - String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name; - cleanup.register(() -> removeMachine(account, arn)); - Response response = request(account, "CreateStateMachine", Map.of( - "name", name, "definition", definition, - "type", type, "roleArn", "arn:aws:iam::" + account + ":role/execution")); - response.then().statusCode(200); - return response.jsonPath().getString("stateMachineArn"); - } - - private void removeMachine(String account, String arn) { - Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn)); - executions.then().statusCode(200); - for (Map execution : executions.jsonPath().>getList("executions")) { - if ("RUNNING".equals(execution.get("status"))) { - request(account, "StopExecution", Map.of("executionArn", execution.get("executionArn"))) - .then().statusCode(200); - } - } - request(account, "DeleteStateMachine", Map.of("stateMachineArn", arn)).then().statusCode(200); + return sfn().createMachine(account, "credentials-", definition, type, + "arn:aws:iam::" + account + ":role/execution"); } private String start(String machine, String input) throws Exception { - Response response = request(SOURCE, "StartExecution", Map.of("stateMachineArn", machine, "input", input)); - response.then().statusCode(200); - return response.jsonPath().getString("executionArn"); + return sfn().start(SOURCE, machine, input); } private Response terminal(String account, String execution) throws Exception { - for (int i = 0; i < 100; i++) { - Response response = request(account, "DescribeExecution", Map.of("executionArn", execution)); - response.then().statusCode(200); - if (!"RUNNING".equals(response.jsonPath().getString("status"))) { - return response; - } - Thread.sleep(50); - } - fail("Execution did not terminate: " + execution); - return null; + return sfn().terminal(account, execution, 5); } private Response request(String account, String action, Map input) { - return given().port(baseUri.getPort()).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 sfn().request(account, action, input); + } + + private StepFunctionsTestClient sfn() { + return new StepFunctionsTestClient(baseUri.getPort(), cleanup); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissionsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissionsTest.java new file mode 100644 index 0000000000..cf74b33ca6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissionsTest.java @@ -0,0 +1,79 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.stepfunctions.LambdaTaskAuthorizer.Permission; +import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class TaskPermissionsTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ACCOUNT = "111122223333"; + + /** Each form resolves in the state machine's Region, whichever host it names, as the queue lookup does. */ + @ParameterizedTest + @CsvSource({ + "http://localhost:4566/111122223333/orders, 111122223333", + "https://sqs.ap-south-1.amazonaws.com/111122223333/orders, 111122223333", + "http://localhost:4566/sqs/444455556666/orders, 444455556666", + "orders, 111122223333", + "444455556666/orders, 444455556666", + "http://localhost:4566/not-an-account/orders, 111122223333"}) + void aQueueUrlNamesTheQueueItsLookupReaches(String queueUrl, String account) { + assertEquals(new TaskPermissions("SQS.", List.of(new Permission("sqs:SendMessage", + "arn:aws:sqs:eu-west-1:" + account + ":orders"))), + TaskPermissions.of(integration("sqs:sendMessage"), input(queueUrl), machine("aws")).orElseThrow()); + } + + @Test + void theQueueIsInTheStateMachinesPartition() { + assertEquals(List.of(new Permission("sqs:SendMessage", "arn:aws-cn:sqs:eu-west-1:" + ACCOUNT + ":orders")), + TaskPermissions.of(integration("sqs:sendMessage"), input("orders"), machine("aws-cn")) + .orElseThrow().permissions()); + } + + @Test + void theSdkFormNamesItsOwnErrorPrefix() { + assertEquals("Sqs.", TaskPermissions.of(integration("aws-sdk:sqs:sendMessage"), input("orders"), machine("aws")) + .orElseThrow().errorPrefix()); + } + + /** SQS answers these with its own validation error once the role has passed. */ + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"QueueUrl\":\" \"}", "{\"QueueUrl\":7}"}) + void aRequestNamingNoQueueNeedsNoPermission(String request) throws Exception { + assertEquals(new TaskPermissions("SQS.", List.of()), + TaskPermissions.of(integration("sqs:sendMessage"), MAPPER.readTree(request), machine("aws")).orElseThrow()); + } + + @ParameterizedTest + @ValueSource(strings = {"lambda:invoke", "apigateway:invoke", "sns:publish", "aws-sdk:sqs:receiveMessage", + "states:startExecution", "dynamodb:putItem", "http:invoke"}) + void integrationsNotMappedStayUnchecked(String integration) { + assertEquals(Optional.empty(), TaskPermissions.of(integration(integration), input("orders"), machine("aws"))); + } + + private static StatesIntegration integration(String tail) { + return StatesIntegration.parse("arn:aws:states:::" + tail).orElseThrow(); + } + + private static JsonNode input(String queueUrl) { + return MAPPER.valueToTree(Map.of("QueueUrl", queueUrl)); + } + + private static StateMachine machine(String partition) { + StateMachine machine = new StateMachine(); + machine.setStateMachineArn("arn:" + partition + ":states:eu-west-1:" + ACCOUNT + ":stateMachine:m"); + return machine; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/testing/SqsTestQueue.java b/src/test/java/io/github/hectorvent/floci/testing/SqsTestQueue.java index 9a7497d151..ecac82df92 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/SqsTestQueue.java +++ b/src/test/java/io/github/hectorvent/floci/testing/SqsTestQueue.java @@ -53,6 +53,17 @@ public final class SqsTestQueue { sqsService.getQueueAttributes(url, List.of("QueueArn"), region).get("QueueArn")); } + /** Sets the queue's {@code Policy} attribute. */ + public void setPolicy(String policy) { + RequestScopes.runAs(account, () -> sqsService.setQueueAttributes(url, Map.of("Policy", policy), region)); + } + + /** Grants {@code action} to the root of {@code grantedAccount}, as AddPermission writes it into the policy. */ + public void addPermission(String label, String grantedAccount, String action) { + RequestScopes.runAs(account, () -> + sqsService.addPermission(url, label, List.of(grantedAccount), List.of(action), region)); + } + /** At most one message, received without waiting. */ public List receive() { return RequestScopes.callAs(account, () -> diff --git a/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsTestClient.java b/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsTestClient.java new file mode 100644 index 0000000000..484d60a399 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsTestClient.java @@ -0,0 +1,93 @@ +package io.github.hectorvent.floci.testing; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.restassured.response.Response; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.fail; + +/** Step Functions calls a test makes as one account, and the state machines it leaves to {@code cleanup}. */ +public final class StepFunctionsTestClient { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final long POLL_MILLIS = 25; + + private final int port; + private final PartitionCleanup cleanup; + + public StepFunctionsTestClient(int port, PartitionCleanup cleanup) { + this.port = port; + this.cleanup = cleanup; + } + + 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("/"); + } + + /** 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(); + String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name; + cleanup.register(() -> removeMachine(account, arn)); + Response created = request(account, "CreateStateMachine", Map.of( + "name", name, "definition", definition, "type", type, "roleArn", role)); + created.then().statusCode(200); + return created.jsonPath().getString("stateMachineArn"); + } + + public String start(String account, String machine, String input) { + Response started = request(account, "StartExecution", Map.of("stateMachineArn", machine, "input", input)); + started.then().statusCode(200); + return started.jsonPath().getString("executionArn"); + } + + /** Polls until the execution ends: nothing in the API waits for a standard workflow. */ + public Response terminal(String account, String execution, int seconds) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds); + do { + Response response = request(account, "DescribeExecution", Map.of("executionArn", execution)); + response.then().statusCode(200); + if (!"RUNNING".equals(response.jsonPath().getString("status"))) { + return response; + } + Thread.sleep(POLL_MILLIS); + } while (System.nanoTime() < deadline); + fail("Execution did not terminate: " + execution); + return null; + } + + public List eventsOfType(String account, String execution, String type) throws Exception { + Response history = request(account, "GetExecutionHistory", Map.of("executionArn", execution)); + history.then().statusCode(200); + List events = new ArrayList<>(); + for (JsonNode event : MAPPER.readTree(history.asString()).path("events")) { + if (type.equals(event.path("type").asText())) { + events.add(event); + } + } + return events; + } + + private void removeMachine(String account, String arn) { + Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn)); + if (executions.statusCode() == 200) { + for (Map execution : executions.jsonPath().>getList("executions")) { + if ("RUNNING".equals(execution.get("status"))) { + request(account, "StopExecution", Map.of("executionArn", execution.get("executionArn"))) + .then().statusCode(200); + } + } + } + request(account, "DeleteStateMachine", Map.of("stateMachineArn", arn)).then().statusCode(200); + } +}