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 <hectorvent@gmail.com>

* 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 <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-05 09:50:01 -06:00
1 parent 4b09c3cf2b
commit bd65477927
21 files changed
+1489 -108

No files matched your search

+8
View File
@@ -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 `/<account>/<queue-name>`, 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
+42 -2
View File
@@ -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 `<prefix>.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:<service>:<action>` 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.
@@ -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();
}
@@ -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<ResourcePolicy> 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()));
}
}
@@ -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<String> 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));
}
@@ -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<JsonNode> 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<JsonNode> 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<TaskPermissions> 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<JsonNode> 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<String, Object> 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);
}
@@ -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.
*
* <p>{@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<ResourcePolicyProvider> resourcePolicies;
private final Instance<ScpProvider> scpProvider;
@Inject
public LambdaTaskAuthorizer(IamService iamService, IamPolicyEvaluator evaluator,
AssumeRolePolicyEvaluator trustEvaluator,
LambdaResourcePolicyProvider functionPolicies, Instance<ScpProvider> scpProvider) {
Instance<ResourcePolicyProvider> resourcePolicies,
Instance<ScpProvider> 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<String, List<String>> 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 <errorPrefix>AccessDeniedException} for a refused permission
*/
void authorize(StateMachine machine, String credentialsRoleArn, String errorPrefix, List<Permission> 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<String> 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<String> 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<String> refusal(String roleArn, String action, String resourceArn, String requestedRegion,
Map<String, List<String>> conditionKeys) {
AwsArnUtils.Arn resource = ANY_RESOURCE.equals(resourceArn) ? null : AwsArnUtils.parse(resourceArn);
Optional<IamRole> 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<List<String>> scpLevels = scpLevels(roleId.accountId());
List<ResourcePolicy> policies = "lambda".equals(resource.service())
? functionPolicies.getResourcePolicies("lambda", resourceArn) : List.of();
String ownerAccount = policies.isEmpty() ? resource.accountId() : policies.getFirst().ownerAccountId();
List<ResourcePolicy> 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<String> documents = policies.stream()
.map(ResourcePolicy::policyDocument)
.filter(document -> document != null && !document.isBlank())
.toList();
Map<String, List<String>> serviceContext = new LinkedHashMap<>(conditionKeys);
serviceContext.put("aws:PrincipalArn", List.of(invokingRoleArn));
Map<String, List<String>> 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;
}
@@ -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 + ".");
@@ -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<Permission> permissions) {
/** The permissions of a mapped integration, or nothing for one that is not checked. */
static Optional<TaskPermissions> 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()))));
}
}
@@ -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\"}");
@@ -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();
}
}
@@ -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());
}
}
@@ -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<ResourcePolicyProvider> 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();
@@ -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<String, Object> 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<String, Object> 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<String, Object> 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<HistoryEvent> 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<String, Object> scheduledDetails(String eventType, String resource, String credentials, String input)
throws Exception {
ArrayList<HistoryEvent> 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<String, Object> detailsOf(List<HistoryEvent> 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(
@@ -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> 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<ResourcePolicyProvider> 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<String> denied(String functionArn, String reason) {
return Optional.of("User: " + SESSION + " is not authorized to perform: lambda:InvokeFunction on resource: "
+ functionArn + " " + reason);
@@ -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<String, String> execution : executions.jsonPath().<Map<String, String>>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<String, ?> 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) {
@@ -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<String, Object> 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<String, Object> 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<String, Object> jsonPathTask(String integration, SqsTestQueue queue, String taskRole) {
Map<String, Object> 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<String, Object> task(String integration, SqsTestQueue queue, String form, String taskRole) {
return switch (form) {
case "jsonpath" -> jsonPathTask(integration, queue, taskRole);
case "jsonpath-path" -> {
Map<String, Object> 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<String, Object> 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<JsonNode> eventsOfType(String execution, String type) throws Exception {
return sfn().eventsOfType(ACCOUNT, execution, type);
}
private Response request(String action, Map<String, ?> input) {
return sfn().request(ACCOUNT, action, input);
}
private StepFunctionsTestClient sfn() {
return new StepFunctionsTestClient(baseUri.getPort(), cleanup);
}
}
@@ -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<String, String> execution : executions.jsonPath().<Map<String, String>>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<String, ?> 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);
}
}
@@ -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;
}
}
@@ -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<Message> receive() {
return RequestScopes.callAs(account, () ->
@@ -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<String, ?> 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<JsonNode> eventsOfType(String account, String execution, String type) throws Exception {
Response history = request(account, "GetExecutionHistory", Map.of("executionArn", execution));
history.then().statusCode(200);
List<JsonNode> 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<String, String> execution : executions.jsonPath().<Map<String, String>>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);
}
}