mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
58c267e621
commit
c1c8b84a1f
13 files changed
+1147
-79
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user