feat(iam): read DynamoDB from the generated tables, its statement and item permissions from the developer guide (#9235)

DynamoDB is read from iam-request-resources.json now, and
ResourceArnBuilder's DynamoDB branch, the registry's PartiQL action,
the condition resolver's mapping of transaction items and statements to
actions and Step Functions' copy of all three are gone, leaving iam in
HAND_BUILT.

Which action each transaction item and each PartiQL statement is
checked as comes from the developer guide, vendored by
fetch_dynamodb_permissions.py into
tools/aws/sources/dynamodb-permissions.json and read under
PERMISSION_SOURCES: the PartiQL IAM page's required permissions and the
transactions page's paragraph on each kind of item.

- Each transaction item is checked as the action of its kind on the
  table its TableName names (TransactItems[].Put.TableName as
  dynamodb:PutItem), each PartiQL statement as the action of its verb on
  the table or index it names, an EXISTS statement as the SELECT it
  evaluates, which DynamoDB's own parser reads through the new
  StoredResourceArns.statement hook before it binds the request's
  parameters. A request naming nothing is checked as its own action on
  *; a state machine's task naming nothing is left to DynamoDB, as
  before.
- RequestResources.targets replaces checkedAs: each element of a list is
  read apart and returned with its check, so the condition resolver
  still gives each item or statement its own keys and
  dynamodb:EnclosingOperation.
- BatchGetItem and BatchWriteItem name their tables by the keys of
  RequestItems, which the generator reads from botocore (RequestItems{}).
- RequestResourceMembers reads Name{}, Name[].Item.Field and statement
  rows (statement, verb, names).
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-22 22:04:18 -04:00
1 parent 4d481ebccb
commit 3a1ea212f0
27 files changed
+1298 -661

No files matched your search

@@ -14,7 +14,6 @@ import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.services.iam.IamActionRegistry;
import io.floci.aws.services.iam.IamService;
import io.floci.aws.services.iam.ResourceArnBuilder;
import io.floci.aws.services.iam.model.IamRole;
import io.floci.aws.services.iam.model.IamUser;
import io.floci.aws.services.lambdaweb.LambdaWebService;
@@ -1347,91 +1346,45 @@ public class IamConditionContextResolver {
return modes.isEmpty() ? List.of("NONE") : List.copyOf(modes);
}
/** One transaction item keeps its action, table and condition keys together. */
record DynamoDbTransactionItem(String action, String resource, Map<String, List<String>> context) {
}
/**
* Resolves every recognized item before the handler can mutate anything. Unknown envelope fields
* cannot turn item checks back into a transaction-verb permission check.
* The condition keys of one check of an operation whose request's parts each take an action (see
* {@link RequestResources#targets}): those {@link #resolve} gives the request for {@code action} when the check
* is of the request itself ({@code part} null), and otherwise those of the part: a DynamoDB transaction item's
* own keys with {@code dynamodb:EnclosingOperation} naming the transaction, or a batch's or transaction's PartiQL
* statement's, with {@code dynamodb:EnclosingOperation} for a transaction's. Null when it gives none.
*/
List<DynamoDbTransactionItem> dynamoDbTransactionItems(String action, ContainerRequestContext ctx,
String region, String accountId) {
if ("dynamodb:BatchExecuteStatement".equals(action) || "dynamodb:ExecuteTransaction".equals(action)) {
return dynamoDbStatementItems(action, ctx, region, accountId);
public Map<String, List<String>> resolvePart(String credentialScope, String action, String operation,
ContainerRequestContext ctx, JsonNode part, String region) {
if (part == null || !"dynamodb".equals(credentialScope) || operation == null) {
return resolve(credentialScope, action, ctx);
}
boolean read = "dynamodb:TransactGetItems".equals(action);
if (!read && !"dynamodb:TransactWriteItems".equals(action)) {
return List.of();
}
JsonNode body = bufferedJsonBody(ctx);
JsonNode items = body == null ? null : body.get("TransactItems");
if (items == null || !items.isArray()) {
return List.of();
}
List<DynamoDbTransactionItem> checks = new ArrayList<>();
List<String> operations = read ? List.of("Get") : List.of("Put", "Delete", "Update", "ConditionCheck");
for (JsonNode item : items) {
for (String operation : operations) {
JsonNode request = item.get(operation);
if (request == null || !request.isObject()) {
continue;
}
String tableName = targetTableName(request);
if (tableName == null) {
continue;
}
// Execution resolves ARN inputs within the request account; authorize that same table.
String executionTable = DynamoDbTableNames.resolveWithRegion(tableName, region).name();
String itemAction = "dynamodb:" + operation + "Item";
TableDefinition table = describeTargetTable(executionTable);
DynamoDbConditionKeys.Result keys = read
? DynamoDbConditionKeys.extractTransactionGet(request, table)
: DynamoDbConditionKeys.extract(itemAction, request, table);
Map<String, List<String>> context = new LinkedHashMap<>();
context.put("dynamodb:EnclosingOperation", List.of(read ? "TransactGetItems" : "TransactWriteItems"));
putKeyConditions(context, keys);
if (!read && request.hasNonNull("ReturnValuesOnConditionCheckFailure")) {
context.put("dynamodb:ReturnValues",
List.of(request.path("ReturnValuesOnConditionCheckFailure").asText()));
}
checks.add(new DynamoDbTransactionItem(itemAction,
ResourceArnBuilder.toDynamoDbTableArn(executionTable, region, accountId), context));
String enclosing = operation.substring(operation.indexOf(':') + 1);
Map<String, List<String>> context = new LinkedHashMap<>();
if (part.has("Statement")) {
String statement = DynamoDbConditionKeys.partiQLStatement(part);
if ("ExecuteTransaction".equals(enclosing)) {
context.put("dynamodb:EnclosingOperation", List.of(enclosing));
}
putKeyConditions(context, DynamoDbConditionKeys.extract(action, part,
describeTargetTable(DynamoDbPartiQLParser.extractTable(statement))));
return context;
}
return checks;
}
/**
* One check per PartiQL statement of a batch or transaction, on the statement's own PartiQL action and
* table, as a single ExecuteStatement is checked. A statement with no PartiQL action keeps the batch's
* own action, which no PartiQL grant covers. Statements of a transaction carry
* {@code dynamodb:EnclosingOperation} {@code ExecuteTransaction}.
*/
private List<DynamoDbTransactionItem> dynamoDbStatementItems(String action, ContainerRequestContext ctx,
String region, String accountId) {
boolean transaction = "dynamodb:ExecuteTransaction".equals(action);
String operation = action.substring("dynamodb:".length());
List<DynamoDbTransactionItem> checks = new ArrayList<>();
for (JsonNode request : DynamoDbConditionKeys.partiQLStatementRequests(operation, bufferedJsonBody(ctx))) {
String statement = DynamoDbConditionKeys.partiQLStatement(request);
String statementAction = DynamoDbPartiQLParser.iamAction(statement);
String tableName = DynamoDbPartiQLParser.extractTable(statement);
String resource = tableName == null || tableName.isEmpty()
? "*" : ResourceArnBuilder.toDynamoDbTableArn(tableName, region, accountId);
Map<String, List<String>> context = new LinkedHashMap<>();
if (transaction) {
context.put("dynamodb:EnclosingOperation", List.of("ExecuteTransaction"));
}
if (statementAction == null) {
checks.add(new DynamoDbTransactionItem(action, resource, context));
continue;
}
putKeyConditions(context, DynamoDbConditionKeys.extract(statementAction, request,
describeTargetTable(tableName)));
checks.add(new DynamoDbTransactionItem(statementAction, resource, context));
boolean read = "TransactGetItems".equals(enclosing);
String tableName = targetTableName(part);
TableDefinition table;
try {
table = describeTargetTable(tableName == null ? null
: DynamoDbTableNames.resolveWithRegion(tableName, region).name());
} catch (AwsException e) {
table = null;
}
return checks;
context.put("dynamodb:EnclosingOperation", List.of(enclosing));
putKeyConditions(context, read ? DynamoDbConditionKeys.extractTransactionGet(part, table)
: DynamoDbConditionKeys.extract(action, part, table));
if (!read && part.hasNonNull("ReturnValuesOnConditionCheckFailure")) {
context.put("dynamodb:ReturnValues", List.of(part.path("ReturnValuesOnConditionCheckFailure").asText()));
}
return context;
}
/** Request-wide context for callers that do not yet have a resolved resource. */
@@ -596,40 +596,29 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
RequestPrincipal principal = RequestPrincipal.caller(callerArns.orElse(null));
List<IamConditionContextResolver.DynamoDbTransactionItem> transactionItems =
"dynamodb".equals(credentialScope)
? conditionContextResolver.dynamoDbTransactionItems(action, ctx, region, accountId)
: List.of();
if (!transactionItems.isEmpty()) {
for (IamConditionContextResolver.DynamoDbTransactionItem item : transactionItems) {
Map<String, List<String>> itemContext = new HashMap<>(item.context());
callerArns.ifPresent(arns -> arns.putPrincipalKeys(itemContext));
if (abortIfDenied(ctx, caller, principal, item.action(), credentialScope,
resolveResourceArns(credentialScope, List.of(item.resource())), List.of(itemContext),
region, accountId, akid)) {
// An operation AWS authorizes by actions its request's parts each take (KMS's ReEncrypt, kms:ReEncryptFrom on
// the key it decrypts with and kms:ReEncryptTo on the one it encrypts with; each of a DynamoDB transaction's
// items and each PartiQL statement, by its own) is checked as each on what the table gives it, with that
// part's condition keys, not as the operation's own; one naming nothing of any is checked as its own on *.
if (RequestResources.checkedByParts(resolvedOperation.operation())) {
List<RequestResources.Target> targets = arnBuilder.targets(credentialScope, resolvedOperation.operation(),
ctx, region, accountId, requestPartition());
if (targets.isEmpty()) {
targets = List.of(new RequestResources.Target(action, List.of("*"), null));
}
for (RequestResources.Target target : targets) {
Map<String, List<String>> resolved = conditionContextResolver.resolvePart(credentialScope,
target.action(), resolvedOperation.operation(), ctx, target.element(), region);
Map<String, List<String>> partContext = resolved == null ? new HashMap<>() : new HashMap<>(resolved);
callerArns.ifPresent(arns -> arns.putPrincipalKeys(partContext));
if (abortIfDenied(ctx, caller, principal, target.action(), action, credentialScope,
resolveResourceArns(credentialScope, target.resources()), List.of(partContext), region,
accountId, akid)) {
return;
}
}
return;
}
// An operation AWS authorizes by several actions (KMS's ReEncrypt, by kms:ReEncryptFrom on the key it decrypts
// with and kms:ReEncryptTo on the one it encrypts with) is checked as each on the resources the table gives
// it, with that action's condition keys, and not as the operation's own.
Map<String, List<String>> checkedAs = arnBuilder.checkedAs(credentialScope, resolvedOperation.operation(), ctx,
region, accountId, requestPartition());
for (Map.Entry<String, List<String>> checked : checkedAs.entrySet()) {
Map<String, List<String>> resolved =
conditionContextResolver.resolve(credentialScope, checked.getKey(), ctx);
Map<String, List<String>> checkedContext = resolved == null ? new HashMap<>() : new HashMap<>(resolved);
callerArns.ifPresent(arns -> arns.putPrincipalKeys(checkedContext));
if (abortIfDenied(ctx, caller, principal, checked.getKey(), action, credentialScope,
resolveResourceArns(credentialScope, checked.getValue()), List.of(checkedContext), region,
accountId, akid)) {
return;
}
}
if (checkedAs.isEmpty() && abortIfDenied(ctx, caller, principal, action, credentialScope, resources,
targetContexts, region, accountId, akid)) {
} else if (abortIfDenied(ctx, caller, principal, action, credentialScope, resources, targetContexts,
region, accountId, akid)) {
return;
}
if (abortIfRolePassDenied(ctx, caller, principal, callerArns.orElse(null), action, credentialScope,
@@ -44,11 +44,11 @@ final class RequestResourceMembers {
"[A-Za-z][A-Za-z0-9_]*(\\[])?(\\.[A-Za-z][A-Za-z0-9_]*(\\[])?)?"
+ "|[A-Za-z][A-Za-z0-9_]*\\{\\}(\\.[A-Za-z][A-Za-z0-9_]*){1,2}");
/**
* A member filling a variable may also be a field of a structure, or of each of a list's structures or of a map's
* structure values, one value for each.
* A member filling a variable may also be a field of a structure, or of each of a list's structures, or of a field
* of each of them, or of a map's structure values, one value for each, or a map's keys ({@code Name{}}).
*/
private static final Pattern FILL_MEMBER = Pattern.compile("[A-Za-z][A-Za-z0-9_]*(\\[]|\\[]\\.[A-Za-z][A-Za-z0-9_]*"
+ "|\\{}\\.[A-Za-z][A-Za-z0-9_]*|\\.[A-Za-z][A-Za-z0-9_]*)?");
+ "(\\.[A-Za-z][A-Za-z0-9_]*)?|\\{}|\\{}\\.[A-Za-z][A-Za-z0-9_]*|\\.[A-Za-z][A-Za-z0-9_]*)?");
/** An ARN format's leading resource type word, and the rest of its resource. */
private static final Pattern RESOURCE_PART = Pattern.compile(
"^arn:\\$\\{Partition}:[^:]*:[^:]*:[^:]*:([A-Za-z][A-Za-z0-9-]*)(.*)$");
@@ -78,6 +78,8 @@ final class RequestResourceMembers {
"made", "find", "endpoint", "default", "whenDefault", "unlessDefault", "defaults", "partialArn");
/** The keys of a resource named through a member naming another of its service's own: it is read no other way. */
private static final Set<String> THROUGH_KEYS = Set.of("types", "through", "when", "endpoint");
/** The keys of a resource a statement the request carries names, which its service parses. */
private static final Set<String> STATEMENT_KEYS = Set.of("types", "statement", "verb", "names");
/** The keys of a resource its service acts on for a request naming none of it: it is read no other way. */
private static final Set<String> DEFAULT_KEYS = Set.of("type", "fill", "when", "default", "endpoint");
@@ -100,9 +102,12 @@ final class RequestResourceMembers {
return name + (map ? "{}" : list ? "[]" : "") + (field == null ? "" : "." + field.path());
}
/** Whether it is a field of each of a list's structures, which gives one value for each of them. */
/**
* Whether it is a field of each of a list's structures, which gives one value for each of them; a field of a
* field of each ({@code TransactItems[].Put.TableName}) gives the values of those that have it.
*/
boolean eachElement() {
return list && field != null && !field.list();
return list && field != null && !field.list() && field.field() == null;
}
}
@@ -238,13 +243,25 @@ final class RequestResourceMembers {
* service finds (ECS's {@code taskDefinitions[]}). A
* {@code partialArn} type's members may give its ARN with the leading parts left out, its account and resource
* ({@code 123456789012:function:my-function}) or its Region too, which the reader completes in the request's
* partition, and Region where the value leaves that out.
* partition, and Region where the value leaves that out. A resource a {@code statement} the request carries names
* is the one of its types whose every variable the service's parse of the statement names, by the word
* {@code names} gives each variable, when the statement's verb is {@code verb}.
*/
record Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault,
Map<String, String> defaults, boolean partialArn) {
Map<String, String> defaults, boolean partialArn, Member statement, String verb,
Map<String, String> names) {
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
Map<String, String> fixed, boolean made, List<Member> find, String endpoint, Member through,
boolean byDefault, Map<String, String> whenDefault, Map<String, String> unlessDefault,
Map<String, String> defaults, boolean partialArn) {
this(types, arn, fill, when, unless, arnOf, account, fixed, made, find, endpoint, through, byDefault,
whenDefault, unlessDefault, defaults, partialArn, null, null, Map.of());
}
Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
Map<String, List<String>> unless, Map<String, String> arnOf, Member account,
@@ -342,10 +359,10 @@ final class RequestResourceMembers {
* client ({@code locatedApart}), whose vendored route tells a request's client. Each operation's {@code forwarded}
* requests are those its service makes to another as the caller, and its {@code statements} those it makes as the
* caller to run each statement its request may carry. An {@code unread} operation names what it acts on in a body
* the reader does not read. An operation AWS authorizes by several actions, none of its own name, has its
* the reader does not read. An operation AWS authorizes by actions its request's parts each take has its
* resources under the one each is checked as ({@code checkedAs}, in the order the file gives the actions: KMS's
* ReEncrypt, {@code kms:ReEncryptFrom} on its source key and {@code kms:ReEncryptTo} on its destination key), and
* none in {@code operations}.
* ReEncrypt, {@code kms:ReEncryptFrom} on its source key and {@code kms:ReEncryptTo} on its destination key; a
* DynamoDB transaction's items and PartiQL statements), and none in {@code operations}.
*/
record Table(Map<String, List<Resource>> operations, Map<String, List<String>> types,
Map<String, List<Created>> creates, Map<String, List<Resource>> makes,
@@ -752,6 +769,9 @@ final class RequestResourceMembers {
throw new IllegalStateException(RESOURCE_NAME + " serves a resource of " + operation
+ " on no endpoint prefix");
}
if (resource.has("statement")) {
return statementResource(operation, resource, formats);
}
Set<String> keys = resource.has("through") ? THROUGH_KEYS : resource.has("arn") ? ARN_KEYS : FILL_KEYS;
List<String> unknown = resource.properties().stream().map(Map.Entry::getKey)
.filter(key -> !keys.contains(key)).toList();
@@ -865,6 +885,31 @@ final class RequestResourceMembers {
defaults(operation, type, resource.path("defaults"), fill, formats), partialArn);
}
/**
* A resource a statement the request carries names, of one of {@code types}: each variable of each type given the
* word the service's parse of the statement names it by, and the statement's verb.
*/
private static Resource statementResource(String operation, JsonNode resource, Map<String, ArnFormat> formats) {
List<String> types = resource.path("types").valueStream().map(JsonNode::asText).toList();
Map<String, String> names = new LinkedHashMap<>();
resource.path("names").properties().forEach(name -> names.put(name.getKey(), name.getValue().asText("")));
Set<String> variables = types.stream().filter(formats::containsKey)
.flatMap(type -> VARIABLE.matcher(formats.get(type).format()).results().map(match -> match.group(1)))
.filter(variable -> !Set.of("Partition", "Region", "Account").contains(variable))
.collect(Collectors.toSet());
String verb = resource.path("verb").asText("");
if (types.isEmpty() || !formats.keySet().containsAll(types) || !names.keySet().equals(variables)
|| names.containsValue("") || verb.isEmpty() || resource.properties().stream()
.map(Map.Entry::getKey).anyMatch(key -> !STATEMENT_KEYS.contains(key))) {
throw new IllegalStateException(RESOURCE_NAME + " names a resource of " + operation + " by the statement "
+ resource.path("statement") + ", no member, verb and types with a format whose every variable "
+ "it names");
}
return new Resource(types, null, Map.of(), Map.of(), Map.of(), Map.of(), null, Map.of(), false, List.of(),
null, null, false, Map.of(), Map.of(), Map.of(), false,
fillMember(operation, resource.path("statement").asText("")), verb, Map.copyOf(names));
}
/**
* The {@code defaults} of a resource: each member filling a variable mapped to the type whose format is that
* variable alone, whose default the member names when a request leaves it out; empty when it has none.
@@ -967,13 +1012,19 @@ final class RequestResourceMembers {
/**
* A member filling a variable: {@code Name}, {@code Name[]}, or a field of a structure, {@code Name.Field}, of
* each of a list's structures, {@code Name[].Field}, or of each of a map's structure values, {@code Name{}.Field}.
* each of a list's structures, {@code Name[].Field}, or of a field of each of them, {@code Name[].Item.Field}, or
* of each of a map's structure values, {@code Name{}.Field}, or a map's keys, {@code Name{}}.
*/
private static Member fillMember(String operation, String path) {
if (!FILL_MEMBER.matcher(path).matches()) {
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path + ", which is no member");
}
return arnMember(operation, path);
int dot = path.indexOf('.');
if (dot < 0) {
return member(operation, path);
}
Member outer = member(operation, path.substring(0, dot));
return new Member(outer.name(), outer.list(), fillMember(operation, path.substring(dot + 1)), outer.map());
}
/**
@@ -9,7 +9,6 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.core.MultivaluedMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
@@ -79,6 +78,15 @@ public final class RequestResources {
return readable(RequestResourceMembers.table(), operation);
}
/**
* Whether the table checks the operation as actions its request's parts each take ({@link #targets}) instead of
* its own action.
*/
public static boolean checkedByParts(String operation) {
RequestResourceMembers.Table table = RequestResourceMembers.table();
return readable(table, operation) && table.checkedAs().containsKey(operation);
}
/** Whether {@code table} reads the operation's requests: it has an entry for it, and not an unread one. */
static boolean readable(RequestResourceMembers.Table table, String operation) {
return operation != null && table.operations().containsKey(operation) && !table.unread().contains(operation);
@@ -203,32 +211,107 @@ public final class RequestResources {
}
/**
* The actions an operation AWS authorizes by several actions, none of its own name, is checked as instead of its
* own, each with the ARNs of the resources the request names that it is checked on, as {@link #of} reads them:
* KMS's ReEncrypt, {@code kms:ReEncryptFrom} on its source key and {@code kms:ReEncryptTo} on its destination key.
* An action the request names no resource of is checked on {@code *}. Empty for every other operation, which is
* checked as its own action on what {@link #of} gives.
* One check of an operation AWS authorizes by actions its request's parts each take: {@code action} on
* {@code resources}, which {@code element} names, the part of the request they come from (a transaction's item, a
* batch's statement), or null for the request itself.
*/
public static Map<String, List<String>> checkedAs(String operation, ContainerRequestContext ctx, String partition,
String region, String accountId, StoredResourceArns stored,
Map<String, String> labels) {
public record Target(String action, List<String> resources, JsonNode element) {
}
/**
* The checks an operation AWS authorizes by actions its request's parts each take is checked as instead of its
* own action, as the table's {@code checkedAs} gives them, read as {@link #of} reads the rest: KMS's ReEncrypt,
* {@code kms:ReEncryptFrom} on its source key and {@code kms:ReEncryptTo} on its destination key; each of a
* DynamoDB transaction's items, as the action of its kind on its table, and each PartiQL statement, as the action
* of its verb on what it names. A resource read from each element of a list is checked apart for each element, with
* that element. An action the table gives no resource of is checked on {@code *}, and one whose resources the
* request names none of is not checked. Empty for every other operation, which is checked as its own action on
* what {@link #of} gives, and for one whose request names nothing of any of its actions.
*/
public static List<Target> targets(String operation, ContainerRequestContext ctx, String partition, String region,
String accountId, StoredResourceArns stored, Map<String, String> labels) {
RequestResourceMembers.Table table = RequestResourceMembers.table();
Map<String, List<RequestResourceMembers.Resource>> actions = !readable(table, operation) ? null
: table.checkedAs().get(operation);
if (actions == null) {
return Map.of();
return List.of();
}
Map<String, String> sent = IamConditionContextResolver.formParameters(ctx);
JsonNode body = sent.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null;
Map<String, String> form = ec2Query(table, operation, located(table, operation, sent, ctx, labels));
Map<String, List<String>> checked = new LinkedHashMap<>();
Map<String, List<RequestResourceMembers.Resource>> served = new LinkedHashMap<>();
actions.forEach((action, resources) -> served.put(action, served(resources, ctx)));
return targets(operation, served, formats(table, operation), form, body, partition, region, accountId, stored);
}
/**
* The checks a JSON request body is made of, as {@link #targets} reads the same request, for a call that is not an
* HTTP request of its own, as a state machine's task to its integrated service.
*/
public static List<Target> targetsOfBody(String operation, JsonNode body, String partition, String region,
String accountId, StoredResourceArns stored) {
RequestResourceMembers.Table table = RequestResourceMembers.table();
Map<String, List<RequestResourceMembers.Resource>> actions = !readable(table, operation) ? null
: table.checkedAs().get(operation);
return actions == null ? List.of()
: targets(operation, actions, formats(table, operation), Map.of(), body, partition, region, accountId,
stored);
}
private static List<Target> targets(String operation, Map<String, List<RequestResourceMembers.Resource>> actions,
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
JsonNode body, String partition, String region, String accountId,
StoredResourceArns stored) {
List<Target> found = new ArrayList<>();
actions.forEach((action, resources) -> {
List<RequestResourceMembers.Resource> read = served(resources, ctx);
List<String> arns = read.isEmpty() ? List.of() : named(operation, read, formats(table, operation), form,
body, partition, region, accountId, stored);
checked.put(action, arns.isEmpty() ? List.of("*") : arns);
if (resources.isEmpty()) {
found.add(new Target(action, List.of("*"), null));
return;
}
for (RequestResourceMembers.Resource resource : resources) {
RequestResourceMembers.Member each = eachElementRead(resource);
if (each == null || body == null || !body.path(each.name()).isArray()) {
List<String> arns = named(operation, List.of(resource), formats, form, body, partition, region,
accountId, stored);
if (!arns.isEmpty()) {
found.add(new Target(action, arns, null));
}
continue;
}
for (JsonNode element : body.path(each.name())) {
// The request with this element alone in its list, sharing the body's other members: nothing is
// copied but the body's top level.
ObjectNode alone = JsonNodeFactory.instance.objectNode();
alone.setAll((ObjectNode) body);
alone.putArray(each.name()).add(element);
List<String> arns = named(operation, List.of(resource), formats, form, alone, partition, region,
accountId, stored);
if (!arns.isEmpty()) {
found.add(new Target(action, arns, partOf(element, each.field())));
}
}
}
});
return Collections.unmodifiableMap(checked);
return List.copyOf(found);
}
/**
* The list a resource is read from a field of each element of, its statement's or its one variable's member;
* null for any other.
*/
private static RequestResourceMembers.Member eachElementRead(RequestResourceMembers.Resource resource) {
RequestResourceMembers.Member member = resource.statement() != null ? resource.statement()
: resource.fill().size() == 1 ? resource.fill().values().iterator().next() : null;
return member != null && member.list() && member.field() != null ? member : null;
}
/** The structure of an element a field path ends in: {@code Put} of {@code Put.TableName}, the element itself. */
private static JsonNode partOf(JsonNode element, RequestResourceMembers.Member field) {
JsonNode part = element;
for (RequestResourceMembers.Member step = field; step.field() != null; step = step.field()) {
part = part.path(step.name());
}
return part;
}
/**
@@ -406,6 +489,8 @@ public final class RequestResources {
.ifPresent(format -> addNamed(arns, format.checked(named), format.awsOwned(),
partition, region, accountId, stored));
}
} else if (resource.statement() != null) {
statement(arns, resource, formats, form, body, partition, region, accountId, stored);
} else if (resource.through() != null) {
through(arns, resource, formats, form, body, region, stored);
} else if (!resource.find().isEmpty()) {
@@ -1018,6 +1103,43 @@ public final class RequestResources {
return named != null && named.pattern().matcher(value).matches();
}
/**
* The resources the statements a {@code statement} resource reads name, as the service parses each: for one of
* the resource's verb, the first of its types, most variables first, whose every variable the parse names by the
* word the table gives it (a DynamoDB index's {@code TableName} and {@code IndexName} by its {@code table} and
* {@code index}, else its table); none for another verb, a statement the service cannot parse, or no service.
*/
private static void statement(Set<String> arns, RequestResourceMembers.Resource resource,
Map<String, RequestResourceMembers.ArnFormat> formats, Map<String, String> form,
JsonNode body, String partition, String region, String accountId,
StoredResourceArns stored) {
if (stored == null) {
return;
}
List<String> types = resource.types().stream()
.sorted(Comparator.comparingLong((String type) -> VARIABLE.matcher(formats.get(type).format())
.results().count()).reversed()).toList();
for (String value : values(form, body, resource.statement())) {
Optional<StoredResourceArns.Statement> parsed = stored.statement(value);
if (parsed.isEmpty() || !resource.verb().equals(parsed.get().verb())) {
continue;
}
for (String type : types) {
Map<String, String> filling = new LinkedHashMap<>();
VARIABLE.matcher(formats.get(type).format()).results().map(match -> match.group(1))
.filter(resource.names()::containsKey)
.forEach(variable -> Optional.ofNullable(parsed.get().names()
.get(resource.names().get(variable))).ifPresent(name -> filling.put(variable, name)));
if (filling.keySet().containsAll(resource.names().keySet().stream().filter(variable ->
formats.get(type).format().contains("${" + variable + "}")).toList())) {
arns.add(formats.get(type).checked(render(formats.get(type).format(), filling, partition, region,
accountId)));
break;
}
}
}
}
/**
* The ARN of a resource the namespace's service stores under the name the request gives: the one {@code stored}
* finds the caller's resource of that name under in the Region.
@@ -1254,7 +1376,11 @@ public final class RequestResources {
return;
}
if (member.map()) {
if (value.isObject()) {
// A map's keys name what its values describe (DynamoDB's RequestItems, keyed by table); a field of its
// values, what each names.
if (value.isObject() && member.field() == null) {
value.fieldNames().forEachRemaining(key -> add(values, key));
} else if (value.isObject()) {
for (JsonNode element : value) {
addElement(values, element, member.field());
}
@@ -140,6 +140,22 @@ public interface StoredResourceArns {
return copy;
}
/**
* A statement a request carries, as its service's parser reads it: its {@code verb} ({@code SELECT}) and the names
* of what it acts on, by the word the table gives each ({@code table}, {@code index}).
*/
record Statement(String verb, Map<String, String> names) {
}
/**
* The verb of {@code statement} and the names of what it acts on, as the service's own parser reads the
* statement it runs (a DynamoDB PartiQL statement's table and index), which the table checks as the action of
* that verb; empty when it reads no such statement, which its handler then refuses.
*/
default Optional<Statement> statement(String statement) {
return Optional.empty();
}
/**
* Whether the service acts on the resource {@code arn} names, one {@link #find} gave, for a request another service
* forwards as the caller: false for a KMS key disabled or pending deletion, which KMS refuses such a request with,
@@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.VendoredResources;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@@ -51,24 +50,6 @@ final class DynamoDbConditionKeyMembers {
return values;
}
/**
* Every element of the list that holds {@code member} under {@code key}'s recorded paths
* ({@code Statements.*.Statement} yields each {@code Statements} element), malformed ones included
* so the caller can still refuse them.
*/
static List<JsonNode> listElements(String operation, String key, String member, JsonNode body) {
List<JsonNode> lists = new ArrayList<>();
for (JsonNode path : TABLE.path("members").path(operation).path(key)) {
String[] steps = path.asText().split("\\.");
if (steps.length > 2 && member.equals(steps[steps.length - 1]) && "*".equals(steps[steps.length - 2])) {
collect(body, Arrays.copyOf(steps, steps.length - 2), 0, lists);
}
}
List<JsonNode> elements = new ArrayList<>();
lists.stream().filter(JsonNode::isArray).forEach(list -> list.forEach(elements::add));
return elements;
}
static JsonNode itemBody(String operation, String prefix, JsonNode body) {
if (body == null || !body.isObject()) {
return body;
@@ -187,14 +187,6 @@ public final class DynamoDbConditionKeys {
"TransactGetItems", "TransactItems.*.Get.", body), table);
}
/**
* The statement requests of a PartiQL batch or transaction ({@code BatchExecuteStatement},
* {@code ExecuteTransaction}), found through the request paths the condition-key table records.
*/
public static List<JsonNode> partiQLStatementRequests(String operation, JsonNode body) {
return DynamoDbConditionKeyMembers.listElements(operation, "dynamodb:Attributes", "Statement", body);
}
/** The statement text of one PartiQL request, or {@code null} when it has none. */
public static String partiQLStatement(JsonNode request) {
return DynamoDbConditionKeyMembers.values("ExecuteStatement", "dynamodb:Attributes", "Statement", request)
@@ -8,6 +8,7 @@ import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -123,29 +124,59 @@ public class DynamoDbPartiQLParser {
}
}
/** A statement's verb and the table and index it acts on. */
public record StatementTarget(String verb, String table, String index) {
}
/**
* The IAM action for a single statement, using the same keyword tokens as execution. A statement
* the tokenizer refuses has no action here, so it is authorized as ExecuteStatement and the
* handler reports why it is malformed, as {@link #extractTable} leaves it.
* The verb of a single statement and the table and index it names, as execution parses it once its FROM clause
* checks pass, before it binds the request's parameters or checks the statement's terms: {@code SELECT},
* {@code INSERT}, {@code UPDATE} or {@code DELETE}, and for an {@code EXISTS} statement those of "the SELECT
* statement that the function evaluates"
* (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-functions.exists.html). A statement whose
* FROM clause execution refuses is read from its keyword tokens, with no index (an update may lead with
* {@code FROM}). Empty for a statement the tokenizer refuses or of any other verb, or one naming no table, which
* the handler refuses after the credential and policy checks.
*/
public static String iamAction(String statement) {
public static Optional<StatementTarget> target(String statement) {
if (statement == null || statement.isBlank()) {
return null;
return Optional.empty();
}
AtomicReference<Stmt> reached = new AtomicReference<>();
try {
parse(statement, List.of(), true, reached::set);
} catch (Exception ignored) {
// Execution checks the statement's terms against the request's parameters after its target, and reports a
// malformed statement after the credential and policy checks have run.
}
if (reached.get() != null) {
StatementTarget target = switch (reached.get()) {
case Stmt.Select select -> new StatementTarget("SELECT", select.table(), select.index());
case Stmt.Insert insert -> new StatementTarget("INSERT", insert.table(), null);
case Stmt.Update update -> new StatementTarget("UPDATE", update.table(), update.index());
case Stmt.Delete delete -> new StatementTarget("DELETE", delete.table(), delete.index());
case Stmt.Exists exists -> new StatementTarget("SELECT", exists.table(), exists.select().index());
};
return target.table() == null || target.table().isEmpty() ? Optional.empty()
: Optional.of(new StatementTarget(target.verb(), target.table(),
target.index() == null || target.index().isEmpty() ? null : target.index()));
}
List<Token> tokens;
try {
tokens = tokenize(statement.trim());
} catch (Exception ignored) {
// Execution reports malformed statements after credential and policy checks have run.
return null;
return Optional.empty();
}
return switch (tokens.getFirst().type()) {
case SELECT -> "dynamodb:PartiQLSelect";
case INSERT -> "dynamodb:PartiQLInsert";
case UPDATE, FROM -> "dynamodb:PartiQLUpdate";
case DELETE -> "dynamodb:PartiQLDelete";
String verb = switch (tokens.getFirst().type()) {
case SELECT -> "SELECT";
case INSERT -> "INSERT";
case UPDATE, FROM -> "UPDATE";
case DELETE -> "DELETE";
default -> null;
};
String table = extractTable(statement);
return verb == null || table == null || table.isEmpty() ? Optional.empty()
: Optional.of(new StatementTarget(verb, table, null));
}
/**
@@ -11,11 +11,34 @@ import java.util.Optional;
/**
* What IAM asks DynamoDB of the resources a request names: the tags of the table an ARN names, or of the table whose
* index it names, from the selected backend.
* index it names, from the selected backend, and the verb, table and index of a PartiQL statement, as execution
* parses it.
*/
@ApplicationScoped
public class DynamoDbStoredResourceArns implements StoredResourceArns {
/**
* What IAM reads of a request checked apart from the tables the backend holds, as a state machine's task: the verb,
* table and index of each PartiQL statement it carries, as execution parses them. DynamoDB mints no id into an ARN
* a request names by its name, so it finds nothing this class would.
*/
public static final StoredResourceArns STATEMENTS = new StoredResourceArns() {
@Override
public String namespace() {
return "dynamodb";
}
@Override
public Optional<String> find(String type, List<String> names, String region) {
return Optional.empty();
}
@Override
public Optional<Statement> statement(String statement) {
return parsed(statement);
}
};
private final DynamoDbTableAccess tables;
@Inject
@@ -38,4 +61,16 @@ public class DynamoDbStoredResourceArns implements StoredResourceArns {
public Map<String, String> storedTags(String arn) {
return tables.storedTags(arn);
}
/** A PartiQL statement's verb and the table and index it names, as execution parses it. */
@Override
public Optional<Statement> statement(String statement) {
return parsed(statement);
}
private static Optional<Statement> parsed(String statement) {
return DynamoDbPartiQLParser.target(statement)
.map(target -> new Statement(target.verb(), target.index() == null
? Map.of("table", target.table()) : Map.of("table", target.table(), "index", target.index())));
}
}
@@ -1,6 +1,5 @@
package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsProtocolClaimFilter;
import io.floci.aws.core.common.AwsQueryServiceResolver;
import io.floci.aws.core.common.IamOperation;
@@ -9,7 +8,6 @@ import io.floci.aws.core.common.RequestResources;
import io.floci.aws.core.common.ResteasyRequests;
import io.floci.aws.core.common.SignedServiceRoute;
import io.floci.aws.core.common.WireProtocol;
import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser;
import io.floci.aws.services.eks.EksController;
import io.floci.aws.services.s3.S3BucketSubresources;
import io.floci.aws.services.s3.S3ObjectActions;
@@ -44,7 +42,6 @@ import java.util.regex.Pattern;
public class IamActionRegistry {
private static final Logger LOG = Logger.getLogger(IamActionRegistry.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private final IamRestRoutes restRoutes;
@@ -576,15 +573,11 @@ public class IamActionRegistry {
return target != null && target.contains(".") ? target.substring(target.lastIndexOf('.') + 1) : null;
}
/** The action for a dispatched operation, including statement-dependent JSON and CBOR calls. */
/**
* The action for a dispatched operation. One AWS authorizes by what its request's parts each do (a DynamoDB
* PartiQL statement by its verb) is checked as the actions the request-resources table gives those parts.
*/
public String resolveOperation(String credentialScope, String operationName, ContainerRequestContext ctx) {
if ("dynamodb".equals(credentialScope) && "ExecuteStatement".equals(operationName)) {
String statement = RequestBodyReader.documentField(ctx, MAPPER, "Statement");
String statementAction = DynamoDbPartiQLParser.iamAction(statement);
if (statementAction != null) {
return statementAction;
}
}
return IamAuthorizedActions.actionFor(credentialScope, operationName);
}
@@ -18,15 +18,11 @@ import jakarta.ws.rs.container.ContainerRequestContext;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Constructs the target resource ARN for a request so the policy evaluator
@@ -126,7 +122,6 @@ public class ResourceArnBuilder {
return namedResources(credentialScope, operation, ctx, region, accountId, partition);
}
return switch (credentialScope) {
case "dynamodb" -> buildDynamoDbArns(ctx, region, accountId);
case "iam" -> buildIamArns(ctx, region, accountId);
default -> namedResources(credentialScope, operation, ctx, region, accountId, partition);
};
@@ -150,18 +145,17 @@ public class ResourceArnBuilder {
}
/**
* The actions an operation AWS authorizes by several actions is checked as instead of its own, each with the
* resources the request names that it is checked on (see {@link RequestResources#checkedAs}), read as
* {@link #buildResources} reads the others: KMS's ReEncrypt, {@code kms:ReEncryptFrom} on its source key and
* {@code kms:ReEncryptTo} on its destination key. Empty for every other operation.
* The checks an operation AWS authorizes by actions its request's parts each take is made of, each action on the
* resources its part names (see {@link RequestResources#targets}), read as {@link #buildResources} reads the
* others: KMS's ReEncrypt, a DynamoDB transaction's items or PartiQL statements. Empty for every other operation.
*/
public Map<String, List<String>> checkedAs(String credentialScope, String operation, ContainerRequestContext ctx,
String region, String accountId, String partition) {
public List<RequestResources.Target> targets(String credentialScope, String operation, ContainerRequestContext ctx,
String region, String accountId, String partition) {
if (credentialScope == null || operation == null || !operation.startsWith(credentialScope + ":")
|| !RequestResources.reads(operation)) {
return Map.of();
return List.of();
}
return RequestResources.checkedAs(operation, ctx, partition, region, accountId,
return RequestResources.targets(operation, ctx, partition, region, accountId,
storedResourceArns(credentialScope), labels(credentialScope, ctx));
}
@@ -779,167 +773,6 @@ public class ResourceArnBuilder {
return null;
}
// ── DynamoDB ─────────────────────────────────────────────────────────────────
private String buildDynamoDbArn(ContainerRequestContext ctx, String region, String accountId) {
List<String> arns = buildDynamoDbArns(ctx, region, accountId);
return arns.isEmpty() ? "*" : arns.getFirst();
}
private List<String> buildDynamoDbArns(ContainerRequestContext ctx, String region, String accountId) {
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();
if (!tableName.isEmpty()) {
return List.of(toDynamoDbTableArn(tableName, region, accountId));
}
}
if (json.path("TableCreationParameters").hasNonNull("TableName")) {
String tableName = json.path("TableCreationParameters").get("TableName").asText().trim();
if (!tableName.isEmpty()) {
return List.of(toDynamoDbTableArn(tableName, region, accountId));
}
}
if (json.hasNonNull("ResourceArn")) {
String resourceArn = json.get("ResourceArn").asText().trim();
if (!resourceArn.isEmpty()) {
return List.of(resourceArn);
}
}
if (json.hasNonNull("TableArn")) {
String tableArn = json.get("TableArn").asText().trim();
if (!tableArn.isEmpty()) {
return List.of(tableArn);
}
}
if (json.hasNonNull("StreamArn")) {
String streamArn = json.get("StreamArn").asText().trim();
if (!streamArn.isEmpty()) {
return List.of(streamArn);
}
}
if (json.hasNonNull("ExportArn")) {
String exportArn = json.get("ExportArn").asText().trim();
if (!exportArn.isEmpty()) {
return List.of(exportArn);
}
}
if (json.hasNonNull("ImportArn")) {
String importArn = json.get("ImportArn").asText().trim();
if (!importArn.isEmpty()) {
return List.of(importArn);
}
}
// AWS authorizes RestoreTableToPointInTime on its source table.
if (json.hasNonNull("SourceTableArn")) {
String sourceTableArn = json.get("SourceTableArn").asText().trim();
if (!sourceTableArn.isEmpty()) {
return List.of(sourceTableArn);
}
}
if (json.hasNonNull("SourceTableName")) {
String sourceTableName = json.get("SourceTableName").asText().trim();
if (!sourceTableName.isEmpty()) {
return List.of(toDynamoDbTableArn(sourceTableName, region, accountId));
}
}
if (json.hasNonNull("RequestItems") && json.get("RequestItems").isObject()) {
Set<String> arns = new LinkedHashSet<>();
Iterator<String> fieldNames = json.get("RequestItems").fieldNames();
while (fieldNames.hasNext()) {
String table = fieldNames.next().trim();
if (!table.isEmpty()) {
arns.add(toDynamoDbTableArn(table, region, accountId));
}
}
if (!arns.isEmpty()) {
return new ArrayList<>(arns);
}
}
if (json.hasNonNull("TransactItems") && json.get("TransactItems").isArray()) {
Set<String> arns = new LinkedHashSet<>();
JsonNode items = json.get("TransactItems");
for (JsonNode item : items) {
String t = null;
if (item.hasNonNull("Put") && item.get("Put").hasNonNull("TableName")) {
t = item.get("Put").get("TableName").asText();
} else if (item.hasNonNull("Delete") && item.get("Delete").hasNonNull("TableName")) {
t = item.get("Delete").get("TableName").asText();
} else if (item.hasNonNull("Update") && item.get("Update").hasNonNull("TableName")) {
t = item.get("Update").get("TableName").asText();
} else if (item.hasNonNull("ConditionCheck") && item.get("ConditionCheck").hasNonNull("TableName")) {
t = item.get("ConditionCheck").get("TableName").asText();
} else if (item.hasNonNull("Get") && item.get("Get").hasNonNull("TableName")) {
t = item.get("Get").get("TableName").asText();
}
if (t != null) {
t = t.trim();
if (!t.isEmpty()) {
arns.add(toDynamoDbTableArn(t, region, accountId));
}
}
}
if (!arns.isEmpty()) {
return new ArrayList<>(arns);
}
}
if (json.hasNonNull("Statement")) {
String stmt = json.get("Statement").asText().trim();
String table = extractDynamoDbTableFromPartiQL(stmt);
if (table != null && !table.isEmpty()) {
return List.of(toDynamoDbTableArn(table, region, accountId));
}
}
if (json.hasNonNull("Statements") && json.get("Statements").isArray()) {
Set<String> arns = new LinkedHashSet<>();
for (JsonNode s : json.get("Statements")) {
if (s.hasNonNull("Statement")) {
String table = extractDynamoDbTableFromPartiQL(s.get("Statement").asText());
if (table != null && !table.isEmpty()) {
arns.add(toDynamoDbTableArn(table, region, accountId));
}
}
}
if (!arns.isEmpty()) {
return new ArrayList<>(arns);
}
}
if (json.hasNonNull("TransactStatements") && json.get("TransactStatements").isArray()) {
Set<String> arns = new LinkedHashSet<>();
for (JsonNode s : json.get("TransactStatements")) {
if (s.hasNonNull("Statement")) {
String table = extractDynamoDbTableFromPartiQL(s.get("Statement").asText());
if (table != null && !table.isEmpty()) {
arns.add(toDynamoDbTableArn(table, region, accountId));
}
}
}
if (!arns.isEmpty()) {
return new ArrayList<>(arns);
}
}
}
return List.of("*");
}
private static String extractDynamoDbTableFromPartiQL(String statement) {
return io.floci.aws.services.dynamodb.DynamoDbPartiQLParser.extractTable(statement);
}
public static String toDynamoDbTableArn(String tableName, String region, String accountId) {
if (AwsArnUtils.isArnFor(tableName, "dynamodb")) {
return tableName;
}
return AwsArnUtils.Arn.of("dynamodb", region, accountId, "table/" + tableName).toString();
}
// ── Helpers ──────────────────────────────────────────────────────────────────
/** The request's JSON or CBOR body, buffered so the handler still reads it, or null when it has none. */
@@ -8,11 +8,9 @@ import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestChecks;
import io.floci.aws.core.common.RequestResources;
import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.services.dynamodb.DynamoDbPartiQLParser;
import io.floci.aws.services.dynamodb.DynamoDbTableNames;
import io.floci.aws.services.dynamodb.DynamoDbStoredResourceArns;
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;
@@ -275,76 +273,49 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
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.
* The action on the table the request names, as the request-resources table reads it, or nothing for a request
* naming none, which DynamoDB answers.
*/
private static TaskPermissions dynamoDbSdk(String operation, JsonNode input, StateMachine machine) {
private static TaskPermissions dynamoDbOptimized(String api, JsonNode input, StateMachine machine) {
String action = "dynamodb:" + AslExecutor.capitalizeFirst(api);
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))
return accessDenied(DYNAMODB_OPTIMIZED_PREFIX, RequestResources.ofBody(action, input, owner.partition(),
owner.region(), owner.accountId(), null).stream()
.filter(AwsArnUtils::isArn)
.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.
* The check a direct request of the operation gets, as the request-resources table reads it: one whose request's
* parts each take an action (a transaction's items, each PartiQL statement) by each part's action on what it names,
* a transaction's with {@code dynamodb:EnclosingOperation}, and anything else by its action on the resources it
* names, every table of a batch. A request whose parts name nothing, or a value that is not an ARN where the
* request names a resource by one, reaches nothing, so DynamoDB answers it.
*/
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);
}
private static TaskPermissions dynamoDbSdk(String operation, JsonNode input, StateMachine machine) {
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
String namedAs = "dynamodb:" + operation;
if (RequestResources.checkedByParts(namedAs)) {
boolean transaction = operation.startsWith("Transact") || "ExecuteTransaction".equals(operation);
List<Permission> permissions = new ArrayList<>();
for (RequestResources.Target target : RequestResources.targetsOfBody(namedAs, input, owner.partition(),
owner.region(), owner.accountId(), DynamoDbStoredResourceArns.STATEMENTS)) {
Map<String, List<String>> context = transaction && target.element() != null
? Map.of("dynamodb:EnclosingOperation", List.of(operation)) : Map.of();
target.resources().stream()
.filter(resource -> ANY_RESOURCE.equals(resource) || AwsArnUtils.isArn(resource))
.forEach(resource -> permissions.add(new Permission(target.action(), resource, context)));
}
return accessDenied(DYNAMODB_SDK_PREFIX, permissions);
}
return permissions;
List<String> named = RequestResources.ofBody(namedAs, input, owner.partition(), owner.region(),
owner.accountId(), null);
return accessDenied(DYNAMODB_SDK_PREFIX, (named.isEmpty() ? List.of(ANY_RESOURCE) : named).stream()
.filter(resource -> ANY_RESOURCE.equals(resource) || AwsArnUtils.isArn(resource))
.map(resource -> new Permission(namedAs, resource))
.toList());
}
/**