feat(stepfunctions): evaluate the execution role on the remaining task integrations (#7724)

* feat(stepfunctions): evaluate the execution role on the remaining task integrations
* fix(stepfunctions): check a Secrets Manager task from the generated request resources
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-14 23:58:52 -04:00
1 parent 558453df20
commit 1b8e4fa503
12 files changed
+1729 -36

No files matched your search

+71 -12
View File
@@ -90,11 +90,11 @@ With IAM enforcement enabled, the existing task authorizer checks the execution
permission to assume the task role, its trust policy, and the task role's permission to
start the child. Account routing also works with enforcement disabled. The `.sync`
polling and cancellation paths retain the task account; their additional IAM permissions
are not evaluated. Lambda, API Gateway, SQS, SNS, EventBridge, DynamoDB, S3 `putObject`, RDS Data,
Redshift Data, ECS, EMR and EMR Serverless tasks evaluate `Credentials` themselves
are not evaluated. Every other integration evaluates `Credentials` itself
([Lambda](#lambda-tasks-under-iam-enforcement), [messaging](#messaging-tasks-under-iam-enforcement),
[data](#data-tasks-under-iam-enforcement), [jobs](#job-tasks-under-iam-enforcement)); other
integrations retain their existing credential handling.
[data](#data-tasks-under-iam-enforcement), [jobs](#job-tasks-under-iam-enforcement),
[control](#control-tasks-under-iam-enforcement)), and so does a nested task in its `.waitForTaskToken`
form, which this routing does not serve: it runs in the state machine's account.
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
@@ -771,9 +771,70 @@ AWS; the prefix is the one each integration's other errors carry. EMR's own erro
global condition keys are available to the policies: `ecs:cluster` and the like are absent, so an Allow
conditioned on them does not apply. With enforcement off nothing here is evaluated.
Integrations other than these, the data and messaging tasks, Lambda, API Gateway and nested executions
are not evaluated yet: they run in the state machine's account whatever the execution role's policies
say.
## Control tasks under IAM enforcement
With `floci.services.iam.enforcement-enabled`, these tasks are authorized like the
[messaging tasks](#messaging-tasks-under-iam-enforcement), in the same order. Each action and resource
type comes from the Service Authorization Reference:
| Resource | Action | Resource evaluated | Refused with |
|---|---|---|---|
| `arn:aws:states:::aws-sdk:scheduler:createSchedule`, `updateSchedule`, `deleteSchedule` | `scheduler:CreateSchedule` and so on | `schedule/<GroupName>/<Name>`, `default` for a group left out | `Scheduler.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:cloudformation:<api>` | `cloudformation:<Action>` | See below | `CloudFormation.AccessDeniedException` |
| `arn:aws:states:::http:invoke` | `states:InvokeHTTPEndpoint` | The state machine | `States.Http.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:ec2:describeRegions` | `ec2:DescribeRegions` | `*` | `Ec2.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:lambda:listEventSourceMappings` | `lambda:ListEventSourceMappings` | `*` | `Lambda.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:lambda:updateEventSourceMapping` | `lambda:UpdateEventSourceMapping` | `event-source-mapping:<UUID>` | `Lambda.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:secretsmanager:describeSecret` | `secretsmanager:DescribeSecret` | As a direct `DescribeSecret`: the secret's stored ARN, suffix included, or `secret:<SecretId>-??????` for a name no secret goes by | `SecretsManager.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:sfn:startExecution`, `startSyncExecution` | `states:StartExecution`, `states:StartSyncExecution` | The child state machine | `Sfn.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:sfn:sendTaskSuccess`, `sendTaskFailure` | `states:SendTaskSuccess`, `states:SendTaskFailure` | The activity or state machine waiting on the token | `Sfn.AccessDeniedException` |
| `arn:aws:states:::aws-sdk:sfn:describeMapRun` | `states:DescribeMapRun` | The Map Run | `Sfn.AccessDeniedException` |
| `arn:aws:states:::states:startExecution`, with `.sync`, `.sync:2` or `.waitForTaskToken` | `states:StartExecution` | The child state machine | `StepFunctions.AccessDeniedException` |
A CloudFormation action is evaluated on the stack or stack set the request reaches, under the id
CloudFormation holds for it, so a name and the id it stands for are one resource:
`stack/<StackName>/<id>` and `stackset/<StackSetName>:<id>`. `createStack` and `createChangeSet` on a stack
not there yet evaluate `stack/<StackName>/*`. A change set named by its ARN, or a `describeStackResources`
naming a `PhysicalResourceId`, is evaluated on the stack that holds it. `describeStacks` and
`getTemplateSummary` without a `StackName` are on `*`, as are `validateTemplate`, `listStacks`, `listExports`,
`createStackSet`, `listStackSets`, `describeOrganizationsAccess` and `activateOrganizationsAccess`, which
have no resource type.
`states:InvokeHTTPEndpoint` has no resource type in the Service Authorization Reference, and the CDK grants
it on `*`, while the Developer Guide's example scopes it to the state machine, so the state machine is what is
evaluated: both policies allow it. The task gives `states:HTTPEndpoint` and `states:HTTPMethod`, both of which
those policies use. The value of `states:HTTPEndpoint` is `ApiEndpoint` as resolved, without `QueryParameters`.
The guide also requires `events:RetrieveConnectionCredentials` and the connection secret's Secrets Manager
permissions. Floci does not evaluate them, although the task reads the connection to authorize its request:
a role lacking them succeeds here and fails on AWS.
A nested `states:startExecution` task does not refuse its execution role for not existing or not
trusting Step Functions, as a Lambda task does not. It only needs the action, which a role that does not
exist does not have. `.sync` needs the starting call alone, not `states:DescribeExecution`, `states:StopExecution`
or the EventBridge permissions the CDK grants for its wait. With `Credentials`, a nested task other than
the `.waitForTaskToken` form keeps the checks and errors of
[nested task credentials](#nested-task-credentials).
Every integration that evaluates a role is refused on its `.waitForTaskToken` form the same way: the refused
task starts nothing and waits for nothing. With the permission, it calls its service and then waits on its
token.
A request naming nothing it can reach has only the role checks, and its service answers it: no `Name`, a stack
or stack set name its service does not have, no `SecretId`, no `UUID`, no `ApiEndpoint`, a `StateMachineArn` or
`MapRunArn` that is not one, or a token naming no task. A stack named by an ARN of what does not exist here is left
to the service. A secret is evaluated as a direct `DescribeSecret` naming it is, from the generated request resources. An API Floci does not serve keeps its
answer, whatever the role: it is "Unsupported", or CloudFormation's `UnknownAction`, and the role is not checked.
An activity task is not evaluated: the CDK's own task needs no permission for it, and the worker calling
`GetActivityTask` is authorized by its own request. `Map`'s `ItemReader` and `ResultWriter` S3 calls are not
evaluated yet; they run in the state machine's account whatever the execution role's policies say.
`<prefix>.AccessDeniedException` and `States.Http.AccessDeniedException` are Floci's reading and have not
been verified against AWS; a nested task with `Credentials` reports a refused action as
`StepFunctions.AWSStepFunctionsException` or `Sfn.SfnException` instead, so a state machine catching this should
name both. `iam:PassRole` is not evaluated for the roles a schedule or a stack names, and only
the condition keys above and global ones are available to the policies. With enforcement off nothing here is
evaluated.
## Task credentials in history
@@ -837,11 +898,9 @@ their `UUID` spelling.
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. The three Lambda mapping and Secrets Manager integrations do not
evaluate the state-machine execution role's per-action IAM policies; the three ECS ones
[do](#job-tasks-under-iam-enforcement), and among the task integrations so do Lambda, API
Gateway, nested executions, the [messaging tasks](#messaging-tasks-under-iam-enforcement) and the
[data tasks](#data-tasks-under-iam-enforcement). Name-based lookups use the
instead of being silently ignored. Under IAM enforcement the [ECS](#job-tasks-under-iam-enforcement)
and [Lambda and Secrets Manager](#control-tasks-under-iam-enforcement) ones evaluate the
state-machine execution role's per-action IAM policies. 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.
@@ -23,6 +23,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
@@ -44,6 +45,26 @@ public class CloudFormationQueryHandler {
this.stackSetService = stackSetService;
}
/** The id of the stack a stack name or id names, as a request naming it finds it. */
public Optional<String> stackId(String stackNameOrId, String region) {
return cfnService.stackId(stackNameOrId, region);
}
/** The id of the stack holding the change set {@code changeSetArn} names. */
public Optional<String> stackIdOfChangeSet(String changeSetArn, String region) {
return cfnService.stackIdOfChangeSet(changeSetArn, region);
}
/** The id of the stack that owns the resource {@code physicalResourceId} names. */
public Optional<String> stackIdOfResource(String physicalResourceId, String region) {
return cfnService.stackIdOfResource(physicalResourceId, region);
}
/** The id of the stack set of this name. */
public Optional<String> stackSetId(String stackSetName) {
return stackSetService.stackSetId(stackSetName);
}
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
return switch (action) {
case "DescribeStacks" -> describeStacks(params, region);
@@ -398,6 +398,32 @@ public class CloudFormationService implements ResourceProvider {
// ── DescribeStacks ────────────────────────────────────────────────────────
/** The id of the stack a stack name or id names, as a request describing it finds it, reading only. */
public Optional<String> stackId(String stackNameOrId, String region) {
return Optional.ofNullable(resolveStackForDescribe(stackNameOrId, region)).map(Stack::getStackId);
}
/** The id of the stack holding the change set {@code changeSetArn} names, reading only. */
public Optional<String> stackIdOfChangeSet(String changeSetArn, String region) {
try {
return Optional.ofNullable(findStackForChangeSetArn(changeSetArn, region, currentAccount()))
.map(Stack::getStackId);
} catch (AwsException expected) {
LOG.debugv("The change set ARN {0} names no change set: {1}", changeSetArn, expected.getMessage());
return Optional.empty();
}
}
/** The id of the stack that owns the resource {@code physicalResourceId} names, reading only. */
public Optional<String> stackIdOfResource(String physicalResourceId, String region) {
try {
return Optional.of(stackContaining(physicalResourceId, region).getStackId());
} catch (AwsException expected) {
LOG.debugv("No stack owns the resource {0}: {1}", physicalResourceId, expected.getMessage());
return Optional.empty();
}
}
public List<Stack> describeStacks(String stackName, String region) {
return describeStacks(stackName, region, currentAccount());
}
@@ -204,6 +204,11 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
organizationsAccess.put(ORGANIZATIONS_ACCESS_KEY, "ENABLED");
}
/** The id of the stack set of this name, reading only. */
public Optional<String> stackSetId(String name) {
return stackSets.get(name).map(StackSet::getStackSetId);
}
public StackSet describeStackSet(String name) {
return getStackSetOrThrow(name);
}
@@ -9,6 +9,7 @@ import io.floci.aws.core.common.AwsErrorResponse;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.EpochSeconds;
import io.floci.aws.core.common.IamEnforcementFilter;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.secretsmanager.model.Secret;
import io.floci.aws.services.secretsmanager.model.SecretVersion;
import jakarta.enterprise.context.ApplicationScoped;
@@ -48,6 +49,11 @@ public class SecretsManagerJsonHandler {
this.eventPublisher = eventPublisher;
}
/** The secrets the service finds, random suffix included, for a caller naming the resources of a request. */
public StoredResourceArns storedResourceArns() {
return service;
}
/**
* Handles a request that carries no caller credential of its own, such as an API Gateway
* service integration. Checks that authorize the caller for a second resource have no caller to
@@ -1260,9 +1260,15 @@ public class AslExecutor {
/** Integrations {@link TaskPermissions} does not map stay unchecked, Lambda and API Gateway check their own. */
private void authorizeTask(StatesIntegration integration, JsonNode input, StateMachine sm, JsonNode credentials,
String taskToken) {
// NestedTaskCredentials has decided this one. Its callback form does not reach it, so it is decided here.
if (credentials != null && taskToken == null && NestedTaskCredentials.isNested(integration)) {
return;
}
Optional<TaskPermissions> required = TaskPermissions.of(integration, input, sm,
redshiftDataHandler == null ? null : redshiftDataHandler.storedResourceArns(), ecsService,
taskToken != null);
taskToken != null, new TaskPermissions.ControlServices(cloudFormationHandler,
sdkManagementTaskInvoker == null ? null : sdkManagementTaskInvoker.secretsStoredResourceArns(),
sfnService == null || !sfnService.isResolvable() ? null : sfnService.get()));
if (required.isEmpty()) {
return;
}
@@ -1270,7 +1276,7 @@ public class AslExecutor {
NestedTaskCredentials.validateShape(credentials);
}
lambdaTaskAuthorizer.authorize(sm, credentials == null ? null : credentials.path("RoleArn").asText(),
required.get().deniedError(), required.get().permissions());
required.get().deniedError(), required.get().permissions(), required.get().checksExecutionRole());
}
private boolean iamEnforcementEnabled() {
@@ -98,14 +98,27 @@ public class LambdaTaskAuthorizer {
* {@code States.TaskFailed} for a refused assumption, and {@code deniedError} for a refused permission
*/
void authorize(StateMachine machine, String credentialsRoleArn, String deniedError, List<Permission> permissions) {
authorize(machine, credentialsRoleArn, deniedError, permissions, true);
}
/**
* As {@link #authorize(StateMachine, String, String, List)}.
*
* @param checkExecutionRole false for an integration whose tasks do not refuse an execution role for not existing
* or not trusting Step Functions: a nested execution, which only needs the permissions
*/
void authorize(StateMachine machine, String credentialsRoleArn, String deniedError, List<Permission> permissions,
boolean checkExecutionRole) {
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.");
if (checkExecutionRole) {
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) {
@@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.core.common.ServiceRegistry;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.ecs.EcsJsonHandler;
import io.floci.aws.services.lambda.LambdaController;
import io.floci.aws.services.secretsmanager.SecretsManagerJsonHandler;
@@ -54,6 +55,11 @@ public class SdkManagementTaskInvoker {
};
}
/** The secrets Secrets Manager finds, for the request of a {@code DescribeSecret} task. */
StoredResourceArns secretsStoredResourceArns() {
return secrets.storedResourceArns();
}
JsonNode invoke(StatesIntegration integration, JsonNode input, String region) throws Exception {
String prefix = switch (integration.service()) {
case "ecs" -> "Ecs";
@@ -8,6 +8,7 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestChecks;
import io.floci.aws.core.common.RequestResources;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.cloudformation.CloudFormationQueryHandler;
import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser;
import io.floci.aws.services.dynamodb.DynamoDbTableNames;
import io.floci.aws.services.eventbridge.EventBridgeService;
@@ -21,6 +22,7 @@ import io.floci.aws.services.stepfunctions.model.StateMachine;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -31,16 +33,14 @@ import java.util.Set;
* 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 deniedError the error a refused permission fails the task with: the integration's prefix and
* the exception the integrated service's SDK raises for an access denial
* @param permissions the actions the call performs
* @param deniedError the error a refused permission fails the task with: the integration's prefix
* and the exception the integrated service's SDK raises for an access denial
* @param permissions the actions the call performs
* @param checksExecutionRole whether the task also needs its execution role to exist and to trust Step Functions,
* which a nested execution does not, on the maintainer's decision to leave nested and
* Lambda tasks as they are
*/
record TaskPermissions(String deniedError, List<Permission> permissions) {
/** The permissions of an integration whose refusal is its prefix and {@code AccessDeniedException}. */
static TaskPermissions accessDenied(String errorPrefix, List<Permission> permissions) {
return new TaskPermissions(errorPrefix + "AccessDeniedException", permissions);
}
record TaskPermissions(String deniedError, List<Permission> permissions, boolean checksExecutionRole) {
private static final Logger LOG = Logger.getLogger(TaskPermissions.class);
private static final String ANY_RESOURCE = "*";
@@ -52,6 +52,8 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
private static final String ECS_SDK_PREFIX = "Ecs.";
private static final String EMR_PREFIX = "EMR.";
private static final String EMR_SERVERLESS_PREFIX = "EmrServerless.";
private static final String LAMBDA_PREFIX = "Lambda.";
private static final String SECRETS_MANAGER_PREFIX = "SecretsManager.";
private static final Set<String> DYNAMODB_OPTIMIZED =
Set.of("putItem", "getItem", "deleteItem", "updateItem", "scan");
private static final ObjectMapper MAPPER = new ObjectMapper();
@@ -67,6 +69,48 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
"cancelStep", List.of("CancelSteps"),
"modifyInstanceFleetByName", List.of("ListInstanceFleets", "ModifyInstanceFleet"),
"modifyInstanceGroupByName", List.of("ListInstanceGroups", "ModifyInstanceGroups"));
private static final String SCHEDULER_PREFIX = "Scheduler.";
private static final String CLOUDFORMATION_PREFIX = "CloudFormation.";
private static final String HTTP_PREFIX = "States.Http.";
private static final String SFN_SDK_PREFIX = "Sfn.";
private static final String NESTED_PREFIX = "StepFunctions.";
private static final Set<String> SCHEDULER = Set.of("createSchedule", "updateSchedule", "deleteSchedule");
private static final Set<String> SFN_SDK = Set.of("startExecution", "startSyncExecution", "sendTaskSuccess",
"sendTaskFailure", "describeMapRun");
private static final Set<String> CFN_ANY_RESOURCE = Set.of("ValidateTemplate", "ListStacks", "ListExports",
"DescribeOrganizationsAccess", "ActivateOrganizationsAccess", "CreateStackSet", "ListStackSets");
private static final Set<String> CFN_OPTIONAL_STACK = Set.of("DescribeStacks", "GetTemplateSummary");
private static final Set<String> CFN_CREATES_STACK = Set.of("CreateStack", "CreateChangeSet");
private static final Set<String> CFN_NAMES_CHANGE_SET =
Set.of("DescribeChangeSet", "ExecuteChangeSet", "DeleteChangeSet");
private static final Set<String> CFN_STACK = Set.of("UpdateStack", "DeleteStack", "ContinueUpdateRollback",
"UpdateTerminationProtection", "ListChangeSets", "DescribeStackEvents", "DescribeStackResources",
"ListStackResources", "DescribeStackResource", "GetTemplate", "SetStackPolicy", "GetStackPolicy");
private static final Set<String> CFN_STACK_SET = Set.of("DescribeStackSet", "UpdateStackSet", "DeleteStackSet",
"CreateStackInstances", "ListStackInstances", "DescribeStackInstance", "DeleteStackInstances",
"ListStackSetOperations", "DescribeStackSetOperation", "ListStackSetAutoDeploymentTargets");
TaskPermissions(String deniedError, List<Permission> permissions) {
this(deniedError, permissions, true);
}
/** The permissions of an integration whose refusal is its prefix and {@code AccessDeniedException}. */
static TaskPermissions accessDenied(String errorPrefix, List<Permission> permissions) {
return new TaskPermissions(errorPrefix + "AccessDeniedException", permissions);
}
/**
* What finds the resources of a control task's request, reading only.
*
* @param cloudFormation the stack or stack set of a CloudFormation request; without it such a request names nothing
* @param secrets the secret a Secrets Manager request names, random suffix included; without it a secret is
* the ARN its format gives the name
* @param states the state machine or activity whose task a callback's token names; without it a token
* names nothing
*/
record ControlServices(CloudFormationQueryHandler cloudFormation, StoredResourceArns secrets,
StoredResourceArns states) {
}
/** The permissions of a mapped integration, or nothing for one that is not checked. */
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine) {
@@ -96,6 +140,49 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
*/
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback) {
return of(integration, input, machine, redshiftData, ecs, callback, new ControlServices(null, null, null));
}
/**
* The permissions of a mapped integration, or nothing for one that is not checked.
*
* @param redshiftData finds the workgroup or the session target a Data API request names; without it a
* workgroup is any workgroup and a session names nothing
* @param ecs finds the task definition revision a reference resolves to and the default cluster, reading
* only; without it a family names any revision and a request naming no cluster any cluster
* @param callback whether the state's resource ended in {@code .waitForTaskToken}, which {@code integration}
* no longer shows: EMR and EMR Serverless have no such form, so theirs stays unsupported
* @param control finds what a control task's request names
*/
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback,
ControlServices control) {
if (integration.isSdkService("scheduler") && SCHEDULER.contains(integration.api())) {
return Optional.of(scheduler(integration.api(), input, machine));
}
if (integration.isSdkService("cloudformation") && servedByCloudFormation(integration.api())) {
return Optional.of(cloudFormation(AslExecutor.capitalizeFirst(integration.api()), input, machine,
control.cloudFormation()));
}
if (integration.is("http", "invoke")) {
return Optional.of(httpInvoke(input, machine));
}
if (integration.isSdk("ec2", "describeRegions")) {
return Optional.of(ec2DescribeRegions(input, machine));
}
if (integration.isSdkService("lambda") && SdkManagementTaskInvoker.supports(integration)) {
return Optional.of(lambdaSdk(integration.api(), input, machine));
}
if (integration.isSdkService("secretsmanager") && SdkManagementTaskInvoker.supports(integration)) {
return Optional.of(accessDenied(SECRETS_MANAGER_PREFIX,
requestPermissions("secretsmanager", "DescribeSecret", input, machine, control.secrets())));
}
if (integration.isSdkService("sfn") && SFN_SDK.contains(integration.api())) {
return Optional.of(sfnSdk(AslExecutor.capitalizeFirst(integration.api()), input, machine, control.states()));
}
if (integration.isAnySuffix("states", "startExecution")) {
return Optional.of(nestedStartExecution(input, machine));
}
if (integration.isAnySuffix("ecs", "runTask")
&& (integration.suffix().isEmpty() || ".sync".equals(integration.suffix()))) {
return Optional.of(accessDenied(ECS_OPTIMIZED_PREFIX, ecs("RunTask", input, machine, ecs)));
@@ -335,9 +422,19 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
*/
private static List<Permission> ecs(String operation, JsonNode input, StateMachine machine,
StoredResourceArns ecs) {
String namedAs = "ecs:" + operation;
String action = IamAuthorizedActions.actionFor("ecs", operation);
JsonNode request = AslExecutor.recaseKeys(MAPPER, input, false);
return requestPermissions("ecs", operation, AslExecutor.recaseKeys(MAPPER, input, false), machine, ecs);
}
/**
* The check the vendored request resources give the same call made directly, in the state machine's partition,
* Region and account: the operation's action on each resource the request names, {@code stored} finding the ones
* only its service knows, or on any resource for an operation that acts on no resource type. A request that is no
* object, or an operation the table does not read, needs nothing here: the service answers it.
*/
private static List<Permission> requestPermissions(String namespace, String operation, JsonNode request,
StateMachine machine, StoredResourceArns stored) {
String namedAs = namespace + ":" + operation;
String action = IamAuthorizedActions.actionFor(namespace, operation);
if (!request.isObject() || !RequestResources.reads(namedAs)) {
return List.of();
}
@@ -345,7 +442,7 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
return List.of(new Permission(action, ANY_RESOURCE));
}
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
return RequestResources.ofBody(namedAs, request, owner.partition(), owner.region(), owner.accountId(), ecs)
return RequestResources.ofBody(namedAs, request, owner.partition(), owner.region(), owner.accountId(), stored)
.stream().map(resource -> new Permission(action, resource)).toList();
}
@@ -377,6 +474,14 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
return accessDenied(EMR_PREFIX, permissions);
}
/**
* {@code DescribeRegions}, checked as the vendored request resources check the same call made directly: it acts
* on no resource type, so on any resource.
*/
private static TaskPermissions ec2DescribeRegions(JsonNode input, StateMachine machine) {
return accessDenied("Ec2.", requestPermissions("ec2", "DescribeRegions", input, machine, null));
}
/** The members of the EMR request the integration sends that name the cluster. */
private static JsonNode emrRequest(String operation, String clusterId) {
return switch (operation) {
@@ -409,6 +514,163 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
.map(check -> new Permission(check.action(), check.resource(), check.context())).toList());
}
/**
* The action on the schedule its name and group give, read as the integration reads them, a group left out being
* {@code default}. A request naming no schedule is refused by Scheduler.
*/
private static TaskPermissions scheduler(String api, JsonNode input, StateMachine machine) {
String name = text(input.path("Name"));
if (name == null) {
return accessDenied(SCHEDULER_PREFIX, List.of());
}
String group = text(input.path("GroupName"));
return accessDenied(SCHEDULER_PREFIX, List.of(new Permission(
"scheduler:" + AslExecutor.capitalizeFirst(api),
arn(machine, "scheduler", "schedule/" + (group == null ? "default" : group) + "/" + name))));
}
/** Every action the CloudFormation handler serves; any other is its own {@code UnknownAction}. */
private static boolean servedByCloudFormation(String api) {
String operation = AslExecutor.capitalizeFirst(api);
return CFN_ANY_RESOURCE.contains(operation) || CFN_OPTIONAL_STACK.contains(operation)
|| CFN_CREATES_STACK.contains(operation) || CFN_NAMES_CHANGE_SET.contains(operation)
|| CFN_STACK.contains(operation) || CFN_STACK_SET.contains(operation);
}
/**
* The action of the API's own name, on the stack or stack set the request reaches under the id CloudFormation
* holds for it, in the service reference's resource types, so a name and the id it stands for are the same
* resource. A stack not there yet has its id open for the APIs that create it; for any other API a stack or
* stack set CloudFormation does not have names nothing, so CloudFormation answers it.
*/
private static TaskPermissions cloudFormation(String operation, JsonNode input, StateMachine machine,
CloudFormationQueryHandler stored) {
String action = "cloudformation:" + operation;
if (CFN_ANY_RESOURCE.contains(operation)) {
return accessDenied(CLOUDFORMATION_PREFIX, List.of(new Permission(action, ANY_RESOURCE)));
}
String resource;
if (CFN_STACK_SET.contains(operation)) {
resource = cloudFormationStackSet(input, machine, stored);
} else if (CFN_OPTIONAL_STACK.contains(operation) && text(input.path("StackName")) == null) {
resource = ANY_RESOURCE;
} else {
resource = cloudFormationStack(operation, input, machine, stored);
}
return accessDenied(CLOUDFORMATION_PREFIX,
resource == null ? List.of() : List.of(new Permission(action, resource)));
}
private static String cloudFormationStackSet(JsonNode input, StateMachine machine,
CloudFormationQueryHandler stored) {
String name = text(input.path("StackSetName"));
if (name == null || stored == null) {
return null;
}
return stored.stackSetId(name).map(id -> arn(machine, "cloudformation", "stackset/" + id)).orElse(null);
}
/** The stack as each API finds it: by name or id, or else by the change set or the resource the API can name it by. */
private static String cloudFormationStack(String operation, JsonNode input, StateMachine machine,
CloudFormationQueryHandler stored) {
String stack = text(input.path("StackName"));
String region = regionOf(machine);
if (stored == null) {
return null;
}
if (stack != null) {
Optional<String> id = stored.stackId(stack, region);
boolean opensId = CFN_CREATES_STACK.contains(operation) && !AwsArnUtils.looksLikeArn(stack);
return id.orElseGet(() -> opensId ? arn(machine, "cloudformation", "stack/" + stack + "/*") : null);
}
String changeSet = text(input.path("ChangeSetName"));
if (CFN_NAMES_CHANGE_SET.contains(operation) && AwsArnUtils.looksLikeArn(changeSet)) {
return stored.stackIdOfChangeSet(changeSet, region).orElse(null);
}
String resource = text(input.path("PhysicalResourceId"));
if ("DescribeStackResources".equals(operation) && resource != null) {
return stored.stackIdOfResource(resource, region).orElse(null);
}
return null;
}
/**
* {@code states:InvokeHTTPEndpoint} on the state machine, the resource the Developer Guide's policy scopes it to:
* a role allowed it on {@code *}, as the CDK grants it, is allowed it there too. The two condition keys the guide
* and the CDK write are given. The connection's own permissions, {@code events:RetrieveConnectionCredentials}
* and its secret's, are not evaluated, although the task reads the connection to authorize its request: a role
* lacking them succeeds here and fails on AWS. A request naming no endpoint is refused by the integration.
*/
private static TaskPermissions httpInvoke(JsonNode input, StateMachine machine) {
String endpoint = text(input.path("ApiEndpoint"));
if (endpoint == null) {
return accessDenied(HTTP_PREFIX, List.of());
}
Map<String, List<String>> keys = new LinkedHashMap<>();
keys.put("states:HTTPEndpoint", List.of(endpoint));
String method = text(input.path("Method"));
if (method != null) {
keys.put("states:HTTPMethod", List.of(method));
}
return accessDenied(HTTP_PREFIX, List.of(new Permission("states:InvokeHTTPEndpoint",
machine.getStateMachineArn(), keys)));
}
/**
* {@code ListEventSourceMappings} has no resource type in the service reference, and
* {@code UpdateEventSourceMapping} acts on the mapping its {@code Uuid} names; a request naming none is refused
* by the integration.
*/
private static TaskPermissions lambdaSdk(String api, JsonNode input, StateMachine machine) {
String action = "lambda:" + AslExecutor.capitalizeFirst(api);
if ("listEventSourceMappings".equals(api)) {
return accessDenied(LAMBDA_PREFIX, List.of(new Permission(action, ANY_RESOURCE)));
}
String uuid = text(input.path("Uuid"));
return accessDenied(LAMBDA_PREFIX, uuid == null ? List.of()
: List.of(new Permission(action, arn(machine, "lambda", "event-source-mapping:" + uuid))));
}
/**
* The check a direct request of the operation gets, on what it names: the state machine it starts, the Map Run it
* describes, or the activity or state machine waiting on the callback's token. A token naming no task, or anything
* that is not the ARN the request needs, names nothing, so Step Functions answers it.
*/
private static TaskPermissions sfnSdk(String operation, JsonNode input, StateMachine machine,
StoredResourceArns stored) {
return accessDenied(SFN_SDK_PREFIX, statesPermissions(operation, input, machine, stored));
}
/**
* {@code states:StartExecution} on the child, without the execution role checks the other integrations make, which
* a nested execution has never had. A request naming no state machine is refused by the integration.
*/
private static TaskPermissions nestedStartExecution(JsonNode input, StateMachine machine) {
return new TaskPermissions(NESTED_PREFIX + "AccessDeniedException",
statesPermissions("StartExecution", input, machine, null), false);
}
private static List<Permission> statesPermissions(String operation, JsonNode input, StateMachine machine,
StoredResourceArns stored) {
try {
return requestPermissions("states", operation, AslExecutor.recaseKeys(MAPPER, input, false), machine,
stored);
} catch (AwsException expected) {
LOG.debugv("The {0} request names no task: {1}", operation, expected.getMessage());
return List.of();
}
}
/** The ARN of a resource of the state machine's partition, Region and account. */
private static String arn(StateMachine machine, String service, String resource) {
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
return new AwsArnUtils.Arn(owner.partition(), service, owner.region(), owner.accountId(), resource).toString();
}
private static String regionOf(StateMachine machine) {
return AwsArnUtils.parse(machine.getStateMachineArn()).region();
}
/** The value when it is the non-blank string an id has to be, as the integrations require of one. */
private static String text(JsonNode value) {
return value.isTextual() && !value.asText().isBlank() ? value.asText() : null;
@@ -0,0 +1,945 @@
package io.floci.aws.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpServer;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.floci.aws.testing.StepFunctionsTestClient;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.awaitility.core.ConditionFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.floci.aws.testing.StepFunctionsTestClient.LAMBDA_TRUST;
import static io.floci.aws.testing.StepFunctionsTestClient.STATES_TRUST;
import static io.floci.aws.testing.StepFunctionsTestClient.trusting;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Scheduler, CloudFormation, HTTP, EC2, Lambda and Secrets Manager SDK, Step Functions SDK and nested tasks under IAM
* enforcement. Each reaches its real service, so a test reads what a task did from that service.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class StepFunctionsControlTaskIamIntegrationTest {
private static final String ACCOUNT = "000000000472";
private static final String REGION = "us-east-1";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String READ_ONLY = allow("*", "sns:ListTopics");
private static final String ASSUME = allow("*", "sts:AssumeRole");
private static final String ANY_RESOURCE = "*";
private static final String TEMPLATE =
"{\"Resources\":{\"Handle\":{\"Type\":\"AWS::CloudFormation::WaitConditionHandle\"}}}";
private static final String CHILD_DEFINITION = "{\"StartAt\":\"Done\",\"States\":{\"Done\":{\"Type\":\"Pass\",\"End\":true}}}";
private static final Check NOTHING_TO_READ = () -> { };
private static final AtomicInteger HTTP_CALLS = new AtomicInteger();
private static HttpServer httpServer;
@TestHTTPResource
URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void startEndpoint() throws IOException {
RestAssuredJsonUtils.configureAwsContentTypes();
httpServer = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
httpServer.createContext("/", exchange -> {
HTTP_CALLS.incrementAndGet();
byte[] body = "{}".getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
httpServer.start();
}
@AfterAll
static void stopEndpoint() {
httpServer.stop(0);
}
@BeforeEach
void resetEndpoint() {
HTTP_CALLS.set(0);
}
static Stream<String> everyApi() {
return Stream.of("aws-sdk:scheduler:createSchedule", "aws-sdk:scheduler:updateSchedule",
"aws-sdk:scheduler:deleteSchedule", "aws-sdk:cloudformation:createStack",
"aws-sdk:cloudformation:describeStacks", "aws-sdk:cloudformation:deleteStack",
"aws-sdk:cloudformation:listStacks", "aws-sdk:cloudformation:describeStackSet",
"aws-sdk:cloudformation:createStackSet", "http:invoke", "aws-sdk:ec2:describeRegions",
"aws-sdk:lambda:listEventSourceMappings", "aws-sdk:lambda:updateEventSourceMapping",
"aws-sdk:secretsmanager:describeSecret", "aws-sdk:sfn:startExecution", "aws-sdk:sfn:startSyncExecution",
"aws-sdk:sfn:sendTaskSuccess", "aws-sdk:sfn:sendTaskFailure", "aws-sdk:sfn:describeMapRun",
"states:startExecution", "states:startExecution.sync", "states:startExecution.sync:2");
}
/** What does not differ between an integration's APIs, nested left to its own tests: it is exempt from most of it. */
static Stream<String> eachIntegration() {
return Stream.of("aws-sdk:scheduler:deleteSchedule", "aws-sdk:cloudformation:describeStacks", "http:invoke",
"aws-sdk:ec2:describeRegions", "aws-sdk:lambda:listEventSourceMappings",
"aws-sdk:secretsmanager:describeSecret", "aws-sdk:sfn:describeMapRun");
}
static Stream<Arguments> eachIntegrationInBothLanguages() {
return eachIntegration().flatMap(integration -> Stream.of(Arguments.of(integration, "jsonpath"),
Arguments.of(integration, "jsonata")));
}
@ParameterizedTest
@MethodSource("everyApi")
void anExecutionRoleAllowedTheActionOnTheResourceReachesTheService(String integration) throws Exception {
Target target = target(integration);
Response completed = terminal(start(machine(target, null, role(STATES_TRUST, target.grant())), "{}"));
assertAnsweredByTheService(completed, target);
target.reached().check();
}
@ParameterizedTest
@MethodSource("everyApi")
void anExecutionRoleNotAllowedTheActionIsRefused(String integration) throws Exception {
Target target = target(integration);
Response completed = terminal(start(machine(target, null, role(STATES_TRUST, READ_ONLY)), "{}"));
assertFailed(completed, target.error());
String cause = completed.jsonPath().getString("cause");
assertTrue(cause.contains(target.action()), cause);
assertTrue(cause.contains(target.resourceArn()), cause);
target.notReached().check();
}
@ParameterizedTest
@MethodSource("everyApi")
void theActionOnAnotherResourceDoesNotCount(String integration) throws Exception {
Target target = target(integration);
assumeFalse(ANY_RESOURCE.equals(target.resourceArn()), "the service reference gives it no resource");
String role = role(STATES_TRUST, allow(target.resourceArn() + "-elsewhere", target.action()));
assertFailed(terminal(start(machine(target, null, role), "{}")), target.error());
target.notReached().check();
}
/** {@code *} is what these are evaluated on: a role allowed them only on some ARN is refused. */
@ParameterizedTest
@MethodSource("everyApi")
void anActionWithNoResourceTypeNeedsAGrantOnAnyResource(String integration) throws Exception {
Target target = target(integration);
assumeTrue(ANY_RESOURCE.equals(target.resourceArn()), "the service reference gives it a resource");
String role = role(STATES_TRUST, allow("arn:aws:sns:" + REGION + ":" + ACCOUNT + ":x", target.action()));
assertFailed(terminal(start(machine(target, null, role), "{}")), target.error());
}
@ParameterizedTest
@MethodSource("eachIntegration")
void anExecutionRoleThatDoesNotTrustStepFunctionsIsRefusedWhateverItsPolicies(String integration) throws Exception {
Target target = target(integration);
String role = role(LAMBDA_TRUST, target.grant());
Response completed = terminal(start(machine(target, null, role), "{}"));
assertFailed(completed, "States.Permissions");
assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString());
target.notReached().check();
}
@ParameterizedTest
@MethodSource("eachIntegration")
void anExecutionRoleThatDoesNotExistIsRefused(String integration) throws Exception {
Target target = target(integration);
String role = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID();
assertFailed(terminal(start(machine(target, null, role), "{}")), "States.Permissions");
target.notReached().check();
}
@ParameterizedTest
@MethodSource("eachIntegrationInBothLanguages")
void credentialsReachTheServiceAsTheirRoleWithoutTheExecutionRolesPermission(String integration, String form)
throws Exception {
Target target = target(integration);
String executionRole = role(STATES_TRUST, ASSUME);
String taskRole = role(trusting(executionRole), target.grant());
Map<String, Object> task = "jsonata".equals(form)
? new LinkedHashMap<>(Map.of("Type", "Task", "QueryLanguage", "JSONata",
"Resource", "arn:aws:states:::" + target.integration(), "Arguments", target.arguments(),
"Credentials", Map.of("RoleArn", "{% $states.input.role %}"), "End", true))
: jsonPathTask(target, taskRole);
String execution = start(machine(target, task, executionRole), MAPPER.writeValueAsString(Map.of("role", taskRole)));
assertAnsweredByTheService(terminal(execution), target);
target.reached().check();
assertEquals(taskRole, eventsOfType(execution, "TaskScheduled").getFirst()
.path("taskScheduledEventDetails").path("taskCredentials").path("roleArn").asText());
}
@ParameterizedTest
@MethodSource("eachIntegration")
void aRoleTheExecutionRoleCannotAssumeFailsInTheNestedForm(String integration) throws Exception {
Target target = target(integration);
String executionRole = role(STATES_TRUST, target.grant());
String taskRole = role(STATES_TRUST, target.grant());
Response completed = terminal(start(machine(target, jsonPathTask(target, taskRole), executionRole), "{}"));
assertFailed(completed, "States.TaskFailed");
assertTrue(completed.jsonPath().getString("cause").contains("is not authorized to assume"), completed.asString());
target.notReached().check();
}
@ParameterizedTest
@MethodSource("eachIntegration")
void aCredentialsRoleNotAllowedTheActionIsRefusedEvenIfTheExecutionRoleIs(String integration) throws Exception {
Target target = target(integration);
String executionRole = role(STATES_TRUST, policy(List.of(
Map.of("Effect", "Allow", "Action", List.of(target.action()), "Resource", List.of(target.resourceArn())),
Map.of("Effect", "Allow", "Action", List.of("sts:AssumeRole"), "Resource", List.of("*")))));
String taskRole = role(trusting(executionRole), READ_ONLY);
assertFailed(terminal(start(machine(target, jsonPathTask(target, taskRole), executionRole), "{}")), target.error());
target.notReached().check();
}
@ParameterizedTest
@MethodSource("eachIntegration")
void aRefusalCanBeRetriedAndCaught(String integration) throws Exception {
Target target = target(integration);
Map<String, Object> task = jsonPathTask(target, null);
task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1,
"BackoffRate", 1.0, "MaxAttempts", 1)));
task.put("Catch", List.of(Map.of("ErrorEquals", List.of(target.error()), "Next", "Recovered")));
task.remove("End");
task.put("Next", "Done");
String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task,
"Done", Map.of("Type", "Pass", "End", true), "Recovered", Map.of("Type", "Pass", "End", true))));
String execution = start(machineWithDefinition(target.machineName(), definition, role(STATES_TRUST, READ_ONLY)), "{}");
assertEquals("SUCCEEDED", terminal(execution).jsonPath().getString("status"));
assertEquals(2, eventsOfType(execution, "TaskFailed").size());
assertEquals(target.error(), eventsOfType(execution, "TaskFailed").getLast()
.path("taskFailedEventDetails").path("error").asText());
}
/** Every integration mapped to a permission serves its callback form, and refuses it the same way. */
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"aws-sdk:scheduler:createSchedule|Scheduler.AccessDeniedException|{\"Name\":\"n\"}",
"aws-sdk:scheduler:deleteSchedule|Scheduler.AccessDeniedException|{\"Name\":\"n\"}",
"aws-sdk:cloudformation:listStacks|CloudFormation.AccessDeniedException|{}",
"http:invoke|States.Http.AccessDeniedException|{\"ApiEndpoint\":\"http://localhost:1/\",\"Method\":\"GET\"}",
"aws-sdk:ec2:describeRegions|Ec2.AccessDeniedException|{}",
"aws-sdk:lambda:listEventSourceMappings|Lambda.AccessDeniedException|{}",
"aws-sdk:sfn:describeMapRun|Sfn.AccessDeniedException|{\"MapRunArn\":\"arn:aws:states:us-east-1:000000000472:mapRun:m/l:i\"}",
"states:startExecution|StepFunctions.AccessDeniedException|{\"StateMachineArn\":\"arn:aws:states:us-east-1:000000000472:stateMachine:child\"}",
"sqs:sendMessage|SQS.AccessDeniedException|{\"QueueUrl\":\"q\",\"MessageBody\":\"m\"}",
"aws-sdk:sqs:sendMessage|Sqs.AccessDeniedException|{\"QueueUrl\":\"q\",\"MessageBody\":\"m\"}",
"sns:publish|SNS.AuthorizationErrorException|{\"TopicArn\":\"arn:aws:sns:us-east-1:000000000472:t\"}",
"aws-sdk:sns:publish|Sns.AuthorizationErrorException|{\"TopicArn\":\"arn:aws:sns:us-east-1:000000000472:t\"}",
"events:putEvents|EventBridge.AccessDeniedException|{\"Entries\":[{\"Source\":\"s\"}]}",
"dynamodb:putItem|DynamoDB.AccessDeniedException|{\"TableName\":\"t\"}",
"aws-sdk:dynamodb:putItem|DynamoDb.AccessDeniedException|{\"TableName\":\"t\"}",
"s3:putObject|S3.AccessDeniedException|{\"Bucket\":\"b\",\"Key\":\"k\"}",
"aws-sdk:s3:putObject|S3.AccessDeniedException|{\"Bucket\":\"b\",\"Key\":\"k\"}",
"aws-sdk:rdsdata:executeStatement|RdsData.AccessDeniedException|{\"ResourceArn\":\"arn:aws:rds:us-east-1:000000000472:cluster:c\"}",
"aws-sdk:redshiftdata:listStatements|RedshiftData.AccessDeniedException|{}",
"aws-sdk:ecs:listServices|Ecs.AccessDeniedException|{}"})
void waitForTaskTokenIsRefusedWithoutWaiting(String integration, String error, String arguments) throws Exception {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::" + integration + ".waitForTaskToken",
"Parameters", MAPPER.readValue(arguments, Map.class), "End", true));
assertFailed(terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}")), error);
}
/** With the permission, the callback form calls the service and then waits on its token. */
@ParameterizedTest
@ValueSource(strings = {"aws-sdk:scheduler:createSchedule", "http:invoke", "aws-sdk:ec2:describeRegions",
"states:startExecution"})
void waitForTaskTokenAllowedReachesTheServiceAndWaits(String integration) throws Exception {
Target target = target(integration);
Map<String, Object> task = jsonPathTask(target, null);
task.put("Resource", "arn:aws:states:::" + integration + ".waitForTaskToken");
String execution = start(machine(target, task, role(STATES_TRUST, target.grant())), "{}");
awaiting("the task to start").until(() -> !eventsOfType(execution, "TaskStarted").isEmpty());
target.awaitReached().check();
assertEquals("RUNNING", request("DescribeExecution", Map.of("executionArn", execution))
.jsonPath().getString("status"));
}
/** Not a form EMR serves, whatever the role is allowed. */
@Test
void aFormAnIntegrationDoesNotServeKeepsItsAnswer() throws Exception {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::elasticmapreduce:addStep.waitForTaskToken",
"Parameters", Map.of("ClusterId", "j-X"), "End", true));
Response completed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}"));
assertFailed(completed, "States.TaskFailed");
assertTrue(completed.jsonPath().getString("cause").startsWith("Unsupported resource"), completed.asString());
}
@ParameterizedTest
@ValueSource(strings = {"aws-sdk:scheduler:getSchedule", "aws-sdk:sfn:describeExecution", "aws-sdk:s3:getObject",
"s3:getObject", "dynamodb:query", "aws-sdk:rdsdata:batchExecuteStatement", "aws-sdk:lambda:invoke",
"aws-sdk:secretsmanager:getSecretValue"})
void anApiNoIntegrationServesKeepsItsAnswerForARoleWithNoPermissions(String integration) throws Exception {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::" + integration, "Parameters", Map.of("Name", "n"), "End", true));
Response completed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(LAMBDA_TRUST, READ_ONLY)), "{}"));
assertFailed(completed, "States.TaskFailed");
assertTrue(completed.jsonPath().getString("cause").startsWith("Unsupported"), completed.asString());
}
/** Nested tasks do not refuse an execution role for its trust policy or for not existing as a role: only for the grant. */
@ParameterizedTest
@ValueSource(strings = {"states:startExecution", "states:startExecution.sync", "states:startExecution.sync:2"})
void aNestedTaskWithoutCredentialsNeedsOnlyTheAction(String integration) throws Exception {
Target target = target(integration);
Response completed = terminal(start(machine(target, null, role(LAMBDA_TRUST, target.grant())), "{}"));
assertAnsweredByTheService(completed, target);
target.reached().check();
}
@ParameterizedTest
@ValueSource(strings = {"aws-sdk:sfn:startExecution", "aws-sdk:sfn:startSyncExecution"})
void anSdkStartWithoutCredentialsChecksTrust(String integration) throws Exception {
Target target = target(integration);
assertFailed(terminal(start(machine(target, null, role(LAMBDA_TRUST, target.grant())), "{}")), "States.Permissions");
target.notReached().check();
}
@Test
void aNestedTaskForARoleThatDoesNotExistIsRefusedTheActionAndNotForTheRole() throws Exception {
Target target = target("states:startExecution");
String role = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID();
assertFailed(terminal(start(machine(target, null, role), "{}")), target.error());
target.notReached().check();
}
/** Decided by {@code NestedTaskCredentials} as before: no trust refusal of the execution role, in either form. */
@ParameterizedTest
@ValueSource(strings = {"states:startExecution", "aws-sdk:sfn:startExecution"})
void aNestedTaskWithCredentialsKeepsItsOwnDecision(String integration) throws Exception {
Target target = target(integration);
String executionRole = role(LAMBDA_TRUST, ASSUME);
String taskRole = role(trusting(executionRole), target.grant());
Response completed = terminal(start(machine(target, jsonPathTask(target, taskRole), executionRole), "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
target.reached().check();
}
/** {@code NestedTaskCredentials} does not see the callback form, so it is authorized here, on the Credentials role. */
@ParameterizedTest
@CsvSource({"true,STARTED", "false,REFUSED"})
void aNestedCallbackWithCredentialsIsAuthorizedAsTheirRole(boolean taskRoleAllowed, String outcome) throws Exception {
Target target = target("states:startExecution");
String executionRole = role(LAMBDA_TRUST, ASSUME);
String taskRole = role(trusting(executionRole), taskRoleAllowed ? target.grant() : READ_ONLY);
Map<String, Object> task = jsonPathTask(target, taskRole);
task.put("Resource", "arn:aws:states:::states:startExecution.waitForTaskToken");
String execution = start(machine(target, task, executionRole), "{}");
if ("REFUSED".equals(outcome)) {
assertFailed(terminal(execution), target.error());
target.notReached().check();
} else {
target.awaitReached().check();
}
}
@Test
void aNestedCallbackWithARoleTheExecutionRoleCannotAssumeFailsInTheNestedForm() throws Exception {
Target target = target("states:startExecution");
String executionRole = role(STATES_TRUST, target.grant());
String taskRole = role(STATES_TRUST, target.grant());
Map<String, Object> task = jsonPathTask(target, taskRole);
task.put("Resource", "arn:aws:states:::states:startExecution.waitForTaskToken");
Response completed = terminal(start(machine(target, task, executionRole), "{}"));
assertFailed(completed, "States.TaskFailed");
assertTrue(completed.jsonPath().getString("cause").contains("is not authorized to assume"), completed.asString());
target.notReached().check();
}
/** A nested {@code .sync} needs the starting call alone, not {@code states:DescribeExecution} for its wait. */
@Test
void aNestedSyncTaskNeedsOnlyTheStartingCall() throws Exception {
Target target = target("states:startExecution.sync");
String role = role(STATES_TRUST, allow(target.resourceArn(), "states:StartExecution"));
assertEquals("SUCCEEDED", terminal(start(machine(target, null, role), "{}")).jsonPath().getString("status"));
}
/** The CDK's shape: {@code *} under a {@code StringLike} on the endpoint. */
@ParameterizedTest
@CsvSource({"true,SUCCEEDED", "false,FAILED"})
void anHttpGrantOnAnyResourceIsConditionedOnTheEndpoint(boolean matches, String status) throws Exception {
Target target = target("http:invoke");
String pattern = matches ? httpEndpoint() + "*" : "https://elsewhere.example/*";
String role = role(STATES_TRUST, policy(List.of(Map.of("Effect", "Allow", "Action",
List.of("states:InvokeHTTPEndpoint"), "Resource", List.of("*"),
"Condition", Map.of("StringLike", Map.of("states:HTTPEndpoint", pattern))))));
Response completed = terminal(start(machine(target, null, role), "{}"));
assertEquals(status, completed.jsonPath().getString("status"), completed.asString());
assertEquals(matches ? 1 : 0, HTTP_CALLS.get());
}
/** The Developer Guide's shape: the state machine, under conditions on the endpoint and the method. */
@ParameterizedTest
@CsvSource({"GET,SUCCEEDED", "POST,FAILED"})
void anHttpGrantOnTheStateMachineIsConditionedOnTheMethod(String method, String status) throws Exception {
Target target = target("http:invoke");
String role = role(STATES_TRUST, policy(List.of(Map.of("Effect", "Allow", "Action",
List.of("states:InvokeHTTPEndpoint"), "Resource", List.of(target.resourceArn()),
"Condition", Map.of("StringEquals", Map.of("states:HTTPMethod", method),
"StringLike", Map.of("states:HTTPEndpoint", httpEndpoint() + "*"))))));
assertEquals(status, terminal(start(machine(target, null, role), "{}")).jsonPath().getString("status"));
}
@Test
void anHttpRequestNamingNoEndpointIsLeftToTheIntegration() throws Exception {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task", "Resource", "arn:aws:states:::http:invoke",
"Parameters", Map.of("Method", "GET"), "End", true));
assertFailed(terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}")),
"States.Runtime");
}
/**
* The task reads its Connection to authorize the request, but the connection's own permissions,
* {@code events:RetrieveConnectionCredentials} and its secret's, are not evaluated: a role lacking them succeeds
* here and fails on AWS, whose service reference example grants them.
*/
@Test
void anHttpTaskDoesNotNeedTheConnectionsPermissions() throws Exception {
Target target = target("http:invoke");
Response completed = terminal(start(machine(target, null,
role(STATES_TRUST, allow("*", "states:InvokeHTTPEndpoint"))), "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals(1, HTTP_CALLS.get());
}
/** A stack named by name or by id is the one resource, in the id CloudFormation holds for it. */
@ParameterizedTest
@ValueSource(strings = {"name", "id"})
void aStackIsEvaluatedAsItsStoredId(String form) throws Exception {
String name = "sfn-control-" + UUID.randomUUID();
String stackId = stack(name);
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::aws-sdk:cloudformation:describeStacks",
"Parameters", Map.of("StackName", "id".equals(form) ? stackId : name), "End", true));
Response allowed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task,
role(STATES_TRUST, allow(stackId, "cloudformation:DescribeStacks"))), "{}"));
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
Response refused = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}"));
assertFailed(refused, "CloudFormation.AccessDeniedException");
assertTrue(refused.jsonPath().getString("cause").contains(stackId), refused.asString());
}
/** {@code DescribeStacks} with nothing to name lists every stack, so it is on any resource. */
@Test
void describeStacksNamingNoStackIsOnAnyResource() throws Exception {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::aws-sdk:cloudformation:describeStacks", "End", true));
Response refused = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}"));
assertFailed(refused, "CloudFormation.AccessDeniedException");
Response allowed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task,
role(STATES_TRUST, allow("*", "cloudformation:DescribeStacks"))), "{}"));
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
}
@ParameterizedTest
@CsvSource({"deleteStack,StackName", "describeStackEvents,StackName", "describeStackSet,StackSetName"})
void aStackCloudFormationDoesNotHaveIsLeftToCloudFormation(String api, String member) throws Exception {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::aws-sdk:cloudformation:" + api,
"Parameters", Map.of(member, "no-such-" + UUID.randomUUID()), "End", true));
Response completed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}"));
assertFalse(String.valueOf(completed.jsonPath().getString("error")).endsWith("AccessDeniedException"),
completed.asString());
}
/** A change set's ARN does not hold its stack's name, so the stack is found through it. */
@Test
void aChangeSetNamedByItsArnIsEvaluatedOnItsStack() throws Exception {
String name = "sfn-control-" + UUID.randomUUID();
String stackId = stack(name);
Response changeSet = cloudFormation("CreateChangeSet", Map.of("StackName", name, "ChangeSetName", "c",
"TemplateBody", TEMPLATE));
changeSet.then().statusCode(200);
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::aws-sdk:cloudformation:describeChangeSet",
"Parameters", Map.of("ChangeSetName", changeSet.xmlPath()
.getString("CreateChangeSetResponse.CreateChangeSetResult.Id")), "End", true));
assertStackActionIsEvaluatedOnTheStack(task, stackId, "cloudformation:DescribeChangeSet");
}
@Test
void describeStackResourcesNamingAPhysicalIdIsEvaluatedOnItsStack() throws Exception {
String name = "sfn-control-" + UUID.randomUUID();
String stackId = stack(name);
String physicalId = cloudFormation("ListStackResources", Map.of("StackName", name)).xmlPath()
.getString("ListStackResourcesResponse.ListStackResourcesResult.StackResourceSummaries.member.PhysicalResourceId");
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::aws-sdk:cloudformation:describeStackResources",
"Parameters", Map.of("PhysicalResourceId", physicalId), "End", true));
assertStackActionIsEvaluatedOnTheStack(task, stackId, "cloudformation:DescribeStackResources");
}
private void assertStackActionIsEvaluatedOnTheStack(Map<String, Object> task, String stackId, String action)
throws Exception {
Response refused = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}"));
assertFailed(refused, "CloudFormation.AccessDeniedException");
assertTrue(refused.jsonPath().getString("cause").contains(stackId), refused.asString());
Response allowed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task,
role(STATES_TRUST, allow(stackId, action))), "{}"));
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
}
/** A token that names no task reaches nothing, so Step Functions answers it whatever the role is allowed. */
@Test
void aCallbackWhoseTokenNamesNoTaskIsLeftToStepFunctions() throws Exception {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::aws-sdk:sfn:sendTaskSuccess",
"Parameters", Map.of("TaskToken", "no-such-token", "Output", "{}"), "End", true));
assertFailed(terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}")),
"Sfn.InvalidTokenException");
}
/** A secret named by its name is evaluated on its stored ARN, random suffix included. */
@Test
void aSecretNamedByItsNameIsEvaluatedOnItsStoredArn() throws Exception {
String name = "sfn-control-" + UUID.randomUUID();
String arn = secret(name);
assertFalse(arn.endsWith(name), arn);
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::aws-sdk:secretsmanager:describeSecret",
"Parameters", Map.of("SecretId", name), "End", true));
Response completed = terminal(start(machine("sfn-control-" + UUID.randomUUID(), task,
role(STATES_TRUST, allow(arn, "secretsmanager:DescribeSecret"))), "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
}
/**
* A name no secret goes by is checked as a direct request naming it is, with the random suffix open: a role not
* allowed it is refused, and one allowed it there reaches Secrets Manager, which has no such secret.
*/
@Test
void aSecretNameThatNamesNoSecretIsCheckedWithItsSuffixOpen() throws Exception {
String name = "no-such-" + UUID.randomUUID();
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::aws-sdk:secretsmanager:describeSecret",
"Parameters", Map.of("SecretId", name), "End", true));
String openSuffix = "arn:aws:secretsmanager:" + REGION + ":" + ACCOUNT + ":secret:" + name + "-??????";
assertFailed(terminal(start(machine("sfn-control-" + UUID.randomUUID(), task, role(STATES_TRUST, READ_ONLY)), "{}")),
"SecretsManager.AccessDeniedException");
assertFailed(terminal(start(machine("sfn-control-" + UUID.randomUUID(), task,
role(STATES_TRUST, allow(openSuffix, "secretsmanager:DescribeSecret"))), "{}")),
"SecretsManager.ResourceNotFoundException");
}
private Target target(String integration) throws Exception {
String machine = "sfn-control-" + UUID.randomUUID();
return switch (integration) {
case "aws-sdk:scheduler:createSchedule" -> {
String name = schedule();
cleanup.register(() -> scheduler("DELETE", name, null));
yield target(integration, machine, scheduleRequest(name, "rate(1 hour)"), "scheduler:CreateSchedule",
scheduleArn(name), "Scheduler.AccessDeniedException", null,
() -> assertEquals(200, scheduler("GET", name, null).statusCode()),
() -> assertEquals(404, scheduler("GET", name, null).statusCode()));
}
case "aws-sdk:scheduler:updateSchedule" -> {
String name = existingSchedule();
yield target(integration, machine, scheduleRequest(name, "rate(2 hours)"), "scheduler:UpdateSchedule",
scheduleArn(name), "Scheduler.AccessDeniedException", null,
() -> assertEquals("rate(2 hours)", scheduler("GET", name, null).jsonPath().getString("ScheduleExpression")),
() -> assertEquals("rate(1 hour)", scheduler("GET", name, null).jsonPath().getString("ScheduleExpression")));
}
case "aws-sdk:scheduler:deleteSchedule" -> {
String name = existingSchedule();
yield target(integration, machine, Map.of("Name", name), "scheduler:DeleteSchedule", scheduleArn(name),
"Scheduler.AccessDeniedException", null,
() -> assertEquals(404, scheduler("GET", name, null).statusCode()),
() -> assertEquals(200, scheduler("GET", name, null).statusCode()));
}
case "aws-sdk:cloudformation:createStack" -> {
String name = "sfn-control-" + UUID.randomUUID();
cleanup.register(() -> cloudFormation("DeleteStack", Map.of("StackName", name)));
yield target(integration, machine, Map.of("StackName", name, "TemplateBody", TEMPLATE),
"cloudformation:CreateStack", "arn:aws:cloudformation:" + REGION + ":" + ACCOUNT + ":stack/" + name + "/*",
"CloudFormation.AccessDeniedException", null,
() -> assertEquals(200, cloudFormation("DescribeStacks", Map.of("StackName", name)).statusCode()),
() -> assertEquals(400, cloudFormation("DescribeStacks", Map.of("StackName", name)).statusCode()));
}
case "aws-sdk:cloudformation:describeStacks" -> {
String name = "sfn-control-" + UUID.randomUUID();
yield target(integration, machine, Map.of("StackName", name), "cloudformation:DescribeStacks", stack(name),
"CloudFormation.AccessDeniedException", null, NOTHING_TO_READ, NOTHING_TO_READ);
}
case "aws-sdk:cloudformation:deleteStack" -> {
String name = "sfn-control-" + UUID.randomUUID();
String id = stack(name);
yield target(integration, machine, Map.of("StackName", name), "cloudformation:DeleteStack", id,
"CloudFormation.AccessDeniedException", null,
() -> awaiting("the stack to go").until(() -> !stackLive(name)), () -> assertTrue(stackLive(name)));
}
case "aws-sdk:cloudformation:listStacks" -> target(integration, machine, Map.of(), "cloudformation:ListStacks",
ANY_RESOURCE, "CloudFormation.AccessDeniedException", null, NOTHING_TO_READ, NOTHING_TO_READ);
case "aws-sdk:cloudformation:describeStackSet" -> {
String name = "sfn-control-" + UUID.randomUUID();
yield target(integration, machine, Map.of("StackSetName", name), "cloudformation:DescribeStackSet",
stackSet(name), "CloudFormation.AccessDeniedException", null, NOTHING_TO_READ, NOTHING_TO_READ);
}
case "aws-sdk:cloudformation:createStackSet" -> {
String name = "sfn-control-" + UUID.randomUUID();
cleanup.register(() -> cloudFormation("DeleteStackSet", Map.of("StackSetName", name)));
yield target(integration, machine, Map.of("StackSetName", name, "TemplateBody", TEMPLATE),
"cloudformation:CreateStackSet", ANY_RESOURCE, "CloudFormation.AccessDeniedException", null,
() -> assertEquals(200, cloudFormation("DescribeStackSet", Map.of("StackSetName", name)).statusCode()),
() -> assertEquals(404, cloudFormation("DescribeStackSet", Map.of("StackSetName", name)).statusCode()));
}
case "http:invoke" -> target(integration, machine, Map.of("ApiEndpoint", httpEndpoint(), "Method", "GET",
"InvocationConfig", Map.of("ConnectionArn", connection())),
"states:InvokeHTTPEndpoint", machineArn(machine), "States.Http.AccessDeniedException", null,
() -> assertEquals(1, HTTP_CALLS.get()), () -> assertEquals(0, HTTP_CALLS.get()));
case "aws-sdk:ec2:describeRegions" -> target(integration, machine, Map.of(), "ec2:DescribeRegions", ANY_RESOURCE,
"Ec2.AccessDeniedException", null, NOTHING_TO_READ, NOTHING_TO_READ);
case "aws-sdk:lambda:listEventSourceMappings" -> target(integration, machine, Map.of(),
"lambda:ListEventSourceMappings", ANY_RESOURCE, "Lambda.AccessDeniedException", null,
NOTHING_TO_READ, NOTHING_TO_READ);
case "aws-sdk:lambda:updateEventSourceMapping" -> {
String uuid = UUID.randomUUID().toString();
yield target(integration, machine, Map.of("Uuid", uuid, "BatchSize", 1), "lambda:UpdateEventSourceMapping",
"arn:aws:lambda:" + REGION + ":" + ACCOUNT + ":event-source-mapping:" + uuid,
"Lambda.AccessDeniedException", "Lambda.ResourceNotFoundException", NOTHING_TO_READ, NOTHING_TO_READ);
}
case "aws-sdk:secretsmanager:describeSecret" -> {
String name = "sfn-control-" + UUID.randomUUID();
yield target(integration, machine, Map.of("SecretId", name), "secretsmanager:DescribeSecret", secret(name),
"SecretsManager.AccessDeniedException", null, NOTHING_TO_READ, NOTHING_TO_READ);
}
case "aws-sdk:sfn:startExecution" -> childTarget(integration, machine, "states:StartExecution", "Sfn.", "STANDARD");
case "aws-sdk:sfn:startSyncExecution" -> childTarget(integration, machine, "states:StartSyncExecution", "Sfn.", "EXPRESS");
case "states:startExecution", "states:startExecution.sync", "states:startExecution.sync:2" ->
childTarget(integration, machine, "states:StartExecution", "StepFunctions.", "STANDARD");
case "aws-sdk:sfn:sendTaskSuccess" -> callbackTarget(integration, machine, "states:SendTaskSuccess",
Map.of("Output", "{}"), "SUCCEEDED");
case "aws-sdk:sfn:sendTaskFailure" -> callbackTarget(integration, machine, "states:SendTaskFailure",
Map.of("Error", "Boom"), "FAILED");
case "aws-sdk:sfn:describeMapRun" -> {
String mapRun = "arn:aws:states:" + REGION + ":" + ACCOUNT + ":mapRun:" + machine + "/label:" + UUID.randomUUID();
yield target(integration, machine, Map.of("MapRunArn", mapRun), "states:DescribeMapRun", mapRun,
"Sfn.AccessDeniedException", "Sfn.ResourceNotFoundException", NOTHING_TO_READ, NOTHING_TO_READ);
}
default -> throw new IllegalArgumentException(integration);
};
}
private Target childTarget(String integration, String machine, String action, String prefix, String type) {
String child = "sfn-control-child-" + UUID.randomUUID();
String arn = machineWithDefinition(child, CHILD_DEFINITION, role(STATES_TRUST, READ_ONLY), type);
Check notStarted = () -> assertEquals(0, executions(arn));
Check started = () -> assertEquals(1, executions(arn));
return "EXPRESS".equals(type)
? target(integration, machine, Map.of("StateMachineArn", arn), action, arn, prefix + "AccessDeniedException",
null, NOTHING_TO_READ, NOTHING_TO_READ)
: target(integration, machine, Map.of("StateMachineArn", arn), action, arn, prefix + "AccessDeniedException",
null, started, notStarted);
}
/** A waiting execution and the token of its activity task, which AWS authorizes a callback on. */
private Target callbackTarget(String integration, String machine, String action, Map<String, Object> arguments,
String finished) throws Exception {
String activityName = "sfn-control-" + UUID.randomUUID();
Response activity = request("CreateActivity", Map.of("name", activityName));
activity.then().statusCode(200);
String activityArn = activity.jsonPath().getString("activityArn");
cleanup.register(() -> request("DeleteActivity", Map.of("activityArn", activityArn)));
String waiting = start(machine("sfn-control-" + UUID.randomUUID(), new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", activityArn, "End", true)), role(STATES_TRUST, READ_ONLY)), "{}");
Response task = request("GetActivityTask", Map.of("activityArn", activityArn));
task.then().statusCode(200);
Map<String, Object> request = new LinkedHashMap<>(arguments);
request.put("TaskToken", task.jsonPath().getString("taskToken"));
return target(integration, machine, request, action, activityArn, "Sfn.AccessDeniedException", null,
() -> assertEquals(finished, terminal(waiting).jsonPath().getString("status")),
() -> assertEquals("RUNNING", request("DescribeExecution", Map.of("executionArn", waiting))
.jsonPath().getString("status")));
}
private static Target target(String integration, String machine, Map<String, ?> arguments, String action,
String resourceArn, String error, String serviceError, Check reached, Check notReached) {
return new Target(integration, machine, arguments, action, resourceArn, error, serviceError, reached, notReached);
}
private record Target(String integration, String machineName, Map<String, ?> arguments, String action,
String resourceArn, String error, String serviceError, Check reached, Check notReached) {
String grant() {
return allow(resourceArn, action);
}
/** {@link #reached}, for a task whose execution has not finished: the call happens after the task starts. */
Check awaitReached() {
return () -> await("the task to reach its service").atMost(Duration.ofSeconds(10))
.pollInterval(Duration.ofMillis(50)).untilAsserted(reached::check);
}
}
@FunctionalInterface
private interface Check {
void check() throws Exception;
}
private static void assertAnsweredByTheService(Response completed, Target target) {
if (target.serviceError() == null) {
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
} else {
assertFailed(completed, target.serviceError());
}
}
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 String httpEndpoint() {
return "http://localhost:" + httpServer.getAddress().getPort() + "/control";
}
private static String schedule() {
return "sfn-control-" + UUID.randomUUID();
}
private String existingSchedule() {
String name = schedule();
scheduler("POST", name, scheduleRequest(name, "rate(1 hour)")).then().statusCode(200);
cleanup.register(() -> scheduler("DELETE", name, null));
return name;
}
private static Map<String, Object> scheduleRequest(String name, String expression) {
return Map.of("Name", name, "ScheduleExpression", expression, "FlexibleTimeWindow", Map.of("Mode", "OFF"),
"Target", Map.of("Arn", "arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":q",
"RoleArn", "arn:aws:iam::" + ACCOUNT + ":role/scheduler"));
}
private static String scheduleArn(String name) {
return "arn:aws:scheduler:" + REGION + ":" + ACCOUNT + ":schedule/default/" + name;
}
private Response scheduler(String method, String name, Map<String, ?> body) {
RequestSpecification spec = given().port(baseUri.getPort())
.header("Authorization", auth(ACCOUNT, "scheduler")).contentType("application/json");
if (body != null) {
spec = spec.body(MAPPER.valueToTree(body).toString());
}
return spec.request(method, "/schedules/" + name);
}
private String stack(String name) throws Exception {
Response created = cloudFormation("CreateStack", Map.of("StackName", name, "TemplateBody", TEMPLATE));
created.then().statusCode(200);
cleanup.register(() -> cloudFormation("DeleteStack", Map.of("StackName", name)));
awaiting("stack " + name).until(() -> cloudFormation("DescribeStacks", Map.of("StackName", name)).asString()
.contains("CREATE_COMPLETE"));
return created.xmlPath().getString("CreateStackResponse.CreateStackResult.StackId");
}
private boolean stackLive(String name) {
return cloudFormation("DescribeStacks", Map.of("StackName", name)).statusCode() == 200;
}
private String stackSet(String name) {
cloudFormation("CreateStackSet", Map.of("StackSetName", name, "TemplateBody", TEMPLATE)).then().statusCode(200);
cleanup.register(() -> cloudFormation("DeleteStackSet", Map.of("StackSetName", name)));
String id = cloudFormation("DescribeStackSet", Map.of("StackSetName", name)).xmlPath()
.getString("DescribeStackSetResponse.DescribeStackSetResult.StackSet.StackSetId");
return "arn:aws:cloudformation:" + REGION + ":" + ACCOUNT + ":stackset/" + id;
}
private Response cloudFormation(String action, Map<String, String> parameters) {
return given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "cloudformation"))
.contentType("application/x-www-form-urlencoded").formParam("Action", action)
.formParam("Version", "2010-05-15").formParams(parameters).post("/");
}
private String secret(String name) {
Response created = given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "secretsmanager"))
.header("X-Amz-Target", "secretsmanager.CreateSecret").contentType("application/x-amz-json-1.1")
.body(MAPPER.valueToTree(Map.of("Name", name, "SecretString", "s")).toString()).post("/");
created.then().statusCode(200);
cleanup.register(() -> given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "secretsmanager"))
.header("X-Amz-Target", "secretsmanager.DeleteSecret").contentType("application/x-amz-json-1.1")
.body(MAPPER.valueToTree(Map.of("SecretId", name, "ForceDeleteWithoutRecovery", true)).toString()).post("/"));
return created.jsonPath().getString("ARN");
}
private String connection() {
String name = "sfn-control-" + UUID.randomUUID();
Response created = given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "events"))
.header("X-Amz-Target", "AWSEvents.CreateConnection").contentType("application/x-amz-json-1.1")
.body(MAPPER.valueToTree(Map.of("Name", name, "AuthorizationType", "API_KEY", "AuthParameters",
Map.of("ApiKeyAuthParameters", Map.of("ApiKeyName", "x-api-key", "ApiKeyValue", "k")))).toString())
.post("/");
created.then().statusCode(200);
cleanup.register(() -> given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "events"))
.header("X-Amz-Target", "AWSEvents.DeleteConnection").contentType("application/x-amz-json-1.1")
.body(MAPPER.valueToTree(Map.of("Name", name)).toString()).post("/"));
return created.jsonPath().getString("ConnectionArn");
}
private int executions(String stateMachine) {
return request("ListExecutions", Map.of("stateMachineArn", stateMachine)).jsonPath().getList("executions").size();
}
private static Map<String, Object> jsonPathTask(Target target, String taskRole) {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::" + target.integration(), "Parameters", target.arguments(), "End", true));
if (taskRole != null) {
task.put("Credentials", Map.of("RoleArn", taskRole));
}
return task;
}
private static String allow(String resource, String... actions) {
return policy(List.of(Map.of("Effect", "Allow", "Action", List.of(actions), "Resource", List.of(resource))));
}
private static String policy(List<Map<String, Object>> statements) {
try {
return MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", statements));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private String role(String trust, String policy) {
return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/",
"sfn-control-" + UUID.randomUUID(), trust, policy);
}
private static String machineArn(String name) {
return "arn:aws:states:" + REGION + ":" + ACCOUNT + ":stateMachine:" + name;
}
private String machine(Target target, Map<String, Object> task, String role) throws Exception {
return machine(target.machineName(), task != null ? task : jsonPathTask(target, null), role);
}
private String machine(String name, Map<String, Object> task, String role) throws Exception {
return machineWithDefinition(name, MAPPER.writeValueAsString(
Map.of("StartAt", "Send", "States", Map.of("Send", task))), role);
}
private String machineWithDefinition(String name, String definition, String role) {
return machineWithDefinition(name, definition, role, "STANDARD");
}
private String machineWithDefinition(String name, String definition, String role, String type) {
return sfn().createMachineNamed(ACCOUNT, name, definition, type, role);
}
private String start(String machine, String input) {
return sfn().start(ACCOUNT, machine, input);
}
private Response terminal(String execution) throws Exception {
return sfn().terminal(ACCOUNT, execution, 20);
}
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);
}
/** Polls for {@code what} as long and as often as the task tests allow a background start. */
private static ConditionFactory awaiting(String what) {
return await(what).atMost(Duration.ofSeconds(30)).pollInterval(Duration.ofMillis(50));
}
}
@@ -319,6 +319,22 @@ class StepFunctionsTaskCredentialsIntegrationTest {
assertDataTaskIsNotEvaluated(integration, arguments, status);
}
/** Past authorization, the service answers: these name what it does not have, or nothing it needs. */
@ParameterizedTest
@CsvSource(delimiter = '|', value = {"aws-sdk:scheduler:deleteSchedule|{\"Name\":\"no-such-schedule\"}|FAILED",
"aws-sdk:cloudformation:listStacks|{}|SUCCEEDED",
"aws-sdk:cloudformation:describeStacks|{\"StackName\":\"no-such-stack\"}|FAILED",
"http:invoke|{\"Method\":\"GET\"}|FAILED",
"aws-sdk:ec2:describeRegions|{}|SUCCEEDED",
"aws-sdk:lambda:listEventSourceMappings|{}|SUCCEEDED",
"aws-sdk:secretsmanager:describeSecret|{\"SecretId\":\"no-such-secret\"}|FAILED",
"aws-sdk:sfn:describeMapRun|{\"MapRunArn\":\"arn:aws:states:us-east-1:000000000001:mapRun:m/l:i\"}|FAILED",
"aws-sdk:sfn:sendTaskSuccess|{\"TaskToken\":\"no-such-token\"}|FAILED"})
void controlCredentialsRetainDefaultIamDisabledBehavior(String integration, String arguments, String status)
throws Exception {
assertDataTaskIsNotEvaluated(integration, MAPPER.readValue(arguments, Map.class), status);
}
private void assertDataTaskIsNotEvaluated(String integration, Map<String, Object> arguments, String status)
throws Exception {
String taskRole = "arn:aws:iam::" + TARGET + ":role/no-such-role";
@@ -2,7 +2,9 @@ package io.floci.aws.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.cloudformation.CloudFormationQueryHandler;
import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission;
import io.floci.aws.services.stepfunctions.model.StateMachine;
import org.junit.jupiter.api.Test;
@@ -10,11 +12,18 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -70,8 +79,7 @@ class TaskPermissionsTest {
@ParameterizedTest
@ValueSource(strings = {"lambda:invoke", "apigateway:invoke", "aws-sdk:sqs:receiveMessage", "aws-sdk:sns:listTopics",
"sns:publishBatch", "aws-sdk:eventbridge:putEvents", "events:listRules", "states:startExecution",
"dynamodb:query", "http:invoke"})
"sns:publishBatch", "aws-sdk:eventbridge:putEvents", "events:listRules", "dynamodb:query"})
void integrationsNotMappedStayUnchecked(String integration) {
assertEquals(Optional.empty(), TaskPermissions.of(integration(integration), input("orders"), machine("aws")));
}
@@ -607,6 +615,326 @@ class TaskPermissionsTest {
.orElseThrow().permissions());
}
private static final String STACK = "arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stack/s/id";
private static TaskPermissions control(String tail, String request, CloudFormationQueryHandler cloudFormation,
StoredResourceArns secrets, StoredResourceArns states,
boolean callback) throws Exception {
return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, null, callback,
new TaskPermissions.ControlServices(cloudFormation, secrets, states)).orElseThrow();
}
private static TaskPermissions control(String tail, String request) throws Exception {
return control(tail, request, null, null, null, false);
}
private static CloudFormationQueryHandler stacks() {
CloudFormationQueryHandler handler = mock(CloudFormationQueryHandler.class);
when(handler.stackId(any(), any())).thenReturn(Optional.empty());
when(handler.stackId("s", "eu-west-1")).thenReturn(Optional.of(STACK));
when(handler.stackId(STACK, "eu-west-1")).thenReturn(Optional.of(STACK));
when(handler.stackIdOfChangeSet(any(), any())).thenReturn(Optional.empty());
when(handler.stackIdOfResource(any(), any())).thenReturn(Optional.empty());
when(handler.stackSetId(any())).thenReturn(Optional.empty());
when(handler.stackSetId("ss")).thenReturn(Optional.of("ss:id"));
return handler;
}
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"createSchedule|{\"Name\":\"n\"}|scheduler:CreateSchedule|schedule/default/n",
"updateSchedule|{\"Name\":\"n\",\"GroupName\":\"g\"}|scheduler:UpdateSchedule|schedule/g/n",
"deleteSchedule|{\"Name\":\"n\",\"GroupName\":\" \"}|scheduler:DeleteSchedule|schedule/default/n"})
void aScheduleIsCheckedInItsGroup(String api, String request, String action, String resource) throws Exception {
TaskPermissions permissions = control("aws-sdk:scheduler:" + api, request);
assertEquals("Scheduler.AccessDeniedException", permissions.deniedError());
assertEquals(List.of(new Permission(action, "arn:aws:scheduler:eu-west-1:" + ACCOUNT + ":" + resource)),
permissions.permissions());
}
@Test
void aScheduleRequestNamingNoScheduleNeedsNoPermission() throws Exception {
assertEquals(List.of(), control("aws-sdk:scheduler:deleteSchedule", "{\"GroupName\":\"g\"}").permissions());
}
@ParameterizedTest
@ValueSource(strings = {"aws-sdk:scheduler:getSchedule", "aws-sdk:scheduler:listSchedules",
"aws-sdk:cloudformation:describeTypeRegistration", "aws-sdk:sfn:describeExecution", "aws-sdk:sfn:stopExecution",
"aws-sdk:ec2:describeInstances", "aws-sdk:lambda:invoke", "aws-sdk:secretsmanager:getSecretValue",
"aws-sdk:s3:getObject", "s3:getObject", "aws-sdk:s3:listObjectsV2", "dynamodb:query",
"aws-sdk:rdsdata:batchExecuteStatement", "http:get", "elasticmapreduce:describeCluster"})
void anApiNoIntegrationServesIsNotChecked(String tail) throws Exception {
assertEquals(Optional.empty(), TaskPermissions.of(integration(tail), json("{}"), machine("aws"), null, null, false,
new TaskPermissions.ControlServices(null, null, null)));
}
/** A new case in the handler has to name its resource type here, or it would run unchecked under enforcement. */
@Test
void everyActionTheCloudFormationHandlerServesIsChecked() throws Exception {
String handler = Files.readString(Path.of("src/main/java/io/floci/aws/services/cloudformation/"
+ "CloudFormationQueryHandler.java"));
Matcher action = Pattern.compile("case \"([A-Za-z]+)\" -> ").matcher(handler);
int actions = 0;
while (action.find()) {
actions++;
String api = Character.toLowerCase(action.group(1).charAt(0)) + action.group(1).substring(1);
assertTrue(TaskPermissions.of(integration("aws-sdk:cloudformation:" + api), json("{}"), machine("aws"), null,
null, false, new TaskPermissions.ControlServices(null, null, null)).isPresent(), action.group(1));
}
assertEquals(36, actions);
}
@ParameterizedTest
@ValueSource(strings = {"validateTemplate", "listStacks", "listExports", "describeOrganizationsAccess",
"activateOrganizationsAccess", "createStackSet", "listStackSets"})
void aCloudFormationActionWithNoResourceTypeIsOnAnyResource(String api) throws Exception {
assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), "*")),
control("aws-sdk:cloudformation:" + api, "{}").permissions());
}
@ParameterizedTest
@ValueSource(strings = {"updateStack", "deleteStack", "continueUpdateRollback", "updateTerminationProtection",
"createChangeSet", "describeChangeSet", "executeChangeSet", "deleteChangeSet", "listChangeSets",
"describeStackEvents", "describeStackResources", "listStackResources", "describeStackResource", "getTemplate",
"setStackPolicy", "getStackPolicy", "describeStacks", "getTemplateSummary", "createStack"})
void aCloudFormationStackActionIsOnTheStackAsCloudFormationHoldsIt(String api) throws Exception {
for (String named : List.of("s", STACK)) {
TaskPermissions permissions = control("aws-sdk:cloudformation:" + api,
"{\"StackName\":\"" + named + "\"}", stacks(), null, null, false);
assertEquals("CloudFormation.AccessDeniedException", permissions.deniedError());
assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), STACK)),
permissions.permissions(), named);
}
}
@ParameterizedTest
@ValueSource(strings = {"createStack", "createChangeSet"})
void aStackNotThereYetHasItsIdOpenForWhatCreatesIt(String api) throws Exception {
assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api),
"arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stack/new/*")),
control("aws-sdk:cloudformation:" + api, "{\"StackName\":\"new\"}", stacks(), null, null, false).permissions());
}
@ParameterizedTest
@ValueSource(strings = {"updateStack", "deleteStack", "describeStacks", "describeChangeSet", "getTemplateSummary"})
void aStackCloudFormationDoesNotHaveNamesNothing(String api) throws Exception {
assertEquals(List.of(), control("aws-sdk:cloudformation:" + api, "{\"StackName\":\"none\"}", stacks(), null, null, false)
.permissions());
}
@Test
void anUnknownStackIdNeverOpensAnIdEvenToCreate() throws Exception {
assertEquals(List.of(), control("aws-sdk:cloudformation:createStack",
"{\"StackName\":\"arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stack/none/id\"}", stacks(), null, null, false)
.permissions());
}
@ParameterizedTest
@ValueSource(strings = {"describeStacks", "getTemplateSummary"})
void aCloudFormationActionWithAnOptionalStackIsOnAnyResourceWithoutOne(String api) throws Exception {
assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), "*")),
control("aws-sdk:cloudformation:" + api, "{}", stacks(), null, null, false).permissions());
}
@ParameterizedTest
@ValueSource(strings = {"describeChangeSet", "executeChangeSet", "deleteChangeSet"})
void aChangeSetArnFindsItsStack(String api) throws Exception {
CloudFormationQueryHandler handler = stacks();
when(handler.stackIdOfChangeSet("arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":changeSet/c/1", "eu-west-1"))
.thenReturn(Optional.of(STACK));
assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api), STACK)),
control("aws-sdk:cloudformation:" + api,
"{\"ChangeSetName\":\"arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":changeSet/c/1\"}",
handler, null, null, false).permissions());
assertEquals(List.of(), control("aws-sdk:cloudformation:" + api, "{\"ChangeSetName\":\"c\"}",
handler, null, null, false).permissions());
}
@Test
void describeStackResourcesFindsTheStackOfThePhysicalId() throws Exception {
CloudFormationQueryHandler handler = stacks();
when(handler.stackIdOfResource("r-1", "eu-west-1")).thenReturn(Optional.of(STACK));
assertEquals(List.of(new Permission("cloudformation:DescribeStackResources", STACK)),
control("aws-sdk:cloudformation:describeStackResources", "{\"PhysicalResourceId\":\"r-1\"}",
handler, null, null, false).permissions());
assertEquals(List.of(), control("aws-sdk:cloudformation:listStackResources", "{\"PhysicalResourceId\":\"r-1\"}",
handler, null, null, false).permissions());
}
@ParameterizedTest
@ValueSource(strings = {"describeStackSet", "updateStackSet", "deleteStackSet", "createStackInstances",
"listStackInstances", "describeStackInstance", "deleteStackInstances", "listStackSetOperations",
"describeStackSetOperation", "listStackSetAutoDeploymentTargets"})
void aStackSetActionIsOnTheStackSetAsCloudFormationHoldsIt(String api) throws Exception {
assertEquals(List.of(new Permission("cloudformation:" + AslExecutor.capitalizeFirst(api),
"arn:aws:cloudformation:eu-west-1:" + ACCOUNT + ":stackset/ss:id")),
control("aws-sdk:cloudformation:" + api, "{\"StackSetName\":\"ss\"}", stacks(), null, null, false).permissions());
assertEquals(List.of(), control("aws-sdk:cloudformation:" + api, "{\"StackSetName\":\"none\"}",
stacks(), null, null, false).permissions());
}
@Test
void anHttpTaskIsOnTheStateMachineWithItsEndpointAndMethodAsConditionKeys() throws Exception {
TaskPermissions permissions = control("http:invoke", "{\"ApiEndpoint\":\"https://a.example/x\",\"Method\":\"PUT\"}");
assertEquals("States.Http.AccessDeniedException", permissions.deniedError());
assertEquals(List.of(new Permission("states:InvokeHTTPEndpoint", machine("aws").getStateMachineArn(),
Map.of("states:HTTPEndpoint", List.of("https://a.example/x"), "states:HTTPMethod", List.of("PUT")))),
permissions.permissions());
}
@Test
void anHttpTaskWithNoMethodHasOnlyTheEndpointKey() throws Exception {
assertEquals(Map.of("states:HTTPEndpoint", List.of("https://a.example/x")),
control("http:invoke", "{\"ApiEndpoint\":\"https://a.example/x\"}").permissions().getFirst().conditionKeys());
}
@ParameterizedTest
@ValueSource(strings = {"{}", "{\"ApiEndpoint\":\" \"}", "{\"ApiEndpoint\":7}", "{\"Method\":\"GET\"}"})
void anHttpTaskNamingNoEndpointNeedsNoPermission(String request) throws Exception {
assertEquals(List.of(), control("http:invoke", request).permissions());
}
@Test
void describeRegionsIsOnAnyResource() throws Exception {
TaskPermissions permissions = control("aws-sdk:ec2:describeRegions", "{}");
assertEquals("Ec2.AccessDeniedException", permissions.deniedError());
assertEquals(List.of(new Permission("ec2:DescribeRegions", "*")), permissions.permissions());
}
@Test
void lambdaMappingsAreCheckedAsTheServiceReferenceGivesThem() throws Exception {
TaskPermissions list = control("aws-sdk:lambda:listEventSourceMappings", "{\"FunctionName\":\"f\"}");
assertEquals("Lambda.AccessDeniedException", list.deniedError());
assertEquals(List.of(new Permission("lambda:ListEventSourceMappings", "*")), list.permissions());
assertEquals(List.of(new Permission("lambda:UpdateEventSourceMapping",
"arn:aws:lambda:eu-west-1:" + ACCOUNT + ":event-source-mapping:u-2")),
control("aws-sdk:lambda:updateEventSourceMapping", "{\"Uuid\":\"u-2\"}").permissions());
assertEquals(List.of(), control("aws-sdk:lambda:updateEventSourceMapping", "{}").permissions());
assertEquals(List.of(), control("aws-sdk:lambda:updateEventSourceMapping", "{\"UUID\":\"u-1\"}").permissions());
}
/**
* The check a direct {@code DescribeSecret} gets: the secret Secrets Manager stores a name under, random suffix
* included; a name it stores nothing under, with the suffix open; and another account's ARN as given and as the
* caller's own of that name.
*/
@Test
void aSecretIsCheckedAsADirectRequestChecksIt() throws Exception {
String stored = "arn:aws:secretsmanager:eu-west-1:" + ACCOUNT + ":secret:s-AbCdEf";
String foreign = "arn:aws:secretsmanager:eu-west-1:444455556666:secret:o-AbCdEf";
StoredResourceArns secrets = new StoredResourceArns() {
@Override
public String namespace() {
return "secretsmanager";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return List.of("s").equals(names) ? Optional.of(stored) : Optional.empty();
}
};
TaskPermissions named = control("aws-sdk:secretsmanager:describeSecret", "{\"SecretId\":\"s\"}", null, secrets,
null, false);
assertEquals("SecretsManager.AccessDeniedException", named.deniedError());
assertEquals(List.of(new Permission("secretsmanager:DescribeSecret", stored)), named.permissions());
assertEquals(List.of(new Permission("secretsmanager:DescribeSecret", foreign),
new Permission("secretsmanager:DescribeSecret",
"arn:aws:secretsmanager:eu-west-1:" + ACCOUNT + ":secret:o-AbCdEf")),
control("aws-sdk:secretsmanager:describeSecret", "{\"SecretId\":\"" + foreign + "\"}", null, secrets,
null, false).permissions());
assertEquals(List.of(new Permission("secretsmanager:DescribeSecret",
"arn:aws:secretsmanager:eu-west-1:" + ACCOUNT + ":secret:none-??????")),
control("aws-sdk:secretsmanager:describeSecret", "{\"SecretId\":\"none\"}", null, secrets, null, false)
.permissions());
assertEquals(List.of(),
control("aws-sdk:secretsmanager:describeSecret", "{}", null, secrets, null, false).permissions());
}
@ParameterizedTest
@CsvSource({"startExecution,states:StartExecution", "startSyncExecution,states:StartSyncExecution"})
void anSdkStartIsCheckedOnTheChildWithTheExecutionRoleChecks(String api, String action) throws Exception {
String child = "arn:aws:states:eu-west-1:" + ACCOUNT + ":stateMachine:c";
TaskPermissions permissions = control("aws-sdk:sfn:" + api, "{\"StateMachineArn\":\"" + child + "\"}");
assertEquals("Sfn.AccessDeniedException", permissions.deniedError());
assertTrue(permissions.checksExecutionRole());
assertEquals(List.of(new Permission(action, child)), permissions.permissions());
}
@ParameterizedTest
@ValueSource(strings = {"states:startExecution", "states:startExecution.sync", "states:startExecution.sync:2"})
void aNestedStartIsCheckedOnTheChildWithoutTheExecutionRoleChecks(String tail) throws Exception {
String child = "arn:aws:states:eu-west-1:" + ACCOUNT + ":stateMachine:c";
TaskPermissions permissions = control(tail, "{\"StateMachineArn\":\"" + child + "\"}");
assertEquals("StepFunctions.AccessDeniedException", permissions.deniedError());
assertFalse(permissions.checksExecutionRole());
assertEquals(List.of(new Permission("states:StartExecution", child)), permissions.permissions());
}
@Test
void aStartNamingAVersionIsCheckedOnTheStateMachineAndOneNamingNothingNeedsNoPermission() throws Exception {
String child = "arn:aws:states:eu-west-1:" + ACCOUNT + ":stateMachine:c";
assertEquals(List.of(new Permission("states:StartExecution", child)),
control("states:startExecution", "{\"StateMachineArn\":\"" + child + ":3\"}").permissions());
assertEquals(List.of(), control("states:startExecution", "{}").permissions());
assertEquals(List.of(), control("aws-sdk:sfn:startExecution", "{\"StateMachineArn\":\"not-an-arn\"}").permissions());
}
@ParameterizedTest
@CsvSource({"sendTaskSuccess,states:SendTaskSuccess", "sendTaskFailure,states:SendTaskFailure"})
void aCallbackIsCheckedOnWhatItsTokenWaitsIn(String api, String action) throws Exception {
String activity = "arn:aws:states:eu-west-1:" + ACCOUNT + ":activity:a";
StoredResourceArns states = new StoredResourceArns() {
@Override
public String namespace() {
return "states";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
@Override
public Optional<String> findByMembers(String type, List<String> names, String region) {
if (!"t-1".equals(names.getFirst())) {
throw new AwsException("InvalidToken", "Invalid Token", 400);
}
return Optional.of(activity);
}
};
assertEquals(List.of(new Permission(action, activity)),
control("aws-sdk:sfn:" + api, "{\"TaskToken\":\"t-1\"}", null, null, states, false).permissions());
assertEquals(List.of(), control("aws-sdk:sfn:" + api, "{\"TaskToken\":\"gone\"}", null, null, states, false).permissions());
}
@Test
void describeMapRunIsOnTheMapRun() throws Exception {
String mapRun = "arn:aws:states:eu-west-1:" + ACCOUNT + ":mapRun:m/label:id";
assertEquals(List.of(new Permission("states:DescribeMapRun", mapRun)),
control("aws-sdk:sfn:describeMapRun", "{\"MapRunArn\":\"" + mapRun + "\"}").permissions());
}
/** {@code executeTaskState} strips the suffix, so each of these arrives bare, with a token, and is mapped as itself. */
@ParameterizedTest
@ValueSource(strings = {"aws-sdk:scheduler:createSchedule", "aws-sdk:cloudformation:listStacks", "http:invoke",
"aws-sdk:ec2:describeRegions", "aws-sdk:lambda:listEventSourceMappings",
"aws-sdk:secretsmanager:describeSecret", "aws-sdk:sfn:startExecution", "states:startExecution"})
void aCallbackFormIsMappedAsTheBareForm(String tail) throws Exception {
String request = "{\"Name\":\"n\",\"ApiEndpoint\":\"https://a.example/\",\"StateMachineArn\":"
+ "\"arn:aws:states:eu-west-1:" + ACCOUNT + ":stateMachine:c\"}";
assertEquals(control(tail, request), control(tail, request, null, null, null, true));
}
private static TaskPermissions ecsPermissions(String tail, String request, StoredResourceArns ecs) throws Exception {
return TaskPermissions.of(integration(tail), json(request), machine("aws"), null, ecs, false).orElseThrow();
}