diff --git a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java index 2916a7105c..104fa711fd 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/AslExecutor.java @@ -1505,6 +1505,12 @@ public class AslExecutor { return invokeNonIntegrationResource(resource, input, taskToken); } + // AWS SDK integrations support Request Response and .waitForTaskToken only, never Run a Job, + // so a .sync or .sync:2 form is refused before anything is called. + if (integration.sdk() && integration.suffix().startsWith(".sync")) { + throw OptimizedIntegrations.unsupported(integration); + } + if (iamEnforcementEnabled()) { authorizeTask(integration, input, sm, credentials, taskToken, taskAccount); } @@ -4228,13 +4234,15 @@ 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)); + String versionId = resolvedParameters.path("VersionId").asText(null); + authorizeMapS3(sm, "States.ItemReaderFailed", + TaskPermissions.itemReaderGetObject(bucket, key, versionId, sm)); if (bucket == null || key == null) { throw new FailStateException("States.Runtime", "ItemReader Parameters must include Bucket and Key"); } try { - S3Object object = s3Service.getObject(bucket, key); + S3Object object = s3Service.getObject(bucket, key, versionId); if ("JSONL".equals(inputType)) { return new ResolvedMapItems(applyMaxItems(maxItems, readJsonLines(object.getData())), MapItemsSource.ITEM_READER_ARRAY); diff --git a/src/main/java/io/floci/aws/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/floci/aws/services/stepfunctions/StepFunctionsService.java index f982ed5359..423fc2b450 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/StepFunctionsService.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/StepFunctionsService.java @@ -154,6 +154,10 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store private static final List JSONPATH_PAYLOAD_TEMPLATES = List.of( "Parameters", "ResultSelector", "ItemSelector", "Assign", "Credentials", "ItemBatcher/BatchInput", "ItemReader/Parameters", "ResultWriter/Parameters"); + // The fields the Developer Guide lists for ItemReader. A List, for the same fixed emission order + // the field lists above commit to. + private static final List ITEM_READER_FIELDS = List.of( + "Resource", "Parameters", "Arguments", "ReaderConfig"); private static final Set ITEM_READER_INPUT_TYPES = Set.of( "MANIFEST", "JSON", "CSV", "JSONL", "PARQUET"); private static final Set RESULT_WRITER_TRANSFORMATIONS = Set.of("NONE", "COMPACT", "FLATTEN"); @@ -3198,6 +3202,12 @@ public class StepFunctionsService implements Resettable, ResourceProvider, Store private void validateItemReader(String statePath, JsonNode stateDef, boolean jsonata, List errors) { JsonNode itemReader = stateDef.get("ItemReader"); + itemReader.fieldNames().forEachRemaining(field -> { + if (!ITEM_READER_FIELDS.contains(field)) { + errors.add(EXPLICIT_LOCATION_MARKER + "Field '" + field + "' is not supported" + + MARKER_PAYLOAD_SEPARATOR + statePath + "/ItemReader"); + } + }); String resource = itemReader.path("Resource").asText(null); if (resource != null && !isItemReaderResource(resource)) { errors.add("The field 'Resource' does not match any of the allowed values. Examples: " diff --git a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java index a641d1111b..4847ed5677 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.core.common.AwsException; +import io.floci.aws.core.common.IamConditionContextResolver; import io.floci.aws.core.common.PassedRoleLookups; import io.floci.aws.core.common.RequestChecks; import io.floci.aws.core.common.RequestResources; @@ -18,6 +19,7 @@ import io.floci.aws.services.eventbridge.EventBridgeService; import io.floci.aws.services.iam.IamAuthorizedActions; import io.floci.aws.services.redshiftdata.RedshiftDataTargetSubmitter; import io.floci.aws.services.s3.S3ConditionKeys; +import io.floci.aws.services.s3.S3ObjectActions; import io.floci.aws.services.s3.S3ResourceArns; import io.floci.aws.services.sqs.SqsService; import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission; @@ -439,14 +441,18 @@ record TaskPermissions(String deniedError, List permissions, boolean } /** - * 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. + * What a Distributed Map's {@code ItemReader} needs to read one object: {@code s3:GetObject} on it, or + * {@code s3:GetObjectVersion} offering {@code s3:versionid} when the reader names a {@code VersionId}, as S3 + * checks a direct read of a version. A request naming no bucket or key needs nothing, and is answered by the + * reader or by S3. */ - static List itemReaderGetObject(String bucket, String key, StateMachine machine) { + static List itemReaderGetObject(String bucket, String key, String versionId, StateMachine machine) { if (bucket == null || bucket.isBlank() || key == null) { return List.of(); } - return List.of(new Permission("s3:GetObject", s3ObjectArn(machine, bucket, key))); + return List.of(new Permission(S3ObjectActions.forVersion("s3:GetObject", versionId), + s3ObjectArn(machine, bucket, key), + versionId == null ? Map.of() : Map.of(IamConditionContextResolver.VERSION_ID, List.of(versionId)))); } /** diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java index 669f4bc03f..c912f70556 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java @@ -11,6 +11,8 @@ import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -854,6 +856,42 @@ class StepFunctionsAwsSdkTaskIntegrationTest { assertEquals("Scheduler.ValidationException", result.path("caughtError").asText()); } + /** + * AWS SDK integrations support Request Response and Wait for Callback only, never Run a Job, so a + * {@code .sync} form is refused before the service is called. + */ + @ParameterizedTest + @Order(28) + @ValueSource(strings = {"sfn:startExecution.sync", "sfn:startExecution.sync:2", "scheduler:deleteSchedule.sync", + "cloudformation:listStacks.sync:2"}) + void aSyncFormOfAnSdkIntegrationIsRefused(String integration) { + String resource = "arn:aws:states:::aws-sdk:" + integration; + String smArn = createStateMachine("aws-sdk-sync-" + integration.replaceAll("[^A-Za-z0-9]", "-"), """ + { + "StartAt": "Call", + "States": { + "Call": { + "Type": "Task", + "Resource": "RESOURCE", + "Parameters": {"StateMachineArn": "CHILD", "Name": "aws-sdk-sync-missing"}, + "End": true + } + } + } + """.replace("RESOURCE", resource).replace("CHILD", quickChildArn)); + try { + Response describe = waitForTerminalState(startExecution(smArn, "{}")); + + assertEquals("FAILED", describe.jsonPath().getString("status"), describe.asString()); + assertEquals("States.TaskFailed", describe.jsonPath().getString("error")); + assertEquals("Unsupported resource: " + resource, describe.jsonPath().getString("cause")); + } finally { + given().header("X-Amz-Target", "AWSStepFunctions.DeleteStateMachine").contentType(SFN_CONTENT_TYPE) + .body("{\"stateMachineArn\": \"" + smArn + "\"}") + .when().post("/").then().statusCode(200); + } + } + @Test @Order(27) void schedulerValidationErrorsAreCatchableFromCreateAndUpdateTasks() throws Exception { diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsMapS3IamIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsMapS3IamIntegrationTest.java index 899ab07de4..e6ced04dad 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsMapS3IamIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsMapS3IamIntegrationTest.java @@ -324,6 +324,38 @@ class StepFunctionsMapS3IamIntegrationTest { assertTrue(completed.jsonPath().getString("cause").contains("not yet implemented"), completed.asString()); } + /** + * A reader naming a {@code VersionId} reads that version, which the Developer Guide's ItemReader page lists for + * getObject, and is checked as {@code s3:GetObjectVersion}, as a direct read of a version is. + */ + @Test + void aReaderNamingAVersionReadsThatVersionWithItsVersionAction() throws Exception { + String bucket = bucket(); + given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "s3")) + .body("Enabled") + .put("/" + bucket + "?versioning").then().statusCode(200); + String first = given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "s3")).body("[1,2]") + .put("/" + bucket + "/items.json").then().statusCode(200).extract().header("x-amz-version-id"); + put(bucket, "items.json", "[1,2,3]"); + Map map = getMap(Map.of("Bucket", bucket, "Key", "items.json", "VersionId", first), "JSON"); + String object = "arn:aws:s3:::" + bucket + "/items.json"; + + Response read = terminal(start(machine(map, role(STATES_TRUST, allow(object, "s3:GetObjectVersion"))), "{}")); + assertEquals("SUCCEEDED", read.jsonPath().getString("status"), read.asString()); + assertEquals(2, MAPPER.readTree(read.jsonPath().getString("output")).size()); + + Response refused = terminal(start(machine(map, role(STATES_TRUST, allow(object, "s3:GetObject"))), "{}")); + assertFailed(refused, READER_REFUSED); + assertTrue(refused.jsonPath().getString("cause").contains("s3:GetObjectVersion"), refused.asString()); + + // As S3 does for a direct read of a version, the reader offers s3:versionid, so a deny naming it applies. + Response denied = terminal(start(machine(map, role(STATES_TRUST, policy(List.of( + Map.of("Effect", "Allow", "Action", "s3:GetObjectVersion", "Resource", object), + Map.of("Effect", "Deny", "Action", "s3:GetObjectVersion", "Resource", object, + "Condition", Map.of("StringEquals", Map.of("s3:versionid", first))))))), "{}")); + assertFailed(denied, READER_REFUSED); + } + @Test void anExecutionRoleAllowedToWriteExports() throws Exception { String bucket = bucket(); diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java index d71fa181f1..8f135cefe6 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsValidateStateMachineDefinitionIntegrationTest.java @@ -623,6 +623,33 @@ class StepFunctionsValidateStateMachineDefinitionIntegrationTest { .body("diagnostics[0].location", equalTo("/States/ProcessItems/ItemReader/Resource")); } + /** The Developer Guide lists Resource, Parameters or Arguments, and ReaderConfig: any other field is refused. */ + @Test + void anItemReaderFieldTheGuideDoesNotListIsRefused() { + String def = """ + {"StartAt":"ProcessItems","States":{"ProcessItems":{"Type":"Map", + "ItemReader":{"Resource":"arn:aws:states:::s3:getObject", + "ReaderConfig":{"InputType":"JSON"}, + "Parameters":{"Bucket":"map-inputs","Key":"workers.json"}, + "Credentials":{"RoleArn":"arn:aws:iam::000000000000:role/reader"}}, + "ItemProcessor":{"ProcessorConfig":{"Mode":"DISTRIBUTED","ExecutionType":"STANDARD"}, + "StartAt":"PassItem","States":{"PassItem":{"Type":"Pass","End":true}}}, + "End":true}}} + """; + + validateDefinition(def) + .then().statusCode(200) + .body("result", equalTo("FAIL")) + .body("diagnostics", hasSize(1)) + .body("diagnostics[0].code", equalTo("SCHEMA_VALIDATION_FAILED")) + .body("diagnostics[0].message", equalTo("Field 'Credentials' is not supported")) + .body("diagnostics[0].location", equalTo("/States/ProcessItems/ItemReader")); + createStateMachine("item-reader-unknown-field", def) + .then().statusCode(400) + .body("__type", containsString("InvalidDefinition")) + .body("message", containsString("Field 'Credentials' is not supported")); + } + @Test void unsupportedItemReaderInputType_returnsFailWithSchemaError() { given().contentType(CT).header("X-Amz-Target", TARGET) diff --git a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java index f8635ab434..6ddbc773a8 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java @@ -1199,16 +1199,23 @@ class TaskPermissionsTest { @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"))); + TaskPermissions.itemReaderGetObject("b", "k/x.json", null, machine("aws"))); assertEquals(List.of(new Permission("s3:GetObject", "arn:aws-cn:s3:::b/k")), - TaskPermissions.itemReaderGetObject("b", "k", machine("aws-cn"))); + TaskPermissions.itemReaderGetObject("b", "k", null, machine("aws-cn"))); + } + + @Test + void itemReaderNamingAVersionReadsItAsTheVersionAction() { + assertEquals(List.of(new Permission("s3:GetObjectVersion", "arn:aws:s3:::b/k", + Map.of("s3:versionid", List.of("v1")))), + TaskPermissions.itemReaderGetObject("b", "k", "v1", machine("aws"))); } @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"))); + assertEquals(List.of(), TaskPermissions.itemReaderGetObject(null, "k", null, machine("aws"))); + assertEquals(List.of(), TaskPermissions.itemReaderGetObject(" ", "k", null, machine("aws"))); + assertEquals(List.of(), TaskPermissions.itemReaderGetObject("b", null, null, machine("aws"))); } @Test