mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -05:00
feat(stepfunctions): evaluate the execution role on DynamoDB, S3, RDS Data and Redshift Data tasks (#7722)
Under IAM enforcement, these tasks are now authorized as the execution role, or as the Credentials role a state names. DynamoDB is checked as a direct request is: batches on each table, transactions by each item's own action, ListTables on its regional collection and statements by what they do. S3 putObject is checked on the object in the bucket's own partition, and a bucket policy can grant or deny. RDS Data needs the action on the cluster and GetSecretValue on the secret. Redshift Data needs what an EventBridge target needs, and its statement operations are checked on any resource. A request naming nothing it can reach is left to its service. With enforcement off nothing changes. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
08be536e15
commit
87eaaab92d
14 files changed
+1563
-23
No files matched your search
@@ -104,6 +104,26 @@ public final class RequestResources {
|
||||
return named(resources, formats(table, operation), form, body, partition, region, accountId, stored);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARNs of the resources a JSON request body names, for a call that is not an HTTP request of its own, as a
|
||||
* state machine's task to its integrated service: as {@link #of} reads the same request, whatever endpoint it
|
||||
* would have reached.
|
||||
*/
|
||||
public static List<String> ofBody(String operation, JsonNode body, String partition, String region,
|
||||
String accountId, StoredResourceArns stored) {
|
||||
RequestResourceMembers.Table table = RequestResourceMembers.table();
|
||||
List<RequestResourceMembers.Resource> resources = operation == null ? null : table.operations().get(operation);
|
||||
if (resources == null || resources.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return named(resources, formats(table, operation), Map.of(), body, partition, region, accountId, stored);
|
||||
}
|
||||
|
||||
/** Whether the table holds the operation as one with no resource of its own, which is checked on {@code *}. */
|
||||
public static boolean actsOnNoResource(String operation) {
|
||||
return reads(operation) && RequestResourceMembers.table().operations().get(operation).isEmpty();
|
||||
}
|
||||
|
||||
/** The ARNs of the resources the request names, as {@link #of} reads them. */
|
||||
private static List<String> named(List<RequestResourceMembers.Resource> resources,
|
||||
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
|
||||
|
||||
@@ -1577,7 +1577,14 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
|
||||
private List<String> buildDynamoDbArns(ContainerRequestContext ctx, String region, String accountId) {
|
||||
JsonNode json = readJsonBody(ctx);
|
||||
return dynamoDbArns(readJsonBody(ctx), region, accountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The resources a DynamoDB request names, read from its body alone: the tables, or the stream, export,
|
||||
* import or other resource it gives, each as given when it gives an ARN, and {@code *} when it names none.
|
||||
*/
|
||||
public static List<String> dynamoDbArns(JsonNode json, String region, String accountId) {
|
||||
if (json != null && json.isObject()) {
|
||||
if (json.hasNonNull("TableName")) {
|
||||
String tableName = json.get("TableName").asText().trim();
|
||||
|
||||
@@ -24,6 +24,19 @@ public final class ResourcePolicyProviders {
|
||||
return policiesFor(providers, credentialScope, null, resourceArn);
|
||||
}
|
||||
|
||||
/** The ARN policies are evaluated on for {@code resourceArn}, as each provider resolves it. */
|
||||
public static String resolveResourceArn(Instance<ResourcePolicyProvider> providers, String credentialScope,
|
||||
String resourceArn) {
|
||||
if (providers == null || providers.isUnsatisfied()) {
|
||||
return resourceArn;
|
||||
}
|
||||
String resolved = resourceArn;
|
||||
for (ResourcePolicyProvider provider : providers) {
|
||||
resolved = provider.resolveResourceArn(credentialScope, resolved);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** The policies applying to an action, as determined by each resource-owning service. */
|
||||
public static List<ResourcePolicyProvider.ResourcePolicy> policiesFor(
|
||||
Instance<ResourcePolicyProvider> providers, String credentialScope, String action, String resourceArn) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
@@ -16,6 +17,11 @@ public class RedshiftDataJsonHandler {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
/** The workgroups and session targets the service finds, for a caller naming the resources of a request. */
|
||||
public StoredResourceArns storedResourceArns() {
|
||||
return service;
|
||||
}
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
return switch (action) {
|
||||
case "ExecuteStatement" -> Response.ok(service.executeStatement(request, region)).build();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.floci.aws.services.redshiftdata;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
@@ -110,9 +111,24 @@ public class RedshiftDataTargetSubmitter {
|
||||
? AwsArnUtils.Arn.of("redshift", region, account,
|
||||
"cluster:" + request.path("ClusterIdentifier").asText()).toString()
|
||||
: targetArn;
|
||||
List<Permission> permissions = permissions(
|
||||
batch ? "redshift-data:BatchExecuteStatement" : "redshift-data:ExecuteStatement",
|
||||
statementTarget, request, account, region);
|
||||
Optional<String> refusal = roleCheck.refusal(permissions);
|
||||
if (refusal.isPresent()) {
|
||||
throw new AwsException("AccessDeniedException", refusal.get(), 403);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What a Data API call on {@code target} needs: its action there and whatever authenticates it, read from the
|
||||
* request. A call on a session's target, which names neither a cluster nor a workgroup, has a session's own
|
||||
* credentials, so it needs only the action.
|
||||
*/
|
||||
public static List<Permission> permissions(String action, String target, JsonNode request, String account,
|
||||
String region) {
|
||||
List<Permission> permissions = new ArrayList<>();
|
||||
permissions.add(new Permission(
|
||||
batch ? "redshift-data:BatchExecuteStatement" : "redshift-data:ExecuteStatement", statementTarget));
|
||||
permissions.add(new Permission(action, target));
|
||||
// The Data API ignores a blank value, so it picks the credentials the same way.
|
||||
String secret = request.path("SecretArn").asText("");
|
||||
if (!secret.isBlank()) {
|
||||
@@ -122,8 +138,8 @@ public class RedshiftDataTargetSubmitter {
|
||||
permissions.add(new Permission("secretsmanager:GetSecretValue", secret));
|
||||
}
|
||||
} else if (request.has("WorkgroupName")) {
|
||||
permissions.add(new Permission("redshift-serverless:GetCredentials", targetArn));
|
||||
} else if (!request.path("DbUser").asText("").isBlank()) {
|
||||
permissions.add(new Permission("redshift-serverless:GetCredentials", target));
|
||||
} else if (request.has("ClusterIdentifier") && !request.path("DbUser").asText("").isBlank()) {
|
||||
String cluster = request.path("ClusterIdentifier").asText();
|
||||
permissions.add(new Permission("redshift:GetClusterCredentials",
|
||||
AwsArnUtils.Arn.of("redshift", region, account,
|
||||
@@ -132,10 +148,7 @@ public class RedshiftDataTargetSubmitter {
|
||||
AwsArnUtils.Arn.of("redshift", region, account,
|
||||
"dbname:" + cluster + "/" + request.path("Database").asText()).toString()));
|
||||
}
|
||||
Optional<String> refusal = roleCheck.refusal(permissions);
|
||||
if (refusal.isPresent()) {
|
||||
throw new AwsException("AccessDeniedException", refusal.get(), 403);
|
||||
}
|
||||
return permissions;
|
||||
}
|
||||
|
||||
private static void putIfPresent(ObjectNode request, String field, String value) {
|
||||
|
||||
@@ -1259,7 +1259,8 @@ public class AslExecutor {
|
||||
|
||||
/** Integrations {@link TaskPermissions} does not map stay unchecked, Lambda and API Gateway check their own. */
|
||||
private void authorizeTask(StatesIntegration integration, JsonNode input, StateMachine sm, JsonNode credentials) {
|
||||
Optional<TaskPermissions> required = TaskPermissions.of(integration, input, sm);
|
||||
Optional<TaskPermissions> required = TaskPermissions.of(integration, input, sm,
|
||||
redshiftDataHandler == null ? null : redshiftDataHandler.storedResourceArns());
|
||||
if (required.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ public class LambdaTaskAuthorizer {
|
||||
effectiveRoleArn = credentialsRoleArn;
|
||||
}
|
||||
for (Permission permission : permissions) {
|
||||
Optional<String> refusal = refusal(effectiveRoleArn, permission.action(), permission.resourceArn(),
|
||||
Optional<String> refusal = refusal(effectiveRoleArn, permission.action(), evaluatedOn(permission.resourceArn()),
|
||||
owner.region(), permission.conditionKeys());
|
||||
if (refusal.isPresent()) {
|
||||
throw new AslExecutor.FailStateException(deniedError, refusal.get());
|
||||
@@ -123,6 +123,15 @@ public class LambdaTaskAuthorizer {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN a permission is evaluated on, the one a direct request is: S3's global bucket namespace reaches a
|
||||
* bucket in another partition, whose ARN is in the bucket's partition and not the state machine's.
|
||||
*/
|
||||
private String evaluatedOn(String resourceArn) {
|
||||
return ANY_RESOURCE.equals(resourceArn) ? resourceArn : ResourcePolicyProviders.resolveResourceArn(
|
||||
resourcePolicies, AwsArnUtils.parse(resourceArn).service(), resourceArn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns why {@code roleArn} may not invoke {@code functionArn}, as Lambda's access denied
|
||||
* message words it, or nothing when it may.
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
package io.floci.aws.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RequestResources;
|
||||
import io.floci.aws.core.common.StoredResourceArns;
|
||||
import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser;
|
||||
import io.floci.aws.services.dynamodb.DynamoDbTableNames;
|
||||
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.sqs.SqsService;
|
||||
import io.floci.aws.services.stepfunctions.LambdaTaskAuthorizer.Permission;
|
||||
import io.floci.aws.services.stepfunctions.model.StateMachine;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@@ -22,8 +34,34 @@ import java.util.Set;
|
||||
*/
|
||||
record TaskPermissions(String deniedError, List<Permission> permissions) {
|
||||
|
||||
/** The permissions of an integration whose refusal is its prefix and {@code AccessDeniedException}. */
|
||||
static TaskPermissions accessDenied(String errorPrefix, List<Permission> permissions) {
|
||||
return new TaskPermissions(errorPrefix + "AccessDeniedException", permissions);
|
||||
}
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(TaskPermissions.class);
|
||||
private static final String ANY_RESOURCE = "*";
|
||||
private static final String DYNAMODB_OPTIMIZED_PREFIX = "DynamoDB.";
|
||||
private static final String DYNAMODB_SDK_PREFIX = "DynamoDb.";
|
||||
private static final String REDSHIFT_DATA_PREFIX = "RedshiftData.";
|
||||
private static final String RDS_DATA_PREFIX = "RdsData.";
|
||||
private static final Set<String> DYNAMODB_OPTIMIZED =
|
||||
Set.of("putItem", "getItem", "deleteItem", "updateItem", "scan");
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** The permissions of a mapped integration, or nothing for one that is not checked. */
|
||||
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine) {
|
||||
return of(integration, input, machine, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The permissions of a mapped integration, or nothing for one that is not checked.
|
||||
*
|
||||
* @param redshiftData finds the workgroup or the session target a Data API request names; without it a
|
||||
* workgroup is any workgroup and a session names nothing
|
||||
*/
|
||||
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
|
||||
StoredResourceArns redshiftData) {
|
||||
if (integration.is("sqs", "sendMessage")) {
|
||||
return Optional.of(sqsSendMessage("SQS.", input, machine));
|
||||
}
|
||||
@@ -39,6 +77,22 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
|
||||
if (integration.is("events", "putEvents")) {
|
||||
return Optional.of(eventsPutEvents(input, machine));
|
||||
}
|
||||
if (integration.isOptimizedService("dynamodb") && DYNAMODB_OPTIMIZED.contains(integration.api())) {
|
||||
return Optional.of(dynamoDbOptimized(integration.api(), input, machine));
|
||||
}
|
||||
if (integration.isSdkService("dynamodb")) {
|
||||
return Optional.of(dynamoDbSdk(AslExecutor.capitalizeFirst(integration.api()), input, machine));
|
||||
}
|
||||
if (integration.is("s3", "putObject") || integration.isSdk("s3", "putObject")) {
|
||||
return Optional.of(s3PutObject(input, machine));
|
||||
}
|
||||
if (integration.isSdkService("redshiftdata") && integration.suffix().isEmpty()) {
|
||||
return Optional.of(redshiftData(AslExecutor.capitalizeFirst(integration.api()), input, machine,
|
||||
redshiftData));
|
||||
}
|
||||
if (integration.isSdkService("rdsdata") && "executeStatement".equals(integration.api())) {
|
||||
return Optional.of(rdsDataExecuteStatement(input));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@@ -92,4 +146,134 @@ record TaskPermissions(String deniedError, List<Permission> permissions) {
|
||||
return new TaskPermissions("EventBridge.AccessDeniedException",
|
||||
buses.stream().map(bus -> new Permission("events:PutEvents", bus)).toList());
|
||||
}
|
||||
|
||||
/** The action on the table {@code TableName} gives, or nothing without one, which DynamoDB answers. */
|
||||
private static TaskPermissions dynamoDbOptimized(String api, JsonNode input, StateMachine machine) {
|
||||
String tableName = input.path("TableName").asText("").trim();
|
||||
if (tableName.isEmpty()) {
|
||||
return accessDenied(DYNAMODB_OPTIMIZED_PREFIX, List.of());
|
||||
}
|
||||
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
|
||||
return accessDenied(DYNAMODB_OPTIMIZED_PREFIX, List.of(new Permission(
|
||||
"dynamodb:" + AslExecutor.capitalizeFirst(api),
|
||||
ResourceArnBuilder.toDynamoDbTableArn(tableName, owner.region(), owner.accountId()))));
|
||||
}
|
||||
|
||||
/**
|
||||
* The check a direct request of the operation gets: a transaction by each item's own action on its table,
|
||||
* and anything else by its action on the resources it names, every table of a batch. A value that is not an
|
||||
* ARN where the request names a resource by one reaches nothing, so DynamoDB answers it.
|
||||
*/
|
||||
private static TaskPermissions dynamoDbSdk(String operation, JsonNode input, StateMachine machine) {
|
||||
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
|
||||
if ("TransactWriteItems".equals(operation) || "TransactGetItems".equals(operation)) {
|
||||
return accessDenied(DYNAMODB_SDK_PREFIX, dynamoDbTransaction(operation, input, owner));
|
||||
}
|
||||
String namedAs = "dynamodb:" + operation;
|
||||
List<String> named = RequestResources.reads(namedAs)
|
||||
? RequestResources.ofBody(namedAs, input, owner.partition(), owner.region(), owner.accountId(), null)
|
||||
: ResourceArnBuilder.dynamoDbArns(input, owner.region(), owner.accountId());
|
||||
String action = dynamoDbAction(operation, input);
|
||||
return accessDenied(DYNAMODB_SDK_PREFIX, named.stream()
|
||||
.filter(resource -> ANY_RESOURCE.equals(resource) || AwsArnUtils.isArn(resource))
|
||||
.map(resource -> new Permission(action, resource))
|
||||
.toList());
|
||||
}
|
||||
|
||||
/** {@code ExecuteStatement} is authorized by what its statement does, as a direct request is. */
|
||||
private static String dynamoDbAction(String operation, JsonNode input) {
|
||||
String statementAction = "ExecuteStatement".equals(operation)
|
||||
? DynamoDbPartiQLParser.iamAction(input.path("Statement").asText(null)) : null;
|
||||
return statementAction != null ? statementAction : "dynamodb:" + operation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Each item's own action on the table it names, resolved within the state machine's account as execution
|
||||
* resolves it, the same for a table named by its ARN. An item DynamoDB would refuse, whose table name does not
|
||||
* resolve or which names no table, needs nothing here: the service answers for the whole transaction.
|
||||
*/
|
||||
private static List<Permission> dynamoDbTransaction(String operation, JsonNode input, AwsArnUtils.Arn owner) {
|
||||
boolean read = "TransactGetItems".equals(operation);
|
||||
List<String> kinds = read ? List.of("Get") : List.of("Put", "Delete", "Update", "ConditionCheck");
|
||||
Map<String, List<String>> enclosing = Map.of("dynamodb:EnclosingOperation", List.of(operation));
|
||||
List<Permission> permissions = new ArrayList<>();
|
||||
JsonNode items = input.path("TransactItems");
|
||||
if (!items.isArray()) {
|
||||
return permissions;
|
||||
}
|
||||
for (JsonNode item : items) {
|
||||
for (String kind : kinds) {
|
||||
String tableName = item.path(kind).path("TableName").asText("").trim();
|
||||
if (tableName.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
String table = DynamoDbTableNames.resolveWithRegion(tableName, owner.region()).name();
|
||||
permissions.add(new Permission("dynamodb:" + kind + "Item",
|
||||
ResourceArnBuilder.toDynamoDbTableArn(table, owner.region(), owner.accountId()), enclosing));
|
||||
} catch (AwsException expected) {
|
||||
LOG.debugv("Transaction item names a table DynamoDB will refuse: {0}", tableName);
|
||||
}
|
||||
}
|
||||
}
|
||||
return permissions;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code s3:PutObject} on the object, in the state machine's partition: the authorizer moves it to the
|
||||
* bucket's own. A request naming no bucket or key is answered by the integration.
|
||||
*/
|
||||
private static TaskPermissions s3PutObject(JsonNode input, StateMachine machine) {
|
||||
String bucket = input.path("Bucket").asText("");
|
||||
String key = input.path("Key").asText(null);
|
||||
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",
|
||||
AwsArnUtils.Arn.global(partition, "s3", "", bucket + "/" + key).toString())));
|
||||
}
|
||||
|
||||
/**
|
||||
* The check an EventBridge target of the Data API gets, on what the request names: its cluster, its workgroup
|
||||
* or its session's target. An operation on no resource, as statement operations are in the service reference,
|
||||
* is checked on {@code *}. A request that names nothing it needs, or an operation the Data API does not
|
||||
* have, is answered by the service.
|
||||
*/
|
||||
private static TaskPermissions redshiftData(String operation, JsonNode input, StateMachine machine,
|
||||
StoredResourceArns stored) {
|
||||
String namedAs = "redshift-data:" + operation;
|
||||
String action = IamAuthorizedActions.actionFor("redshift-data", operation);
|
||||
if (!input.isObject() || !RequestResources.reads(namedAs)) {
|
||||
return accessDenied(REDSHIFT_DATA_PREFIX, List.of());
|
||||
}
|
||||
if (RequestResources.actsOnNoResource(namedAs)) {
|
||||
return accessDenied(REDSHIFT_DATA_PREFIX, List.of(new Permission(action, ANY_RESOURCE)));
|
||||
}
|
||||
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
|
||||
List<Permission> permissions = new ArrayList<>();
|
||||
for (String target : RequestResources.ofBody(namedAs, input, owner.partition(), owner.region(),
|
||||
owner.accountId(), stored)) {
|
||||
RedshiftDataTargetSubmitter.permissions(action, target, input, owner.accountId(), owner.region())
|
||||
.forEach(required -> permissions.add(new Permission(required.action(), required.resourceArn())));
|
||||
}
|
||||
return accessDenied(REDSHIFT_DATA_PREFIX, permissions);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code rds-data:ExecuteStatement} on the cluster and, since the Data API reads the database's credentials
|
||||
* from it as the caller, {@code secretsmanager:GetSecretValue} on the secret. The members are read in either
|
||||
* casing, as the task's request is recased. A request with no ARN for the cluster is answered by the service.
|
||||
*/
|
||||
private static TaskPermissions rdsDataExecuteStatement(JsonNode input) {
|
||||
JsonNode request = AslExecutor.recaseKeys(MAPPER, input, false);
|
||||
String resourceArn = request.path("resourceArn").asText(null);
|
||||
if (!AwsArnUtils.isArn(resourceArn)) {
|
||||
return accessDenied(RDS_DATA_PREFIX, List.of());
|
||||
}
|
||||
String secretArn = request.path("secretArn").asText(null);
|
||||
Permission execute = new Permission("rds-data:ExecuteStatement", resourceArn);
|
||||
return accessDenied(RDS_DATA_PREFIX, AwsArnUtils.isArn(secretArn)
|
||||
? List.of(execute, new Permission("secretsmanager:GetSecretValue", secretArn)) : List.of(execute));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user