feat(stepfunctions): evaluate the execution role on Map's S3 reads and writes (#7725)

Under IAM enforcement, a Distributed Map's S3 calls are now authorized as its execution role, which has to exist and to trust Step Functions. An ItemReader needs s3:GetObject on the object it reads or s3:ListBucket on the bucket it lists, offering s3:prefix when the request has one, as a direct listing does. A ResultWriter needs s3:PutObject on each object it writes: SUCCEEDED_0.json, manifest.json, and FAILED_0.json when a child failed. Every key is evaluated before the first write, so a refusal leaves no partial export. Each is evaluated in the bucket's own partition, and the bucket's policy can grant or deny it.

A refusal fails with States.ItemReaderFailed or States.ResultWriterFailed, and an execution role refused outright with States.Permissions, so Retry and Catch on the Map apply. A refused reader runs no child; a refused writer fails the Map run after its children, as any writer failure does. The multipart actions and s3:GetObject the CDK grants a ResultWriter are not needed, since Floci writes each file in one PutObject. PARQUET and MANIFEST make no S3 call and keep their answer. Credentials on a Map or inside its reader or writer are not read. A mocked execution is evaluated on these calls too, since a test case cannot mock a Map and its S3 calls stay real, and with enforcement off nothing changes.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-15 16:15:48 -04:00
1 parent 58c267e621
commit c1c8b84a1f
13 files changed
+1147 -79

No files matched your search

+41 -2
View File
@@ -244,6 +244,9 @@ JSONPath state machines may resolve the limit from the Map input with `MaxItemsP
JSONata state machines may use a `{% %}` expression in `MaxItems`. `MaxItems` and `MaxItemsPath`
are mutually exclusive, and `MaxItemsPath` is rejected for JSONata state machines.
Under IAM enforcement the reader needs `s3:GetObject` or `s3:ListBucket`: see
[Distributed Map S3 calls](#distributed-map-s3-calls-under-iam-enforcement).
## Distributed Map ItemBatcher
`ItemBatcher` hands each child execution a batch of items instead of a single item. The child input
@@ -276,6 +279,9 @@ absorbed failures to `FAILED_0.json`, each listed under the matching key of the
spent, the state fails with `States.ExceedToleratedFailureThreshold` and the run emits
`MapRunFailed`.
Under IAM enforcement a `ResultWriter` export needs `s3:PutObject` on each of these files: see
[Distributed Map S3 calls](#distributed-map-s3-calls-under-iam-enforcement).
`DescribeMapRun` reports the declared values under `toleratedFailureCount` and
`toleratedFailurePercentage`. A `Map` that declares neither keeps the earlier behaviour: the first
failed item fails the state, carrying that item's own error.
@@ -827,8 +833,8 @@ Floci does not serve keeps its answer, whatever the role: it is "Unsupported", a
CloudFormation API, which is evaluated as above before CloudFormation answers it with `UnknownAction`.
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.
`GetActivityTask` is authorized by its own request. `Map`'s S3 calls are in
[their own section](#distributed-map-s3-calls-under-iam-enforcement).
`<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
@@ -837,6 +843,39 @@ name both. `iam:PassRole` is not evaluated for the roles a schedule or a stack n
the condition keys above and global ones are available to the policies. With enforcement off nothing here is
evaluated.
## Distributed Map S3 calls under IAM enforcement
With `floci.services.iam.enforcement-enabled`, a Distributed `Map` makes its S3 calls as its execution role, which
has to exist and to trust `states.amazonaws.com`. Each permission is evaluated before the call that needs it, on the
ARN a direct request is checked on, in the bucket's own partition, and the bucket's policy can grant or deny it.
| Field | Form | Action | Resource | Refused with |
|---|---|---|---|---|
| `ItemReader` | `arn:aws:states:::s3:getObject` (`JSON`, `JSONL`, `CSV`) | `s3:GetObject` | `<bucket>/<Key>` | `States.ItemReaderFailed` |
| `ItemReader` | `arn:aws:states:::s3:listObjectsV2` | `s3:ListBucket`, with `s3:prefix` when the request has a `Prefix` | `<bucket>` | `States.ItemReaderFailed` |
| `ResultWriter` | `arn:aws:states:::s3:putObject` | `s3:PutObject` | `<bucket>/<Prefix>/<run id>/SUCCEEDED_0.json`, `manifest.json`, and `FAILED_0.json` when a child failed | `States.ResultWriterFailed` |
An execution role that does not exist or does not trust Step Functions is refused with `States.Permissions`. Each is
a failure of the `Map` state, so its `Retry` and `Catch` apply. The refusal's cause names the action and the resource.
A refused reader starts no Map run and no child. A refused writer fails the Map run after its children have run, as
any other `ResultWriter` failure does. The keys of an export are known before its first write, so all of them are
evaluated first and a refusal of any leaves nothing in the bucket.
The export writes each file in a single `PutObject`, so the rest of what the CDK grants a `ResultWriter`,
`s3:GetObject`, `s3:ListMultipartUploadParts` and `s3:AbortMultipartUpload`, is accepted but not needed here.
A request naming nothing it can reach has only the role checks, and is answered as it would be without them: no
`Bucket` or `Key`, or a bucket S3 does not have once the role is allowed. The `ResultWriter` Region check comes after
the evaluation. `PARQUET` and `MANIFEST` make no S3 call here, so they keep their `States.ItemReaderFailed` whatever
the role. A `WriterConfig` with no `Resource`, a Map over its input and an inline `Map` make no S3 call either, and
need nothing. The tasks inside `ItemProcessor` are evaluated as any other task.
A `Map` has no credentials of its own here: `Credentials` on the state, or inside `ItemReader` or `ResultWriter`, is
not read. An execution with a [mock test case](#mocked-service-integrations) is evaluated on these calls too: a test
case cannot mock a `Map`, so its S3 calls stay real, as an unmocked task's call in that execution does. `States.ItemReaderFailed` and `States.ResultWriterFailed` for a refusal are Floci's
reading and have not been verified against AWS.
## Task credentials in history
A task that declares `Credentials` records the resolved role in the `taskCredentials.roleArn` of its
@@ -61,6 +61,7 @@ import io.floci.aws.services.scheduler.model.Schedule;
import io.floci.aws.services.scheduler.model.ScheduleRequest;
import io.floci.aws.services.sns.SnsJsonHandler;
import io.floci.aws.services.sqs.SqsJsonHandler;
import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission;
import io.floci.aws.services.stepfunctions.StepFunctionsService.TokenTimeout;
import io.floci.aws.services.stepfunctions.StepFunctionsService.TokenWait;
import io.floci.aws.services.stepfunctions.model.Execution;
@@ -1280,6 +1281,17 @@ public class AslExecutor {
required.get().deniedError(), required.get().permissions(), required.get().checksExecutionRole());
}
/**
* A Distributed Map's reads and writes are evaluated as its execution role, before the S3 call that needs them.
* An execution with a mock test case is evaluated too: a test case cannot mock a Map state, so its S3 calls stay
* real, as an unmocked task's call in that execution does and is evaluated.
*/
private void authorizeMapS3(StateMachine sm, String refusedError, List<Permission> permissions) {
if (iamEnforcementEnabled()) {
lambdaTaskAuthorizer.authorizeMapS3(sm, refusedError, permissions);
}
}
private boolean iamEnforcementEnabled() {
return config != null && config.services() != null && config.services().iam() != null
&& config.services().iam().enforcementEnabled();
@@ -3332,7 +3344,7 @@ public class AslExecutor {
// Map input-processing fields, including ItemsPath and MaxConcurrencyPath, resolve against
// the effective state input after InputPath has been applied.
JsonNode mapInput = applyInputPath(stateDef, input, context);
ResolvedMapItems resolvedItems = resolveMapItems(stateDef, mapInput, jsonata, context, variables);
ResolvedMapItems resolvedItems = resolveMapItems(stateDef, mapInput, jsonata, context, variables, sm);
JsonNode items = resolvedItems.items();
if (!items.isArray()) {
@@ -3906,6 +3918,9 @@ public class AslExecutor {
"ResultWriter " + (jsonata ? "Arguments" : "Parameters")
+ " must resolve to an object", "ResultWriter/Arguments");
}
// Every object is evaluated before the first is written, so a refusal leaves no partial export.
authorizeMapS3(sm, "States.ResultWriterFailed",
TaskPermissions.resultWriterExport(loc, mapRun.id(), !failedChildren.isEmpty(), sm));
JsonNode bucketNode = loc.get("Bucket");
if (bucketNode == null) {
throw new FailStateException("States.ResultWriterFailed",
@@ -3941,12 +3956,10 @@ public class AslExecutor {
// The run id alone keys the exported result set under the user-supplied S3 prefix.
String mapRunId = mapRun.id();
String mapRunArn = mapRun.arn();
String base = prefix.isEmpty()
? mapRunId + "/"
: prefix + (prefix.endsWith("/") ? "" : "/") + mapRunId + "/";
String base = TaskPermissions.resultWriterBase(prefix, mapRunId);
String succeededKey = base + "SUCCEEDED_0.json";
String manifestKey = base + "manifest.json";
String succeededKey = base + TaskPermissions.RESULT_WRITER_SUCCEEDED;
String manifestKey = base + TaskPermissions.RESULT_WRITER_MANIFEST;
byte[] succeededBytes = serializeResultFile(formatted, outputType);
s3Service.putObject(bucket, succeededKey, succeededBytes, "application/json", new HashMap<>());
@@ -3957,7 +3970,7 @@ public class AslExecutor {
ObjectNode resultFiles = manifest.putObject("ResultFiles");
ArrayNode failedFiles = resultFiles.putArray("FAILED");
if (!failedChildren.isEmpty()) {
String failedKey = base + "FAILED_0.json";
String failedKey = base + TaskPermissions.RESULT_WRITER_FAILED;
byte[] failedBytes = serializeResultFile(
formatFailedChildren(failedChildren, region, account, smName, mapRun.label()),
outputType);
@@ -4085,8 +4098,8 @@ public class AslExecutor {
return objectMapper.writeValueAsBytes(formatted);
}
private ResolvedMapItems resolveMapItems(JsonNode stateDef, JsonNode input,
boolean jsonata, JsonNode context, ObjectNode variables) throws Exception {
private ResolvedMapItems resolveMapItems(JsonNode stateDef, JsonNode input, boolean jsonata, JsonNode context,
ObjectNode variables, StateMachine sm) throws Exception {
if (jsonata && stateDef.has("Items")) {
JsonNode itemsNode = stateDef.get("Items");
if (itemsNode.isTextual() && JsonataEvaluator.isExpression(itemsNode.asText())) {
@@ -4099,7 +4112,7 @@ public class AslExecutor {
}
if (stateDef.has("ItemReader")) {
return resolveItemReaderItems(stateDef.get("ItemReader"), input, context, jsonata, variables);
return resolveItemReaderItems(stateDef.get("ItemReader"), input, context, jsonata, variables, sm);
}
JsonNode itemsPath = stateDef.path("ItemsPath");
@@ -4110,7 +4123,7 @@ public class AslExecutor {
private ResolvedMapItems resolveItemReaderItems(JsonNode itemReader, JsonNode input,
JsonNode context, boolean jsonata,
ObjectNode variables) throws Exception {
ObjectNode variables, StateMachine sm) throws Exception {
String resource = itemReader.path("Resource").asText(null);
StatesIntegration integration = StatesIntegration.parse(resource).orElse(null);
boolean listObjects = integration != null && integration.is("s3", "listObjectsV2");
@@ -4121,7 +4134,7 @@ public class AslExecutor {
int maxItems = resolveItemReaderMaxItems(itemReader, input, jsonata, context, variables);
if (listObjects) {
return resolveListObjectsItems(itemReader, input, context, jsonata, variables, maxItems);
return resolveListObjectsItems(itemReader, input, context, jsonata, variables, maxItems, sm);
}
String inputType = itemReader.path("ReaderConfig").path("InputType").asText(null);
@@ -4133,6 +4146,7 @@ public class AslExecutor {
JsonNode resolvedParameters = resolveItemReaderParameters(itemReader, input, context, jsonata, variables);
String bucket = resolvedParameters.path("Bucket").asText(null);
String key = resolvedParameters.path("Key").asText(null);
authorizeMapS3(sm, "States.ItemReaderFailed", TaskPermissions.itemReaderGetObject(bucket, key, sm));
if (bucket == null || key == null) {
throw new FailStateException("States.Runtime", "ItemReader Parameters must include Bucket and Key");
}
@@ -4292,13 +4306,14 @@ public class AslExecutor {
private ResolvedMapItems resolveListObjectsItems(JsonNode itemReader, JsonNode input, JsonNode context,
boolean jsonata, ObjectNode variables,
int maxItems) throws Exception {
int maxItems, StateMachine sm) throws Exception {
JsonNode parameters = resolveItemReaderParameters(itemReader, input, context, jsonata, variables);
String bucket = parameters.path("Bucket").asText(null);
String prefix = parameters.path("Prefix").asText(null);
authorizeMapS3(sm, "States.ItemReaderFailed", TaskPermissions.itemReaderListObjects(bucket, prefix, sm));
if (bucket == null) {
throw new FailStateException("States.Runtime", "ItemReader Parameters must include Bucket");
}
String prefix = parameters.path("Prefix").asText(null);
ArrayNode items = objectMapper.createArrayNode();
try {
@@ -109,6 +109,25 @@ public class LambdaTaskAuthorizer {
*/
void authorize(StateMachine machine, String credentialsRoleArn, String deniedError, List<Permission> permissions,
boolean checkExecutionRole) {
decide(machine, credentialsRoleArn, deniedError, permissions, checkExecutionRole);
}
/**
* Decides the S3 calls a Distributed Map makes as its execution role, which has no error prefix of its own: a
* refused permission fails the state with the error its reader or writer fails with on any other S3 failure.
* The execution role has to exist and to trust Step Functions, as for a task, and is refused with
* {@code States.Permissions}. A Map has no {@code Credentials} to assume.
*
* @param refusedError the error a refused permission fails with
* @throws AslExecutor.FailStateException {@code States.Permissions} for the execution role, and
* {@code refusedError} for a refused permission
*/
void authorizeMapS3(StateMachine machine, String refusedError, List<Permission> permissions) {
decide(machine, null, refusedError, permissions, true);
}
private void decide(StateMachine machine, String credentialsRoleArn, String refusedError,
List<Permission> permissions, boolean checkExecutionRole) {
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
if (checkExecutionRole) {
IamRole executionRole = role(machine.getRoleArn()).orElseThrow(
@@ -131,7 +150,7 @@ public class LambdaTaskAuthorizer {
Optional<String> refusal = refusal(effectiveRoleArn, permission.action(), evaluatedOn(permission.resourceArn()),
owner.region(), permission.conditionKeys());
if (refusal.isPresent()) {
throw new AslExecutor.FailStateException(deniedError, refusal.get());
throw new AslExecutor.FailStateException(refusedError, refusal.get());
}
}
}
@@ -14,6 +14,7 @@ import io.floci.aws.services.eventbridge.EventBridgeService;
import io.floci.aws.services.iam.IamAuthorizedActions;
import io.floci.aws.services.iam.ResourceArnBuilder;
import io.floci.aws.services.redshiftdata.RedshiftDataTargetSubmitter;
import io.floci.aws.services.s3.S3ConditionKeys;
import io.floci.aws.services.s3.S3ResourceArns;
import io.floci.aws.services.sqs.SqsService;
import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission;
@@ -43,6 +44,9 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
private static final Logger LOG = Logger.getLogger(TaskPermissions.class);
private static final String ANY_RESOURCE = "*";
static final String RESULT_WRITER_SUCCEEDED = "SUCCEEDED_0.json";
static final String RESULT_WRITER_FAILED = "FAILED_0.json";
static final String RESULT_WRITER_MANIFEST = "manifest.json";
private static final String DYNAMODB_OPTIMIZED_PREFIX = "DynamoDB.";
private static final String DYNAMODB_SDK_PREFIX = "DynamoDb.";
private static final String REDSHIFT_DATA_PREFIX = "RedshiftData.";
@@ -353,9 +357,69 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
if (bucket.isBlank() || key == null) {
return accessDenied("S3.", List.of());
}
String partition = AwsArnUtils.parse(machine.getStateMachineArn()).partition();
return accessDenied("S3.",
List.of(new Permission("s3:PutObject", S3ResourceArns.object(partition, bucket, key))));
return accessDenied("S3.", List.of(new Permission("s3:PutObject", s3ObjectArn(machine, bucket, key))));
}
/**
* What a Distributed Map's {@code ItemReader} needs to read one object: {@code s3:GetObject} on it. A request
* naming no bucket or key needs nothing, and is answered by the reader or by S3.
*/
static List<Permission> itemReaderGetObject(String bucket, String key, StateMachine machine) {
if (bucket == null || bucket.isBlank() || key == null) {
return List.of();
}
return List.of(new Permission("s3:GetObject", s3ObjectArn(machine, bucket, key)));
}
/**
* What a Distributed Map's {@code ItemReader} needs to list a bucket: {@code s3:ListBucket} on it, offering
* {@code s3:prefix} when the request has a prefix, as a direct listing offers it. A request naming no bucket
* needs nothing, and is answered by the reader or by S3.
*/
static List<Permission> itemReaderListObjects(String bucket, String prefix, StateMachine machine) {
if (bucket == null || bucket.isBlank()) {
return List.of();
}
return List.of(new Permission("s3:ListBucket", s3BucketArn(machine, bucket),
prefix == null ? Map.of() : Map.of(S3ConditionKeys.PREFIX, List.of(prefix))));
}
/**
* What a Distributed Map's {@code ResultWriter} needs to export: {@code s3:PutObject} on each object it writes,
* all known before the first is. The failed file is written only when a child failed. A location naming no
* bucket, or a prefix that is not a string, needs nothing, and is answered by the writer.
*
* @param location the resolved {@code Parameters} or {@code Arguments} of the writer
*/
static List<Permission> resultWriterExport(JsonNode location, String mapRunId, boolean failedChildren,
StateMachine machine) {
String bucket = text(location.path("Bucket"));
JsonNode prefix = location.path("Prefix");
if (bucket == null || !(prefix.isMissingNode() || prefix.isTextual())) {
return List.of();
}
String base = resultWriterBase(prefix.asText(""), mapRunId);
List<String> files = failedChildren
? List.of(RESULT_WRITER_SUCCEEDED, RESULT_WRITER_FAILED, RESULT_WRITER_MANIFEST)
: List.of(RESULT_WRITER_SUCCEEDED, RESULT_WRITER_MANIFEST);
return files.stream()
.map(file -> new Permission("s3:PutObject", s3ObjectArn(machine, bucket, base + file)))
.toList();
}
/** The key every object of a Map run's export starts with: the run id keys it under the prefix given. */
static String resultWriterBase(String prefix, String mapRunId) {
return prefix.isEmpty() ? mapRunId + "/" : prefix + (prefix.endsWith("/") ? "" : "/") + mapRunId + "/";
}
/** A bucket's ARN in the state machine's partition: the authorizer moves it to the bucket's own. */
private static String s3BucketArn(StateMachine machine, String bucket) {
return S3ResourceArns.bucket(AwsArnUtils.parse(machine.getStateMachineArn()).partition(), bucket);
}
/** An object's ARN in the state machine's partition: the authorizer moves it to the bucket's own. */
private static String s3ObjectArn(StateMachine machine, String bucket, String key) {
return S3ResourceArns.object(AwsArnUtils.parse(machine.getStateMachineArn()).partition(), bucket, key);
}
/**
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.config.EmulatorConfig;
import io.floci.aws.services.lambda.LambdaExecutorService;
import io.floci.aws.services.s3.S3Service;
import io.floci.aws.services.stepfunctions.model.Execution;
import io.floci.aws.services.stepfunctions.model.HistoryEvent;
import io.floci.aws.services.stepfunctions.model.MockedResponseStep;
@@ -11,6 +12,7 @@ import io.floci.aws.services.stepfunctions.model.MockedTestCase;
import io.floci.aws.services.stepfunctions.model.StateMachine;
import io.quarkus.test.junit.QuarkusTest;
import io.vertx.mutiny.core.Vertx;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -21,8 +23,12 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
@@ -283,6 +289,42 @@ class AslExecutorMockedResponsesTest {
return new MockedResponseStep(from, to, null, error, cause);
}
/** A test case cannot mock a Map state, whose S3 calls stay real, so a mocked execution is evaluated on them too. */
@Test
void aMockedExecutionsMapS3CallsAreEvaluatedUnderEnforcement() {
LambdaTaskAuthorizer authorizer = mock(LambdaTaskAuthorizer.class);
S3Service s3 = mock(S3Service.class);
when(s3.listObjects(any(), any(), any(), anyInt())).thenReturn(List.of());
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().stepfunctions().maxWaitSeconds()).thenReturn(30);
when(config.services().iam().enforcementEnabled()).thenReturn(true);
@SuppressWarnings("unchecked")
Instance<StepFunctionsService> sfnService = mock(Instance.class);
when(sfnService.get()).thenReturn(mock(StepFunctionsService.class));
executor = AslExecutorFixture.builder()
.lambdaExecutor(lambdaExecutor)
.lambdaTaskAuthorizer(authorizer)
.s3Service(s3)
.sfnService(sfnService)
.objectMapper(objectMapper)
.config(config)
.vertx(vertx)
.customResourceLiveness(null)
.build();
String definition = """
{"StartAt":"Run","States":{"Run":{"Type":"Map","End":true,
"ItemReader":{"Resource":"arn:aws:states:::s3:listObjectsV2","Parameters":{"Bucket":"b"}},
"ItemProcessor":{"ProcessorConfig":{"Mode":"DISTRIBUTED","ExecutionType":"STANDARD"},
"StartAt":"Item","States":{"Item":{"Type":"Pass","End":true}}}}}}
""";
Execution mocked = run(definition, testCase(Map.of("Elsewhere", List.of())), "{}", "mocked");
assertEquals("SUCCEEDED", mocked.getStatus(), mocked.getCause());
verify(authorizer).authorizeMapS3(any(), eq("States.ItemReaderFailed"), any());
verify(s3).listObjects(eq("b"), any(), any(), anyInt());
}
private Execution run(String definition, MockedTestCase mocks) {
return run(definition, mocks, "{}");
}
@@ -585,6 +585,40 @@ class LambdaTaskAuthorizerTest {
when(iamService.findRole(SFN_ACCOUNT, "sfn-exec")).thenReturn(Optional.of(role));
}
/** A refusal fails with the error it is given, and the message says what was refused, on what. */
@Test
void aMapRefusalFailsWithTheErrorItIsGiven() {
roleWithPolicies(READ_OBJECTS);
executionRole(STATES_TRUST);
AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class,
() -> authorizer.authorizeMapS3(machine(), "States.ResultWriterFailed",
List.of(new Permission("s3:PutObject", BUCKET))));
assertEquals("States.ResultWriterFailed", refused.error);
assertTrue(refused.cause.contains("s3:PutObject"), refused.cause);
assertTrue(refused.cause.contains(BUCKET), refused.cause);
}
@Test
void aMapAllowedEveryPermissionPasses() {
roleWithPolicies(READ_OBJECTS);
executionRole(STATES_TRUST);
authorizer.authorizeMapS3(machine(), "States.ItemReaderFailed", List.of(new Permission("s3:GetObject", BUCKET)));
}
@Test
void aMapsExecutionRoleHasToTrustStepFunctionsWhateverItAsksFor() {
roleWithPolicies(READ_OBJECTS);
executionRole(trust("{\"Service\":\"lambda.amazonaws.com\"}"));
AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class,
() -> authorizer.authorizeMapS3(machine(), "States.ItemReaderFailed", List.of()));
assertEquals("States.Permissions", refused.error);
}
private static StateMachine machine() {
StateMachine machine = new StateMachine();
machine.setStateMachineArn(STATE_MACHINE);
@@ -3,7 +3,6 @@ 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;
@@ -40,6 +39,8 @@ 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.allow;
import static io.floci.aws.testing.StepFunctionsTestClient.policy;
import static io.floci.aws.testing.StepFunctionsTestClient.trusting;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
@@ -897,22 +898,8 @@ class StepFunctionsControlTaskIamIntegrationTest {
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);
return sfn().role(ACCOUNT, "sfn-control-", trust, policy);
}
private static String machineArn(String name) {
@@ -4,7 +4,6 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.services.rdsdata.RdsDataService;
import io.floci.aws.services.redshiftdata.RedshiftDataService;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
@@ -37,6 +36,7 @@ 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.policy;
import static io.floci.aws.testing.StepFunctionsTestClient.trusting;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -653,15 +653,6 @@ class StepFunctionsDataTaskIamIntegrationTest {
return allow("*", "dynamodb:*", "s3:*", "rds-data:*", "redshift-data:*", "secretsmanager:*", "sts:AssumeRole");
}
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 static String bucketStatement(String effect, String principal, String bucket) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"%s"},
@@ -800,19 +791,11 @@ class StepFunctionsDataTaskIamIntegrationTest {
}
private String bucket(String account, String region) {
String name = "sfn-iam-" + UUID.randomUUID();
String authorization = auth(account, region, "s3");
given().port(baseUri.getPort()).header("Authorization", authorization)
.body(REGION.equals(region) ? "" : "<CreateBucketConfiguration><LocationConstraint>" + region
+ "</LocationConstraint></CreateBucketConfiguration>")
.put("/" + name).then().statusCode(200);
cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(), authorization, name));
return name;
return sfn().bucket(account, region, "sfn-iam-");
}
private void setBucketPolicy(String bucket, String policy) {
given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "s3")).body(policy)
.queryParam("policy", "").put("/" + bucket).then().statusCode(200);
sfn().setBucketPolicy(ACCOUNT, bucket, policy);
}
private Response object(String bucket, String key) {
@@ -2,7 +2,6 @@ package io.floci.aws.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.testing.EnforcementFixtures;
import io.floci.aws.testing.IamEnforcementProfile;
import io.floci.aws.testing.PartitionCleanup;
import io.floci.aws.testing.RestAssuredJsonUtils;
@@ -33,6 +32,8 @@ 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.allow;
import static io.floci.aws.testing.StepFunctionsTestClient.policy;
import static io.floci.aws.testing.StepFunctionsTestClient.trusting;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
@@ -998,27 +999,13 @@ class StepFunctionsJobTaskIamIntegrationTest {
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 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 role(String trust, String policy) {
return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/",
"sfn-jobs-" + UUID.randomUUID(), trust, policy);
return sfn().role(ACCOUNT, "sfn-jobs-", trust, policy);
}
private String machine(Map<String, Object> task, String role) throws Exception {
@@ -0,0 +1,798 @@
package io.floci.aws.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
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.allow;
import static io.floci.aws.testing.StepFunctionsTestClient.policy;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The S3 calls a Distributed Map makes as its execution role, under IAM enforcement. S3 runs for real, so a test reads
* what a reader saw from the Map's output and what a writer wrote from the bucket.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class StepFunctionsMapS3IamIntegrationTest {
private static final String ACCOUNT = "000000000473";
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 READER_REFUSED = "States.ItemReaderFailed";
private static final String WRITER_REFUSED = "States.ResultWriterFailed";
private static final Map<String, Object> PASS_CHILD = processor(Map.of("StartAt", "Item",
"States", Map.of("Item", Map.of("Type", "Pass", "End", true))));
/** Fails the items that say so, for a Map that tolerates it. */
private static final Map<String, Object> FAILING_CHILD = processor(Map.of("StartAt", "Decide", "States", Map.of(
"Decide", Map.of("Type", "Choice", "Default", "Ok",
"Choices", List.of(Map.of("Variable", "$.fail", "BooleanEquals", true, "Next", "Boom"))),
"Ok", Map.of("Type", "Pass", "End", true),
"Boom", Map.of("Type", "Fail", "Error", "Item.Failed", "Cause", "told to"))));
private static final String TWO_ITEMS = "{\"items\":[{\"fail\":false},{\"fail\":false}]}";
@TestHTTPResource
URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void contentTypes() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@ValueSource(strings = {"LIST", "LIST_PREFIX", "JSON", "JSONL", "CSV"})
void anExecutionRoleAllowedToReadRunsEveryChild(String form) throws Exception {
Reader reader = reader(form);
String execution = start(machine(readerMap(reader), role(STATES_TRUST, reader.grant())), "{}");
Response completed = terminal(execution);
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals(reader.items(), MAPPER.readTree(completed.jsonPath().getString("output")).size());
assertEquals(1, eventsOfType(execution, "MapRunStarted").size());
}
@ParameterizedTest
@ValueSource(strings = {"LIST", "LIST_PREFIX", "JSON", "JSONL", "CSV"})
void anExecutionRoleNotAllowedToReadIsRefusedAndRunsNoChild(String form) throws Exception {
Reader reader = reader(form);
String execution = start(machine(readerMap(reader), role(STATES_TRUST, READ_ONLY)), "{}");
Response completed = terminal(execution);
assertFailed(completed, READER_REFUSED);
String cause = completed.jsonPath().getString("cause");
assertTrue(cause.contains(reader.action()), cause);
assertTrue(cause.contains(reader.resourceArn()), cause);
assertEquals(0, eventsOfType(execution, "MapRunStarted").size());
}
@ParameterizedTest
@ValueSource(strings = {"LIST", "LIST_PREFIX", "JSON", "JSONL", "CSV"})
void theActionOnAnotherResourceDoesNotCount(String form) throws Exception {
Reader reader = reader(form);
Response completed = terminal(start(machine(readerMap(reader),
role(STATES_TRUST, allow(reader.resourceArn() + "-elsewhere", reader.action()))), "{}"));
assertFailed(completed, READER_REFUSED);
}
/** A listing is not a read, as neither is for a direct request: each form needs its own action. */
@ParameterizedTest
@CsvSource({"LIST,s3:GetObject", "LIST_PREFIX,s3:GetObject", "JSON,s3:ListBucket", "JSONL,s3:ListBucket",
"CSV,s3:ListBucket"})
void theOtherReaderActionDoesNotCount(String form, String otherAction) throws Exception {
Reader reader = reader(form);
String everything = "arn:aws:s3:::" + reader.bucket();
Response completed = terminal(start(machine(readerMap(reader),
role(STATES_TRUST, policy(List.of(Map.of("Effect", "Allow", "Action", otherAction,
"Resource", List.of(everything, everything + "/*")))))), "{}"));
assertFailed(completed, READER_REFUSED);
}
@ParameterizedTest
@ValueSource(strings = {"LIST", "LIST_PREFIX", "JSON", "JSONL", "CSV"})
void aRoleThatDoesNotTrustStepFunctionsCannotRead(String form) throws Exception {
Reader reader = reader(form);
String role = role(LAMBDA_TRUST, reader.grant());
String execution = start(machine(readerMap(reader), role), "{}");
Response completed = terminal(execution);
assertFailed(completed, "States.Permissions");
assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString());
assertEquals(0, eventsOfType(execution, "MapRunStarted").size());
}
@ParameterizedTest
@ValueSource(strings = {"LIST", "JSON"})
void aRoleThatDoesNotExistCannotRead(String form) throws Exception {
Reader reader = reader(form);
String role = "arn:aws:iam::" + ACCOUNT + ":role/absent-" + UUID.randomUUID();
Response completed = terminal(start(machine(readerMap(reader), role), "{}"));
assertFailed(completed, "States.Permissions");
assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString());
}
@Test
void aRoleThatDoesNotTrustStepFunctionsCannotWrite() throws Exception {
String bucket = bucket();
String role = role(LAMBDA_TRUST, allow("arn:aws:s3:::" + bucket + "/*", "s3:PutObject"));
String execution = start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS);
Response completed = terminal(execution);
assertFailed(completed, "States.Permissions");
assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString());
assertEquals(1, eventsOfType(execution, "MapRunFailed").size());
assertEquals(List.of(), keys(bucket));
}
@Test
void aRoleThatDoesNotExistCannotWrite() throws Exception {
String bucket = bucket();
String role = "arn:aws:iam::" + ACCOUNT + ":role/absent-" + UUID.randomUUID();
Response completed = terminal(start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS));
assertFailed(completed, "States.Permissions");
assertEquals(List.of(), keys(bucket));
}
@ParameterizedTest
@ValueSource(strings = {"LIST", "JSON", "JSONL", "CSV"})
void aBucketPolicyLetsARoleRead(String form) throws Exception {
Reader reader = reader(form);
String role = role(STATES_TRUST, READ_ONLY);
setBucketPolicy(reader.bucket(), bucketStatement("Allow", role, reader.action(), reader.resourceArn()));
Response completed = terminal(start(machine(readerMap(reader), role), "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
}
@ParameterizedTest
@ValueSource(strings = {"LIST", "JSON", "JSONL", "CSV"})
void aBucketPolicyDenyStopsARoleReading(String form) throws Exception {
Reader reader = reader(form);
String role = role(STATES_TRUST, reader.grant());
setBucketPolicy(reader.bucket(), bucketStatement("Deny", role, reader.action(), reader.resourceArn()));
Response completed = terminal(start(machine(readerMap(reader), role), "{}"));
assertFailed(completed, READER_REFUSED);
assertTrue(completed.jsonPath().getString("cause").contains("resource-based policy"), completed.asString());
}
@Test
void aBucketPolicyLetsARoleWrite() throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, READ_ONLY);
setBucketPolicy(bucket, bucketStatement("Allow", role, "s3:PutObject", "arn:aws:s3:::" + bucket + "/out/*"));
Response completed = terminal(start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals(2, keys(bucket).size());
}
@Test
void aBucketPolicyDenyStopsARoleWriting() throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, allow("arn:aws:s3:::" + bucket + "/*", "s3:PutObject"));
setBucketPolicy(bucket, bucketStatement("Deny", role, "s3:PutObject", "arn:aws:s3:::" + bucket + "/*"));
Response completed = terminal(start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS));
assertFailed(completed, WRITER_REFUSED);
assertTrue(completed.jsonPath().getString("cause").contains("resource-based policy"), completed.asString());
assertEquals(List.of(), keys(bucket));
}
/** A listing offers {@code s3:prefix} only when it has one, as a direct request does. */
@Test
void aGrantConditionedOnThePrefixCoversThatPrefix() throws Exception {
String bucket = bucket();
put(bucket, "data/a", "a");
put(bucket, "other/b", "b");
String role = role(STATES_TRUST, policy(List.of(Map.of("Effect", "Allow", "Action", "s3:ListBucket",
"Resource", "arn:aws:s3:::" + bucket,
"Condition", Map.of("StringEquals", Map.of("s3:prefix", "data/"))))));
Response granted = terminal(start(machine(listMap(Map.of("Bucket", bucket, "Prefix", "data/")), role), "{}"));
Response elsewhere = terminal(start(machine(listMap(Map.of("Bucket", bucket, "Prefix", "other/")), role), "{}"));
Response noPrefix = terminal(start(machine(listMap(Map.of("Bucket", bucket)), role), "{}"));
assertEquals("SUCCEEDED", granted.jsonPath().getString("status"), granted.asString());
assertFailed(elsewhere, READER_REFUSED);
assertFailed(noPrefix, READER_REFUSED);
}
/** S3's one namespace reaches a bucket of another partition, whose ARN is the one a direct request is checked on. */
@ParameterizedTest
@ValueSource(strings = {"LIST", "JSON"})
void aBucketReadInAnotherPartitionIsEvaluatedInItsOwn(String form) throws Exception {
String bucket = bucket(ACCOUNT, "cn-north-1");
boolean list = "LIST".equals(form);
String resource = list ? bucket : bucket + "/items.json";
put(bucket, "items.json", "[1,2]", auth(ACCOUNT, "cn-north-1", "s3"));
Map<String, Object> map = list ? listMap(Map.of("Bucket", bucket))
: getMap(Map.of("Bucket", bucket, "Key", "items.json"), "JSON");
String action = list ? "s3:ListBucket" : "s3:GetObject";
Response refused = terminal(start(machine(map, role(STATES_TRUST, allow("arn:aws:s3:::" + resource, action))), "{}"));
Response allowed = terminal(start(machine(map, role(STATES_TRUST, allow("arn:aws-cn:s3:::" + resource, action))), "{}"));
assertFailed(refused, READER_REFUSED);
assertTrue(refused.jsonPath().getString("cause").contains("arn:aws-cn:s3:::" + bucket), refused.asString());
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
}
/** Evaluated before the Region check, which is then what answers: a role cannot learn where a bucket is. */
@Test
void aBucketWrittenInAnotherPartitionIsEvaluatedInItsOwn() throws Exception {
String bucket = bucket(ACCOUNT, "cn-north-1");
Map<String, Object> map = writerMap(bucket, "out", PASS_CHILD);
Response refused = terminal(start(machine(map, role(STATES_TRUST,
allow("arn:aws:s3:::" + bucket + "/*", "s3:PutObject"))), TWO_ITEMS));
Response allowed = terminal(start(machine(map, role(STATES_TRUST,
allow("arn:aws-cn:s3:::" + bucket + "/*", "s3:PutObject"))), TWO_ITEMS));
assertFailed(refused, WRITER_REFUSED);
assertTrue(refused.jsonPath().getString("cause").contains("arn:aws-cn:s3:::" + bucket), refused.asString());
assertFailed(allowed, WRITER_REFUSED);
assertTrue(allowed.jsonPath().getString("cause").contains("same AWS Region"), allowed.asString());
}
@ParameterizedTest
@ValueSource(strings = {"LIST", "JSON"})
void aMissingBucketIsAnsweredByS3OnceTheRoleIsAllowed(String form) throws Exception {
String bucket = "sfn-map-absent-" + UUID.randomUUID();
boolean list = "LIST".equals(form);
Map<String, Object> map = list ? listMap(Map.of("Bucket", bucket))
: getMap(Map.of("Bucket", bucket, "Key", "items.json"), "JSON");
String action = list ? "s3:ListBucket" : "s3:GetObject";
String arn = "arn:aws:s3:::" + bucket + (list ? "" : "/items.json");
Response refused = terminal(start(machine(map, role(STATES_TRUST, READ_ONLY)), "{}"));
Response answered = terminal(start(machine(map, role(STATES_TRUST, allow(arn, action))), "{}"));
assertFailed(refused, READER_REFUSED);
assertTrue(refused.jsonPath().getString("cause").contains(action), refused.asString());
assertFailed(answered, READER_REFUSED);
assertFalse(answered.jsonPath().getString("cause").contains(action), answered.asString());
}
@ParameterizedTest
@CsvSource({"LIST,'{}'", "JSON,'{\"Key\":\"items.json\"}'"})
void aRequestNamingNoBucketIsAnsweredByTheReader(String form, String parameters) throws Exception {
Map<String, Object> request = MAPPER.readValue(parameters, Map.class);
Map<String, Object> map = "LIST".equals(form) ? listMap(request) : getMap(request, "JSON");
Response answered = terminal(start(machine(map, role(STATES_TRUST, READ_ONLY)), "{}"));
Response roleChecked = terminal(start(machine(map, role(LAMBDA_TRUST, READ_ONLY)), "{}"));
assertFailed(answered, "States.Runtime");
assertTrue(answered.jsonPath().getString("cause").contains("must include Bucket"), answered.asString());
assertFailed(roleChecked, "States.Permissions");
}
/** Floci reads neither, so there is no S3 call to evaluate and its answer does not depend on the role. */
@ParameterizedTest
@ValueSource(strings = {"PARQUET", "MANIFEST"})
void anInputTypeFlociDoesNotReadKeepsItsAnswer(String inputType) throws Exception {
String bucket = bucket();
Map<String, Object> map = getMap(Map.of("Bucket", bucket, "Key", "items"), inputType);
Response completed = terminal(start(machine(map, role(LAMBDA_TRUST, READ_ONLY)), "{}"));
assertFailed(completed, READER_REFUSED);
assertTrue(completed.jsonPath().getString("cause").contains("not yet implemented"), completed.asString());
}
@Test
void anExecutionRoleAllowedToWriteExports() throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, allow("arn:aws:s3:::" + bucket + "/out/*", "s3:PutObject"));
Response completed = terminal(start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
JsonNode output = MAPPER.readTree(completed.jsonPath().getString("output"));
String manifest = output.path("ResultWriterDetails").path("Key").asText();
assertTrue(manifest.startsWith("out/"), manifest);
List<String> keys = keys(bucket);
assertEquals(2, keys.size(), keys.toString());
assertTrue(keys.contains(manifest), keys.toString());
}
/** The children have run by then, and the Map run fails as any other failure of its writer does. */
@Test
void anExecutionRoleNotAllowedToWriteFailsTheMapAfterItsChildren() throws Exception {
String bucket = bucket();
String execution = start(machine(writerMap(bucket, "out", PASS_CHILD), role(STATES_TRUST, READ_ONLY)), TWO_ITEMS);
Response completed = terminal(execution);
assertFailed(completed, WRITER_REFUSED);
String cause = completed.jsonPath().getString("cause");
assertTrue(cause.contains("s3:PutObject"), cause);
assertTrue(cause.contains("arn:aws:s3:::" + bucket + "/out/"), cause);
assertEquals(List.of(), keys(bucket));
assertEquals(1, eventsOfType(execution, "MapRunFailed").size());
String mapRun = eventsOfType(execution, "MapRunStarted").getFirst()
.path("mapRunStartedEventDetails").path("mapRunArn").asText();
Response described = request("DescribeMapRun", Map.of("mapRunArn", mapRun));
assertEquals("FAILED", described.jsonPath().getString("status"), described.asString());
assertEquals(2, described.jsonPath().getInt("itemCounts.succeeded"), described.asString());
}
@Test
void aGrantOnAnotherPrefixDoesNotCoverTheExport() throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, allow("arn:aws:s3:::" + bucket + "/elsewhere/*", "s3:PutObject"));
Response completed = terminal(start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS));
assertFailed(completed, WRITER_REFUSED);
assertEquals(List.of(), keys(bucket));
}
@Test
void aGrantOnAnotherActionDoesNotCoverTheExport() throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, allow("arn:aws:s3:::" + bucket + "/*", "s3:GetObject",
"s3:ListMultipartUploadParts", "s3:AbortMultipartUpload"));
assertFailed(terminal(start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS)), WRITER_REFUSED);
assertEquals(List.of(), keys(bucket));
}
/** Multipart is not called, and the export reads nothing back: the single write is all the role needs. */
@Test
void anExportNeedsOnlyPutObject() throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, policy(List.of(
Map.of("Effect", "Allow", "Action", "s3:PutObject", "Resource", "arn:aws:s3:::" + bucket + "/*"),
Map.of("Effect", "Deny", "Action",
List.of("s3:GetObject", "s3:ListMultipartUploadParts", "s3:AbortMultipartUpload", "s3:ListBucket"),
"Resource", "*"))));
Response completed = terminal(start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
}
/** Every key is known up front and evaluated first, so a refusal of the last leaves no partial export. */
@ParameterizedTest
@ValueSource(strings = {"SUCCEEDED_0.json", "manifest.json"})
void aRefusalOfOneObjectWritesNone(String refused) throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, policy(List.of(
Map.of("Effect", "Allow", "Action", "s3:PutObject", "Resource", "arn:aws:s3:::" + bucket + "/*"),
Map.of("Effect", "Deny", "Action", "s3:PutObject", "Resource", "arn:aws:s3:::" + bucket + "/*/" + refused))));
Response completed = terminal(start(machine(writerMap(bucket, "out", PASS_CHILD), role), TWO_ITEMS));
assertFailed(completed, WRITER_REFUSED);
assertTrue(completed.jsonPath().getString("cause").contains(refused), completed.asString());
assertEquals(List.of(), keys(bucket));
}
/** Only what is written is evaluated: the failed file needs a grant when a tolerated child failed, not otherwise. */
@Test
void theFailedFileIsEvaluatedOnlyWhenAChildFailed() throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, policy(List.of(Map.of("Effect", "Allow", "Action", "s3:PutObject", "Resource",
List.of("arn:aws:s3:::" + bucket + "/*/SUCCEEDED_0.json", "arn:aws:s3:::" + bucket + "/*/manifest.json")))));
Map<String, Object> map = writerMap(bucket, "out", FAILING_CHILD);
map.put("ToleratedFailurePercentage", 100);
Response noFailure = terminal(start(machine(map, role), TWO_ITEMS));
assertEquals("SUCCEEDED", noFailure.jsonPath().getString("status"), noFailure.asString());
int exported = keys(bucket).size();
Response failure = terminal(start(machine(map, role), "{\"items\":[{\"fail\":true},{\"fail\":false}]}"));
assertFailed(failure, WRITER_REFUSED);
assertTrue(failure.jsonPath().getString("cause").contains("FAILED_0.json"), failure.asString());
assertEquals(exported, keys(bucket).size());
}
@Test
void aFailedFileIsExportedWithItsGrant() throws Exception {
String bucket = bucket();
String role = role(STATES_TRUST, allow("arn:aws:s3:::" + bucket + "/out/*", "s3:PutObject"));
Map<String, Object> map = writerMap(bucket, "out", FAILING_CHILD);
map.put("ToleratedFailurePercentage", 100);
Response completed = terminal(start(machine(map, role), "{\"items\":[{\"fail\":true},{\"fail\":false}]}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals(3, keys(bucket).size());
}
@Test
void aWriterConfigAloneWritesNothingAndNeedsNothing() throws Exception {
Map<String, Object> map = mapState(PASS_CHILD);
map.put("ItemsPath", "$.items");
map.put("ResultWriter", Map.of("WriterConfig", Map.of("Transformation", "COMPACT", "OutputType", "JSON")));
Response completed = terminal(start(machine(map, role(LAMBDA_TRUST, READ_ONLY)), TWO_ITEMS));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
}
@Test
void aWriterNamingNoBucketIsAnsweredByTheWriter() throws Exception {
Map<String, Object> map = mapState(PASS_CHILD);
map.put("ItemsPath", "$.items");
map.put("ResultWriter", Map.of("Resource", "arn:aws:states:::s3:putObject",
"Parameters", Map.of("Bucket.$", "$.bucket", "Prefix", "out")));
String input = "{\"bucket\":\"\",\"items\":[1]}";
Response answered = terminal(start(machine(map, role(STATES_TRUST, READ_ONLY)), input));
Response roleChecked = terminal(start(machine(map, role(LAMBDA_TRUST, READ_ONLY)), input));
assertFailed(answered, WRITER_REFUSED);
assertTrue(answered.jsonPath().getString("cause").contains("bucket is required"), answered.asString());
assertFailed(roleChecked, "States.Permissions");
}
@Test
void aMissingBucketIsAnsweredByTheWriterOnceTheRoleIsAllowed() throws Exception {
String bucket = "sfn-map-absent-" + UUID.randomUUID();
Map<String, Object> map = writerMap(bucket, "out", PASS_CHILD);
Response refused = terminal(start(machine(map, role(STATES_TRUST, READ_ONLY)), TWO_ITEMS));
Response answered = terminal(start(machine(map, role(STATES_TRUST,
allow("arn:aws:s3:::" + bucket + "/*", "s3:PutObject"))), TWO_ITEMS));
assertFailed(refused, WRITER_REFUSED);
assertTrue(refused.jsonPath().getString("cause").contains("s3:PutObject"), refused.asString());
assertFailed(answered, WRITER_REFUSED);
assertTrue(answered.jsonPath().getString("cause").contains("Unable to export"), answered.asString());
}
/** Retried, the reader is evaluated again and the Map then goes to its Catch, with a second's wait between. */
@ParameterizedTest
@CsvSource({"States.ItemReaderFailed,STATES", "States.Permissions,LAMBDA"})
void aRefusedReaderIsRetriedThenCaught(String error, String trust) throws Exception {
Reader reader = reader("LIST");
Map<String, Object> map = readerMap(reader);
map.put("Retry", List.of(Map.of("ErrorEquals", List.of(error), "IntervalSeconds", 1, "MaxAttempts", 1)));
map.put("Catch", List.of(Map.of("ErrorEquals", List.of(error), "Next", "Fallback", "ResultPath", "$.caught")));
map.remove("End");
map.put("Next", "Done");
Response completed = terminal(start(machineWithFallback(map,
role("STATES".equals(trust) ? STATES_TRUST : LAMBDA_TRUST, READ_ONLY)), "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
JsonNode caught = MAPPER.readTree(completed.jsonPath().getString("output")).path("caught");
assertEquals(error, caught.path("Error").asText(), completed.asString());
JsonNode described = MAPPER.readTree(completed.asString());
assertTrue(described.path("stopDate").asDouble() - described.path("startDate").asDouble() >= 1,
completed.asString());
}
@Test
void aRefusedWriterRunsTheMapAgainOnRetryThenIsCaught() throws Exception {
String bucket = bucket();
Map<String, Object> map = writerMap(bucket, "out", PASS_CHILD);
map.put("Retry", List.of(Map.of("ErrorEquals", List.of(WRITER_REFUSED), "IntervalSeconds", 1, "MaxAttempts", 1)));
map.put("Catch", List.of(Map.of("ErrorEquals", List.of(WRITER_REFUSED), "Next", "Fallback", "ResultPath", "$.caught")));
map.remove("End");
map.put("Next", "Done");
String execution = start(machineWithFallback(map, role(STATES_TRUST, READ_ONLY)), TWO_ITEMS);
Response completed = terminal(execution);
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals(WRITER_REFUSED, MAPPER.readTree(completed.jsonPath().getString("output"))
.path("caught").path("Error").asText(), completed.asString());
assertEquals(2, eventsOfType(execution, "MapRunFailed").size());
assertEquals(List.of(), keys(bucket));
}
/** A refused reader ends the Map before its writer has anything to do, whatever the role may write. */
@Test
void aRefusedReaderWritesNothing() throws Exception {
Reader reader = reader("JSON");
String target = bucket();
Map<String, Object> map = readerMap(reader);
map.put("ResultWriter", writer(target, "out"));
Response completed = terminal(start(machine(map, role(STATES_TRUST,
allow("arn:aws:s3:::" + target + "/*", "s3:PutObject"))), "{}"));
assertFailed(completed, READER_REFUSED);
assertEquals(List.of(), keys(target));
}
@Test
void aReaderAndWriterBothAllowedExportWhatWasRead() throws Exception {
Reader reader = reader("JSON");
String target = bucket();
Map<String, Object> map = readerMap(reader);
map.put("ResultWriter", writer(target, "out"));
String role = role(STATES_TRUST, policy(List.of(
Map.of("Effect", "Allow", "Action", reader.action(), "Resource", reader.resourceArn()),
Map.of("Effect", "Allow", "Action", "s3:PutObject", "Resource", "arn:aws:s3:::" + target + "/*"))));
Response completed = terminal(start(machine(map, role), "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals(2, keys(target).size());
}
/** What each resolves to is what is evaluated, in both query languages. */
@ParameterizedTest
@ValueSource(strings = {"JSONPath", "JSONata"})
void whatARequestResolvesToIsWhatIsEvaluated(String language) throws Exception {
Reader reader = reader("JSON");
String target = bucket();
boolean jsonata = "JSONata".equals(language);
Map<String, Object> map = mapState(PASS_CHILD);
map.put("QueryLanguage", language);
map.put("ItemReader", Map.of("Resource", "arn:aws:states:::s3:getObject",
"ReaderConfig", Map.of("InputType", "JSON"),
jsonata ? "Arguments" : "Parameters", jsonata
? Map.of("Bucket", "{% $states.input.source %}", "Key", "{% $states.input.key %}")
: Map.of("Bucket.$", "$.source", "Key.$", "$.key")));
map.put("ResultWriter", Map.of("Resource", "arn:aws:states:::s3:putObject",
jsonata ? "Arguments" : "Parameters", jsonata
? Map.of("Bucket", "{% $states.input.target %}", "Prefix", "{% $states.input.prefix %}")
: Map.of("Bucket.$", "$.target", "Prefix.$", "$.prefix")));
String input = MAPPER.writeValueAsString(Map.of("source", reader.bucket(), "key", "items.json",
"target", target, "prefix", "out"));
String readGrant = policy(List.of(
Map.of("Effect", "Allow", "Action", reader.action(), "Resource", reader.resourceArn())));
String bothGrants = policy(List.of(
Map.of("Effect", "Allow", "Action", reader.action(), "Resource", reader.resourceArn()),
Map.of("Effect", "Allow", "Action", "s3:PutObject", "Resource", "arn:aws:s3:::" + target + "/out/*")));
Response noRead = terminal(start(machine(map, role(STATES_TRUST, READ_ONLY)), input));
Response noWrite = terminal(start(machine(map, role(STATES_TRUST, readGrant)), input));
assertFailed(noRead, READER_REFUSED);
assertFailed(noWrite, WRITER_REFUSED);
assertEquals(List.of(), keys(target));
Response allowed = terminal(start(machine(map, role(STATES_TRUST, bothGrants)), input));
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
assertEquals(2, keys(target).size());
}
/** A Map's own S3 grant says nothing about its children, whose tasks are evaluated as they always were. */
@Test
void aChildTaskIsEvaluatedOnItsOwn() throws Exception {
Reader reader = reader("JSON");
Map<String, Object> map = readerMap(reader);
map.put("ItemProcessor", processor(Map.of("StartAt", "Write", "States", Map.of("Write", Map.of("Type", "Task",
"Resource", "arn:aws:states:::s3:putObject",
"Parameters", Map.of("Bucket", reader.bucket(), "Key", "child", "Body", "x"), "End", true)))));
Response completed = terminal(start(machine(map, role(STATES_TRUST, reader.grant())), "{}"));
assertFailed(completed, "S3.AccessDeniedException");
}
/** No S3 call, nothing to evaluate: neither of these reaches the role at all. */
@ParameterizedTest
@ValueSource(strings = {"INLINE", "DISTRIBUTED"})
void aMapOverItsInputNeedsNothing(String mode) throws Exception {
Map<String, Object> map = mapState(processor(mode, Map.of("StartAt", "Item",
"States", Map.of("Item", Map.of("Type", "Pass", "End", true)))));
map.put("ItemsPath", "$.items");
Response completed = terminal(start(machine(map, role(LAMBDA_TRUST, READ_ONLY)), TWO_ITEMS));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
}
private Reader reader(String form) {
String bucket = bucket();
String arn = "arn:aws:s3:::" + bucket;
return switch (form) {
case "LIST" -> {
put(bucket, "data/a", "a");
put(bucket, "data/b", "b");
put(bucket, "other/c", "c");
yield new Reader(bucket, listMap(Map.of("Bucket", bucket)), "s3:ListBucket", arn, 3);
}
case "LIST_PREFIX" -> {
put(bucket, "data/a", "a");
put(bucket, "data/b", "b");
put(bucket, "other/c", "c");
yield new Reader(bucket, listMap(Map.of("Bucket", bucket, "Prefix", "data/")), "s3:ListBucket", arn, 2);
}
case "JSON" -> {
put(bucket, "items.json", "[1,2]");
yield new Reader(bucket, getMap(Map.of("Bucket", bucket, "Key", "items.json"), "JSON"),
"s3:GetObject", arn + "/items.json", 2);
}
case "JSONL" -> {
put(bucket, "items.jsonl", "{\"a\":1}\n{\"a\":2}\n{\"a\":3}\n");
yield new Reader(bucket, getMap(Map.of("Bucket", bucket, "Key", "items.jsonl"), "JSONL"),
"s3:GetObject", arn + "/items.jsonl", 3);
}
case "CSV" -> {
put(bucket, "items.csv", "h1,h2\na,b\n");
Map<String, Object> map = mapState(PASS_CHILD);
map.put("ItemReader", Map.of("Resource", "arn:aws:states:::s3:getObject",
"ReaderConfig", Map.of("InputType", "CSV", "CSVHeaderLocation", "FIRST_ROW"),
"Parameters", Map.of("Bucket", bucket, "Key", "items.csv")));
yield new Reader(bucket, map, "s3:GetObject", arn + "/items.csv", 1);
}
default -> throw new IllegalArgumentException(form);
};
}
private static Map<String, Object> readerMap(Reader reader) {
return new LinkedHashMap<>(reader.map());
}
private static Map<String, Object> listMap(Map<String, Object> parameters) {
Map<String, Object> map = mapState(PASS_CHILD);
map.put("ItemReader", Map.of("Resource", "arn:aws:states:::s3:listObjectsV2", "Parameters", parameters));
return map;
}
private static Map<String, Object> getMap(Map<String, Object> parameters, String inputType) {
Map<String, Object> map = mapState(PASS_CHILD);
map.put("ItemReader", Map.of("Resource", "arn:aws:states:::s3:getObject",
"ReaderConfig", Map.of("InputType", inputType), "Parameters", parameters));
return map;
}
private static Map<String, Object> writerMap(String bucket, String prefix, Map<String, Object> processor) {
Map<String, Object> map = mapState(processor);
map.put("ItemsPath", "$.items");
map.put("ResultWriter", writer(bucket, prefix));
return map;
}
private static Map<String, Object> writer(String bucket, String prefix) {
return Map.of("Resource", "arn:aws:states:::s3:putObject",
"Parameters", Map.of("Bucket", bucket, "Prefix", prefix));
}
private static Map<String, Object> mapState(Map<String, Object> processor) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("Type", "Map");
map.put("ItemProcessor", processor);
map.put("End", true);
return map;
}
private static Map<String, Object> processor(Map<String, Object> states) {
return processor("DISTRIBUTED", states);
}
private static Map<String, Object> processor(String mode, Map<String, Object> states) {
Map<String, Object> processor = new LinkedHashMap<>(states);
processor.put("ProcessorConfig", "INLINE".equals(mode) ? Map.of("Mode", mode)
: Map.of("Mode", mode, "ExecutionType", "STANDARD"));
return processor;
}
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 static String bucketStatement(String effect, String principal, String action, String resource) {
return policy(List.of(Map.of("Effect", effect, "Principal", Map.of("AWS", principal),
"Action", action, "Resource", resource)));
}
private String role(String trust, String policy) {
return sfn().role(ACCOUNT, "sfn-map-", trust, policy);
}
private String bucket() {
return bucket(ACCOUNT, REGION);
}
private String bucket(String account, String region) {
return sfn().bucket(account, region, "sfn-map-");
}
private void put(String bucket, String key, String body) {
put(bucket, key, body, auth(ACCOUNT, "s3"));
}
private void put(String bucket, String key, String body, String authorization) {
given().port(baseUri.getPort()).header("Authorization", authorization).body(body)
.put("/" + bucket + "/" + key).then().statusCode(200);
}
private void setBucketPolicy(String bucket, String policy) {
sfn().setBucketPolicy(ACCOUNT, bucket, policy);
}
private List<String> keys(String bucket) {
return given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "s3")).queryParam("list-type", "2")
.get("/" + bucket).then().statusCode(200).extract().xmlPath()
.getList("ListBucketResult.Contents.Key");
}
private String machine(Map<String, Object> map, String role) throws Exception {
return create(MAPPER.writeValueAsString(Map.of("StartAt", "Run", "States", Map.of("Run", map))), role);
}
private String machineWithFallback(Map<String, Object> map, String role) throws Exception {
return create(MAPPER.writeValueAsString(Map.of("StartAt", "Run", "States", Map.of("Run", map,
"Fallback", Map.of("Type", "Pass", "End", true),
"Done", Map.of("Type", "Pass", "End", true)))), role);
}
private String create(String definition, String role) {
return sfn().createMachine(ACCOUNT, "sfn-map-", definition, "STANDARD", role);
}
private String start(String machine, String input) {
return sfn().start(ACCOUNT, machine, input);
}
private Response terminal(String execution) throws Exception {
return sfn().terminal(ACCOUNT, execution, 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);
}
/**
* @param map the Map state reading it
* @param items how many items it reads
*/
private record Reader(String bucket, Map<String, Object> map, String action, String resourceArn, int items) {
String grant() {
return allow(resourceArn, action);
}
}
private StepFunctionsTestClient sfn() {
return new StepFunctionsTestClient(baseUri.getPort(), cleanup);
}
}
@@ -190,6 +190,30 @@ class StepFunctionsTaskCredentialsIntegrationTest {
.statusCode(200).body("executions.size()", Matchers.equalTo(0));
}
/** With enforcement off a Map's role is not looked at, so one that does not exist still reads and exports. */
@Test
void mapS3CallsRetainDefaultIamDisabledBehavior() throws Exception {
String bucket = sfn().bucket(SOURCE, "us-east-1", "credentials-map-");
String s3 = auth(SOURCE, "s3");
given().port(baseUri.getPort()).header("Authorization", s3).body("[1,2]")
.put("/" + bucket + "/items.json").then().statusCode(200);
String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Run", "States", Map.of("Run", Map.of(
"Type", "Map", "End", true,
"ItemReader", Map.of("Resource", "arn:aws:states:::s3:getObject",
"ReaderConfig", Map.of("InputType", "JSON"),
"Parameters", Map.of("Bucket", bucket, "Key", "items.json")),
"ResultWriter", Map.of("Resource", "arn:aws:states:::s3:putObject",
"Parameters", Map.of("Bucket", bucket, "Prefix", "out")),
"ItemProcessor", Map.of("ProcessorConfig", Map.of("Mode", "DISTRIBUTED", "ExecutionType", "STANDARD"),
"StartAt", "Item", "States", Map.of("Item", Map.of("Type", "Pass", "End", true)))))));
Response done = terminal(SOURCE, start(machine(SOURCE, definition, "STANDARD"), "{}"));
assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());
String manifest = MAPPER.readTree(done.jsonPath().getString("output")).path("ResultWriterDetails").path("Key").asText();
given().port(baseUri.getPort()).header("Authorization", s3).get("/" + bucket + "/" + manifest).then().statusCode(200);
}
@ParameterizedTest
@ValueSource(strings = {"direct", "optimized"})
void lambdaCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception {
@@ -262,19 +286,17 @@ class StepFunctionsTaskCredentialsIntegrationTest {
@ParameterizedTest
@ValueSource(strings = {"dynamodb:putItem", "aws-sdk:dynamodb:putItem", "s3:putObject", "aws-sdk:s3:putObject"})
void dataCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception {
String name = "credentials-" + UUID.randomUUID();
Map<String, Object> arguments;
if (integration.contains("dynamodb")) {
String name = "credentials-" + UUID.randomUUID();
dynamoDb("CreateTable", Map.of("TableName", name, "BillingMode", "PAY_PER_REQUEST",
"AttributeDefinitions", List.of(Map.of("AttributeName", "pk", "AttributeType", "S")),
"KeySchema", List.of(Map.of("AttributeName", "pk", "KeyType", "HASH"))));
cleanup.register(() -> dynamoDb("DeleteTable", Map.of("TableName", name)));
arguments = Map.of("TableName", name, "Item", Map.of("pk", Map.of("S", "a")));
} else {
given().port(baseUri.getPort()).header("Authorization", auth(SOURCE, "s3")).put("/" + name)
.then().statusCode(200);
cleanup.register(() -> EnforcementFixtures.removeBucket(baseUri.getPort(), auth(SOURCE, "s3"), name));
arguments = Map.of("Bucket", name, "Key", "a", "Body", "hello");
String bucket = sfn().bucket(SOURCE, "us-east-1", "credentials-");
arguments = Map.of("Bucket", bucket, "Key", "a", "Body", "hello");
}
assertDataTaskIsNotEvaluated(integration, arguments, "SUCCEEDED");
}
@@ -930,6 +930,62 @@ class TaskPermissionsTest {
control("aws-sdk:sfn:describeMapRun", "{\"MapRunArn\":\"" + mapRun + "\"}").permissions());
}
@Test
void itemReaderReadsTheObjectInTheStateMachinesPartition() {
assertEquals(List.of(new Permission("s3:GetObject", "arn:aws:s3:::b/k/x.json")),
TaskPermissions.itemReaderGetObject("b", "k/x.json", machine("aws")));
assertEquals(List.of(new Permission("s3:GetObject", "arn:aws-cn:s3:::b/k")),
TaskPermissions.itemReaderGetObject("b", "k", machine("aws-cn")));
}
@Test
void itemReaderNamingNoObjectNeedsNoPermission() {
assertEquals(List.of(), TaskPermissions.itemReaderGetObject(null, "k", machine("aws")));
assertEquals(List.of(), TaskPermissions.itemReaderGetObject(" ", "k", machine("aws")));
assertEquals(List.of(), TaskPermissions.itemReaderGetObject("b", null, machine("aws")));
}
@Test
void itemReaderListsTheBucketOfferingThePrefixItHas() {
assertEquals(List.of(new Permission("s3:ListBucket", "arn:aws:s3:::b")),
TaskPermissions.itemReaderListObjects("b", null, machine("aws")));
assertEquals(List.of(new Permission("s3:ListBucket", "arn:aws-us-gov:s3:::b",
Map.of("s3:prefix", List.of("data/")))),
TaskPermissions.itemReaderListObjects("b", "data/", machine("aws-us-gov")));
}
@Test
void itemReaderListingNoBucketNeedsNoPermission() {
assertEquals(List.of(), TaskPermissions.itemReaderListObjects(null, "p", machine("aws")));
assertEquals(List.of(), TaskPermissions.itemReaderListObjects("", "p", machine("aws")));
}
@ParameterizedTest
@CsvSource({"out,out/run/", "out/,out/run/", "'',run/", "/a//,/a//run/"})
void resultWriterExportIsEachObjectItWrites(String prefix, String base) throws Exception {
JsonNode location = MAPPER.valueToTree(Map.of("Bucket", "b", "Prefix", prefix));
assertEquals(List.of(new Permission("s3:PutObject", "arn:aws:s3:::b/" + base + "SUCCEEDED_0.json"),
new Permission("s3:PutObject", "arn:aws:s3:::b/" + base + "manifest.json")),
TaskPermissions.resultWriterExport(location, "run", false, machine("aws")));
assertEquals(List.of(new Permission("s3:PutObject", "arn:aws-cn:s3:::b/" + base + "SUCCEEDED_0.json"),
new Permission("s3:PutObject", "arn:aws-cn:s3:::b/" + base + "FAILED_0.json"),
new Permission("s3:PutObject", "arn:aws-cn:s3:::b/" + base + "manifest.json")),
TaskPermissions.resultWriterExport(location, "run", true, machine("aws-cn")));
}
@Test
void resultWriterExportWithNoPrefixIsUnderTheRun() throws Exception {
assertEquals("arn:aws:s3:::b/run/manifest.json", TaskPermissions.resultWriterExport(
json("{\"Bucket\":\"b\"}"), "run", false, machine("aws")).getLast().resourceArn());
}
@ParameterizedTest
@ValueSource(strings = {"{}", "{\"Bucket\":\"\"}", "{\"Bucket\":1}", "{\"Bucket\":\"b\",\"Prefix\":1}"})
void resultWriterNamingNoLocationNeedsNoPermission(String location) throws Exception {
assertEquals(List.of(), TaskPermissions.resultWriterExport(json(location), "run", true, machine("aws")));
}
/** {@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",
@@ -41,9 +41,13 @@ public final class StepFunctionsTestClient {
}
public static String allow(String resource, String... actions) {
return policy(List.of(Map.of("Effect", "Allow", "Action", List.of(actions), "Resource", resource)));
}
/** A policy document holding {@code statements}. */
public static String policy(List<Map<String, Object>> statements) {
try {
return MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", List.of(
Map.of("Effect", "Allow", "Action", List.of(actions), "Resource", resource))));
return MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", statements));
} catch (Exception e) {
throw new IllegalStateException(e);
}
@@ -53,6 +57,24 @@ public final class StepFunctionsTestClient {
return EnforcementFixtures.createRole(cleanup, port, account, "/", namePrefix + UUID.randomUUID(), trust, policy);
}
/** A bucket {@code account} creates in {@code region}, removed again by {@code cleanup}. */
public String bucket(String account, String region, String namePrefix) {
String name = namePrefix + UUID.randomUUID();
String authorization = auth(account, region, "s3");
given().port(port).header("Authorization", authorization)
.body("us-east-1".equals(region) ? "" : "<CreateBucketConfiguration><LocationConstraint>" + region
+ "</LocationConstraint></CreateBucketConfiguration>")
.put("/" + name).then().statusCode(200);
cleanup.register(() -> EnforcementFixtures.removeBucket(port, authorization, name));
return name;
}
/** Puts {@code policy} on {@code bucket} as {@code account}. */
public void setBucketPolicy(String account, String bucket, String policy) {
given().port(port).header("Authorization", auth(account, "s3")).body(policy)
.queryParam("policy", "").put("/" + bucket).then().statusCode(200);
}
public SqsTestQueue queue(SqsService service, String account, String region, String namePrefix) {
SqsTestQueue queue = SqsTestQueue.create(service, account, region, namePrefix);
cleanup.register(queue::delete);