From 3a1ea212f0ff70d86cccceb84f81789e12d13b84 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:04:18 -0400 Subject: [PATCH] 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). --- Makefile | 3 +- docs/services/dynamodb.md | 25 +- .../common/IamConditionContextResolver.java | 113 ++----- .../aws/core/common/IamEnforcementFilter.java | 51 ++- .../core/common/RequestResourceMembers.java | 75 ++++- .../aws/core/common/RequestResources.java | 160 +++++++++- .../aws/core/common/StoredResourceArns.java | 16 + .../dynamodb/DynamoDbConditionKeyMembers.java | 19 -- .../dynamodb/DynamoDbConditionKeys.java | 8 - .../dynamodb/DynamoDbPartiQLParser.java | 55 +++- .../dynamodb/DynamoDbStoredResourceArns.java | 37 ++- .../aws/services/iam/IamActionRegistry.java | 15 +- .../aws/services/iam/ResourceArnBuilder.java | 181 +---------- .../stepfunctions/TaskPermissions.java | 95 ++---- .../resources/aws/iam-request-resources.json | 69 ++++- .../IamConditionContextResolverTest.java | 4 +- .../common/RequestResourceMembersTest.java | 17 +- .../aws/core/common/RequestResourcesTest.java | 3 +- .../dynamodb/DynamoDbConditionKeysTest.java | 25 +- .../dynamodb/DynamoDbPartiQLParserTest.java | 28 +- .../services/iam/ResourceArnBuilderTest.java | 291 ++++++++---------- .../stepfunctions/TaskPermissionsTest.java | 69 +++-- tools/aws/fetch_dynamodb_permissions.py | 142 +++++++++ tools/aws/regen_iam_request_resources.py | 203 ++++++++++-- tools/aws/sources/dynamodb-permissions.json | 66 ++++ tools/aws/test_fetch_dynamodb_permissions.py | 55 ++++ tools/aws/test_regen_iam_request_resources.py | 134 ++++++++ 27 files changed, 1298 insertions(+), 661 deletions(-) create mode 100644 tools/aws/fetch_dynamodb_permissions.py create mode 100644 tools/aws/sources/dynamodb-permissions.json create mode 100644 tools/aws/test_fetch_dynamodb_permissions.py diff --git a/Makefile b/Makefile index e40e2593bc..7853fab90f 100644 --- a/Makefile +++ b/Makefile @@ -629,7 +629,8 @@ IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json tools/aws/sources/apigateway-arn-formats.json tools/aws/fetch_apigateway_arn_formats.py \ tools/aws/test_fetch_apigateway_arn_formats.py src/main/resources/aws/iam-authorized-actions.json \ tools/aws/sources/kms-api-permissions.json tools/aws/fetch_kms_api_permissions.py \ - tools/aws/test_fetch_kms_api_permissions.py + tools/aws/test_fetch_kms_api_permissions.py tools/aws/sources/dynamodb-permissions.json \ + tools/aws/fetch_dynamodb_permissions.py tools/aws/test_fetch_dynamodb_permissions.py iam-data-verify: ## CI gate (online): every vendored IAM file must still match AWS; CHANGED="" checks only the ones they cover @# Every check runs even when an earlier one fails, so one file's drift cannot hide another's diff --git a/docs/services/dynamodb.md b/docs/services/dynamodb.md index 4443ab5ea4..c5ae1df239 100644 --- a/docs/services/dynamodb.md +++ b/docs/services/dynamodb.md @@ -15,8 +15,29 @@ This resource matching was checked against live AWS with isolated role sessions. Pagination and ignored table selectors do not change the collection being authorized. Other DynamoDB operations retain their own authorization resources. The Service Reference lists no resource type for the action, so the collection comes from that -measurement, the one thing the generated table of request resources states by hand. Other DynamoDB -operations keep their existing resource builders, including batch, transaction and PartiQL table extraction. +measurement, the one thing the generated table of request resources states by hand. + +## IAM enforcement + +With IAM enforcement enabled, every DynamoDB request is checked as AWS checks it, read from the generated +tables like other services' requests. A request is checked on the table, index, stream, backup, export, +import or global table it names, by name or ARN. A table ARN is checked as given and as the caller's own +table of that name, the one DynamoDB acts on. + +- `BatchGetItem` and `BatchWriteItem` are checked on every table their `RequestItems` keys. +- Each item of a `TransactWriteItems` or `TransactGetItems` is checked on its own table as the action the + developer guide's [transactions page](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis-iam.html) + gives its kind: `Put` as `dynamodb:PutItem`, `Update` as `dynamodb:UpdateItem`, `Delete` as + `dynamodb:DeleteItem`, `Get` as `dynamodb:GetItem` and `ConditionCheck` as `dynamodb:ConditionCheckItem`, with + `dynamodb:EnclosingOperation` naming the transaction. +- Each PartiQL statement of an `ExecuteStatement`, `BatchExecuteStatement` or `ExecuteTransaction` is checked as + the action the [PartiQL IAM page](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-iam.html) + gives its verb (`dynamodb:PartiQLSelect`, `PartiQLInsert`, `PartiQLUpdate`, `PartiQLDelete`) on the table or + index it names, as DynamoDB parses it; a transaction's with `dynamodb:EnclosingOperation` `ExecuteTransaction`. + An `EXISTS` statement is checked as the + [SELECT statement it evaluates](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-functions.exists.html), + and the index of a statement with `?` placeholders is read before they are bound. A request naming nothing is + checked as its own operation on `*`; a state machine's task naming nothing is left to DynamoDB to answer. ## Supported Actions diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index cf4db08da0..c61e5d1b44 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -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> 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 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> 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 checks = new ArrayList<>(); - List 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> 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> 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 dynamoDbStatementItems(String action, ContainerRequestContext ctx, - String region, String accountId) { - boolean transaction = "dynamodb:ExecuteTransaction".equals(action); - String operation = action.substring("dynamodb:".length()); - List 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> 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. */ diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index cb19f64067..4100339500 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -596,40 +596,29 @@ public class IamEnforcementFilter implements ContainerRequestFilter { } RequestPrincipal principal = RequestPrincipal.caller(callerArns.orElse(null)); - List transactionItems = - "dynamodb".equals(credentialScope) - ? conditionContextResolver.dynamoDbTransactionItems(action, ctx, region, accountId) - : List.of(); - if (!transactionItems.isEmpty()) { - for (IamConditionContextResolver.DynamoDbTransactionItem item : transactionItems) { - Map> 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 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> resolved = conditionContextResolver.resolvePart(credentialScope, + target.action(), resolvedOperation.operation(), ctx, target.element(), region); + Map> 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> checkedAs = arnBuilder.checkedAs(credentialScope, resolvedOperation.operation(), ctx, - region, accountId, requestPartition()); - for (Map.Entry> checked : checkedAs.entrySet()) { - Map> resolved = - conditionContextResolver.resolve(credentialScope, checked.getKey(), ctx); - Map> 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, diff --git a/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java b/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java index 995226ea51..84f2cf3bba 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java +++ b/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java @@ -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 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 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 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 types, Member arn, Map fill, Map> when, Map> unless, Map arnOf, Member account, Map fixed, boolean made, List find, String endpoint, Member through, boolean byDefault, Map whenDefault, Map unlessDefault, - Map defaults, boolean partialArn) { + Map defaults, boolean partialArn, Member statement, String verb, + Map names) { + + Resource(List types, Member arn, Map fill, Map> when, + Map> unless, Map arnOf, Member account, + Map fixed, boolean made, List find, String endpoint, Member through, + boolean byDefault, Map whenDefault, Map unlessDefault, + Map 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 types, Member arn, Map fill, Map> when, Map> unless, Map 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> operations, Map> types, Map> creates, Map> 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 keys = resource.has("through") ? THROUGH_KEYS : resource.has("arn") ? ARN_KEYS : FILL_KEYS; List 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 formats) { + List types = resource.path("types").valueStream().map(JsonNode::asText).toList(); + Map names = new LinkedHashMap<>(); + resource.path("names").properties().forEach(name -> names.put(name.getKey(), name.getValue().asText(""))); + Set 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()); } /** diff --git a/src/main/java/io/floci/aws/core/common/RequestResources.java b/src/main/java/io/floci/aws/core/common/RequestResources.java index 9190610dac..81229b63d7 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResources.java +++ b/src/main/java/io/floci/aws/core/common/RequestResources.java @@ -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> checkedAs(String operation, ContainerRequestContext ctx, String partition, - String region, String accountId, StoredResourceArns stored, - Map labels) { + public record Target(String action, List 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 targets(String operation, ContainerRequestContext ctx, String partition, String region, + String accountId, StoredResourceArns stored, Map labels) { RequestResourceMembers.Table table = RequestResourceMembers.table(); Map> actions = !readable(table, operation) ? null : table.checkedAs().get(operation); if (actions == null) { - return Map.of(); + return List.of(); } Map sent = IamConditionContextResolver.formParameters(ctx); JsonNode body = sent.isEmpty() ? located(table, operation, PassedRoles.jsonBody(ctx), ctx, labels) : null; Map form = ec2Query(table, operation, located(table, operation, sent, ctx, labels)); - Map> checked = new LinkedHashMap<>(); + Map> 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 targetsOfBody(String operation, JsonNode body, String partition, String region, + String accountId, StoredResourceArns stored) { + RequestResourceMembers.Table table = RequestResourceMembers.table(); + Map> 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 targets(String operation, Map> actions, + Map formats, Map form, + JsonNode body, String partition, String region, String accountId, + StoredResourceArns stored) { + List found = new ArrayList<>(); actions.forEach((action, resources) -> { - List read = served(resources, ctx); - List 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 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 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 arns, RequestResourceMembers.Resource resource, + Map formats, Map form, + JsonNode body, String partition, String region, String accountId, + StoredResourceArns stored) { + if (stored == null) { + return; + } + List 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 parsed = stored.statement(value); + if (parsed.isEmpty() || !resource.verb().equals(parsed.get().verb())) { + continue; + } + for (String type : types) { + Map 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()); } diff --git a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java index 5c47f68c70..b90fb8f8a7 100644 --- a/src/main/java/io/floci/aws/core/common/StoredResourceArns.java +++ b/src/main/java/io/floci/aws/core/common/StoredResourceArns.java @@ -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 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(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, diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeyMembers.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeyMembers.java index ceff600e86..92f0390cf3 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeyMembers.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeyMembers.java @@ -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 listElements(String operation, String key, String member, JsonNode body) { - List 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 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; diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeys.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeys.java index 3d21a09f6c..2d7b31446e 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeys.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeys.java @@ -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 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) diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParser.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParser.java index fe785bb5d7..22bb8014fa 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParser.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParser.java @@ -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 target(String statement) { if (statement == null || statement.isBlank()) { - return null; + return Optional.empty(); + } + AtomicReference 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 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)); } /** diff --git a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStoredResourceArns.java b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStoredResourceArns.java index 1c0cb4ea68..f20636a966 100644 --- a/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStoredResourceArns.java +++ b/src/main/java/io/floci/aws/services/dynamodb/DynamoDbStoredResourceArns.java @@ -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 find(String type, List names, String region) { + return Optional.empty(); + } + + @Override + public Optional statement(String statement) { + return parsed(statement); + } + }; + private final DynamoDbTableAccess tables; @Inject @@ -38,4 +61,16 @@ public class DynamoDbStoredResourceArns implements StoredResourceArns { public Map 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(String statement) { + return parsed(statement); + } + + private static Optional 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()))); + } } diff --git a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java index 58b1193801..77debc5dc1 100644 --- a/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java +++ b/src/main/java/io/floci/aws/services/iam/IamActionRegistry.java @@ -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); } diff --git a/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java b/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java index ed80ca6704..87b6bf70ba 100644 --- a/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java +++ b/src/main/java/io/floci/aws/services/iam/ResourceArnBuilder.java @@ -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> checkedAs(String credentialScope, String operation, ContainerRequestContext ctx, - String region, String accountId, String partition) { + public List 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 arns = buildDynamoDbArns(ctx, region, accountId); - return arns.isEmpty() ? "*" : arns.getFirst(); - } - - private List 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 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 arns = new LinkedHashSet<>(); - Iterator 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 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 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 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. */ diff --git a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java index 1e111d5d38..8d96f58c8a 100644 --- a/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java +++ b/src/main/java/io/floci/aws/services/stepfunctions/TaskPermissions.java @@ -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 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 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 dynamoDbTransaction(String operation, JsonNode input, AwsArnUtils.Arn owner) { - boolean read = "TransactGetItems".equals(operation); - List kinds = read ? List.of("Get") : List.of("Put", "Delete", "Update", "ConditionCheck"); - Map> enclosing = Map.of("dynamodb:EnclosingOperation", List.of(operation)); - List 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 permissions = new ArrayList<>(); + for (RequestResources.Target target : RequestResources.targetsOfBody(namedAs, input, owner.partition(), + owner.region(), owner.accountId(), DynamoDbStoredResourceArns.STATEMENTS)) { + Map> 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 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()); } /** diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json index bd78964c00..1eed65507a 100644 --- a/src/main/resources/aws/iam-request-resources.json +++ b/src/main/resources/aws/iam-request-resources.json @@ -1,7 +1,7 @@ { "_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.44.9 (local/aws/botocore)", "retrieved": "2026-11-22", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."}, - "namespaces": {"access-analyzer": ["accessanalyzer"], "account": ["account"], "acm": ["acm"], "apigateway": ["apigateway", "apigatewayv2"], "application-autoscaling": ["application-autoscaling"], "aps": ["amp"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "bedrock": ["bedrock", "bedrock-agent", "bedrock-agent-runtime", "bedrock-data-automation", "bedrock-data-automation-runtime", "bedrock-runtime"], "budgets": ["budgets"], "ce": ["ce"], "cloudformation": ["cloudcontrol", "cloudformation"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dsql": ["dsql"], "dynamodb": ["dynamodb"], "ec2": ["ec2"], "ec2-instance-connect": ["ec2-instance-connect"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-containers": ["emr-containers"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "glue": ["glue"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "kms": ["kms"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "macie2": ["macie2"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "pipes": ["pipes"], "quicksight": ["quicksight"], "ram": ["ram"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "resource-groups": ["resource-groups"], "route53": ["route53"], "s3": ["s3", "s3control"], "s3tables": ["s3tables"], "s3vectors": ["s3vectors"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "sns": ["sns"], "sqs": ["sqs"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "sts": ["sts"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]}, - "handBuilt": ["dynamodb", "iam"], + "namespaces": {"access-analyzer": ["accessanalyzer"], "account": ["account"], "acm": ["acm"], "apigateway": ["apigateway", "apigatewayv2"], "application-autoscaling": ["application-autoscaling"], "aps": ["amp"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "bedrock": ["bedrock", "bedrock-agent", "bedrock-agent-runtime", "bedrock-data-automation", "bedrock-data-automation-runtime", "bedrock-runtime"], "budgets": ["budgets"], "ce": ["ce"], "cloudformation": ["cloudcontrol", "cloudformation"], "cloudfront": ["cloudfront"], "cloudfront-keyvaluestore": ["cloudfront-keyvaluestore"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "controlcatalog": ["controlcatalog"], "controltower": ["controltower"], "cur": ["cur"], "datasync": ["datasync"], "dsql": ["dsql"], "dynamodb": ["dynamodb", "dynamodbstreams"], "ec2": ["ec2"], "ec2-instance-connect": ["ec2-instance-connect"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticloadbalancing": ["elb", "elbv2"], "elasticmapreduce": ["emr"], "emr-containers": ["emr-containers"], "emr-serverless": ["emr-serverless"], "es": ["es", "opensearch"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "fis": ["fis"], "globalaccelerator": ["globalaccelerator"], "glue": ["glue"], "guardduty": ["guardduty"], "inspector2": ["inspector2"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "kms": ["kms"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "macie2": ["macie2"], "oam": ["oam"], "payment-cryptography": ["payment-cryptography", "payment-cryptography-data"], "pipes": ["pipes"], "quicksight": ["quicksight"], "ram": ["ram"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-data": ["redshift-data"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-explorer-2": ["resource-explorer-2"], "resource-groups": ["resource-groups"], "route53": ["route53"], "s3": ["s3", "s3control"], "s3tables": ["s3tables"], "s3vectors": ["s3vectors"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "securityhub": ["securityhub"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "signer": ["signer", "signer-data"], "sns": ["sns"], "sqs": ["sqs"], "ssm": ["ssm"], "sso": ["sso", "sso-admin"], "states": ["stepfunctions"], "sts": ["sts"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"], "xray": ["xray"]}, + "handBuilt": ["iam"], "notCovered": {"airflow": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "appsync": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup::autoScalingGroupName/`, while Floci mints `autoScalingGroup:`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "batch": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rules do not fill a name from, so nearly every operation's resource would be left open", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/_, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "detective": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dlm": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticache": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticbeanstalk": "not read yet: an environment's ARN carries its application's name, `environment//`, while most of its requests name it by EnvironmentName or EnvironmentId alone, so reading it needs the stored environment those find", "elasticfilesystem": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "execute-api": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "identitystore": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "iot": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "kafka": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "lightsail": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "memorydb": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "mq": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "network-firewall": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "organizations": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rds-data": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "route53resolver": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rum": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "sagemaker": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "servicecatalog": "not read yet: CreatePortfolioShare, UpdatePortfolioShare and DeletePortfolioShare give in AccountId the account a portfolio is shared with, which the rule reads as the portfolio's; a portfolio or product imported from another account keeps its owner's account in its ARN while requests name it by its id alone; and AppRegistry's applications and attribute groups are named in the path", "ses": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "signin": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "sso-oauth": "REST: its requests name their resources in the path, which RequestResources reads from the route a request matched in the vendored REST routes (regen_rest_routes.MODELS), which do not have its model yet", "swf": "not read yet: the Service Reference gives a domain's ARN no Region, `swf:::/domain/`, while the SWF Developer Guide gives it as arn:aws:swf:Region:AccountID:/domain/DomainName, as Floci mints it; reading it needs that format corrected", "transcribe": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "transfer": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "verifiedpermissions": "not read yet: a policyStoreId may name its store by an alias, `policy-store-alias/`, which AWS authorizes as the action on the store the alias points to and GetPolicyStoreAlias on the alias, and an aliasName carries the `policy-store-alias/` its format already gives; reading it needs both", "wafv2": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint"}, "otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "apiportal", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bcm-data-hub", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "osm", "outposts", "panorama", "partnercentral", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "ssmmessages", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web"], "arnFormats": {"access-analyzer": {"Analyzer": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}", "ArchiveRule": "arn:${Partition}:access-analyzer:${Region}:${Account}:analyzer/${AnalyzerName}/archive-rule/${RuleName}"}, "account": {"account": "arn:${Partition}:account::${Account}:account", "accountInOrganization": "arn:${Partition}:account::${ManagementAccountId}:account/o-${OrganizationId}/${MemberAccountId}"}, "acm": {"acme-domain-validation": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-domain-validation/${AcmeDomainValidationId}", "acme-endpoint": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}", "acme-external-account-binding": "arn:${Partition}:acm:${Region}:${Account}:acme-endpoint/${AcmeEndpointId}/acme-external-account-binding/${ExternalAccountBindingId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}"}, "apigateway": {"AccessLogSettings": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}/accesslogsettings", "Account": "arn:${Partition}:apigateway:${Region}::/account", "Api": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}", "ApiKey": "arn:${Partition}:apigateway:${Region}::/apikeys/${ApiKeyId}", "ApiKeys": "arn:${Partition}:apigateway:${Region}::/apikeys", "ApiMapping": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/apimappings/${ApiMappingId}", "ApiMappings": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/apimappings", "Apis": "arn:${Partition}:apigateway:${Region}::/apis", "Authorizer": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/authorizers/${AuthorizerId}", "Authorizers": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/authorizers", "AuthorizersCache": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}/cache/authorizers", "BasePathMapping": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/basepathmappings/${BasePath}", "BasePathMappings": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}/basepathmappings", "ClientCertificate": "arn:${Partition}:apigateway:${Region}::/clientcertificates/${ClientCertificateId}", "ClientCertificates": "arn:${Partition}:apigateway:${Region}::/clientcertificates", "Cors": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/cors", "Deployment": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/deployments/${DeploymentId}", "Deployments": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/deployments", "DocumentationPart": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/parts/${DocumentationPartId}", "DocumentationParts": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/parts", "DocumentationVersion": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/versions/${DocumentationVersionId}", "DocumentationVersions": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/documentation/versions", "DomainName": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}", "DomainNameAccessAssociation": "arn:${Partition}:apigateway:${Region}:${Account}:/domainnameaccessassociations/domainname/${DomainName}/${SourceType}/${SourceId}", "DomainNameAccessAssociations": "arn:${Partition}:apigateway:${Region}:${Account}:/domainnameaccessassociations", "DomainNames": "arn:${Partition}:apigateway:${Region}::/domainnames", "ExportedAPI": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/exports/${Specification}", "GatewayResponse": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/gatewayresponses/${ResponseType}", "GatewayResponses": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/gatewayresponses", "Integration": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}", "IntegrationResponse": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}/integrationresponses/${IntegrationResponseId}", "IntegrationResponses": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations/${IntegrationId}/integrationresponses", "Integrations": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/integrations", "Method": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}/methods/${HttpMethodType}", "MethodResponse": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}/methods/${HttpMethodType}/responses/${StatusCode}", "Model": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models/${ModelId}", "ModelTemplate": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models/${ModelId}/template", "Models": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/models", "Portal": "arn:${Partition}:apigateway:${Region}:${Account}:/portals/${PortalId}", "PortalProduct": "arn:${Partition}:apigateway:${Region}:${Account}:/portalproducts/${PortalProductId}", "PrivateBasePathMapping": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}+${DomainIdentifier}/basepathmappings/${BasePath}", "PrivateBasePathMappings": "arn:${Partition}:apigateway:${Region}::/domainnames/${DomainName}+${DomainIdentifier}/basepathmappings", "PrivateDomainName": "arn:${Partition}:apigateway:${Region}:${Account}:/domainnames/${DomainName}+${DomainIdentifier}", "ProductPage": "arn:${Partition}:apigateway:${Region}:${Account}:/portalproducts/${PortalProductId}/productpages/${ProductPageId}", "ProductRestEndpointPage": "arn:${Partition}:apigateway:${Region}:${Account}:/portalproducts/${PortalProductId}/productrestendpointpages/${ProductRestEndpointPageId}", "RequestValidator": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/requestvalidators/${RequestValidatorId}", "RequestValidators": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/requestvalidators", "Resource": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources/${ResourceId}", "Resources": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/resources", "RestApi": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}", "RestApis": "arn:${Partition}:apigateway:${Region}::/restapis", "Route": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes/${RouteId}", "RouteRequestParameter": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes/${RouteId}/requestparameters/${RequestParameterKey}", "RouteResponse": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes/${RouteId}/routeresponses/${RouteResponseId}", "RouteResponses": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes/${RouteId}/routeresponses", "RouteSettings": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}/routesettings/${RouteKey}", "Routes": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/routes", "RoutingRule": "arn:${Partition}:apigateway:${Region}:${Account}:/domainnames/${DomainName}/routingrules/${RoutingRuleId}", "Sdk": "arn:${Partition}:apigateway:${Region}::/restapis/${RestApiId}/stages/${StageName}/sdks/${SdkType}", "Stage": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages/${StageName}", "Stages": "arn:${Partition}:apigateway:${Region}::/apis/${ApiId}/stages", "Tags": "arn:${Partition}:apigateway:${Region}::/tags/${UrlEncodedResourceARN}", "Template": "arn:${Partition}:apigateway:${Region}::/restapis/models/${ModelName}/template", "UsagePlan": "arn:${Partition}:apigateway:${Region}::/usageplans/${UsagePlanId}", "UsagePlanKey": "arn:${Partition}:apigateway:${Region}::/usageplans/${UsagePlanId}/keys/${Id}", "UsagePlanKeys": "arn:${Partition}:apigateway:${Region}::/usageplans/${UsagePlanId}/keys", "UsagePlans": "arn:${Partition}:apigateway:${Region}::/usageplans", "VpcLink": "arn:${Partition}:apigateway:${Region}::/vpclinks/${VpcLinkId}", "VpcLinks": "arn:${Partition}:apigateway:${Region}::/vpclinks"}, "application-autoscaling": {"ScalableTarget": "arn:${Partition}:application-autoscaling:${Region}:${Account}:scalable-target/${ResourceId}"}, "aps": {"anomalydetector": "arn:${Partition}:aps:${Region}:${Account}:anomalydetector/${WorkspaceId}/${AnomalyDetectorId}", "cluster": "arn:${Partition}:eks:${Region}:${Account}:cluster/${ClusterName}", "rulegroupsnamespace": "arn:${Partition}:aps:${Region}:${Account}:rulegroupsnamespace/${WorkspaceId}/${Namespace}", "scraper": "arn:${Partition}:aps:${Region}:${Account}:scraper/${ScraperId}", "workspace": "arn:${Partition}:aps:${Region}:${Account}:workspace/${WorkspaceId}"}, "athena": {"capacity-reservation": "arn:${Partition}:athena:${Region}:${Account}:capacity-reservation/${CapacityReservationName}", "datacatalog": "arn:${Partition}:athena:${Region}:${Account}:datacatalog/${DataCatalogName}", "session": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}/session/${SessionId}", "system-table": "arn:${Partition}:athena:${Region}:${Account}:system-table/${TableName}", "workgroup": "arn:${Partition}:athena:${Region}:${Account}:workgroup/${WorkGroupName}"}, "bcm-data-exports": {"billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "export": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:export/${Identifier}", "table": "arn:${Partition}:bcm-data-exports:${Region}:${Account}:table/${Identifier}"}, "bcm-pricing-calculator": {"bill-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-estimate/${BillEstimateId}", "bill-scenario": "arn:${Partition}:bcm-pricing-calculator::${Account}:bill-scenario/${BillScenarioId}", "workload-estimate": "arn:${Partition}:bcm-pricing-calculator::${Account}:workload-estimate/${WorkloadEstimateId}"}, "bedrock": {"advanced-prompt-optimization-job": "arn:${Partition}:bedrock:${Region}:${Account}:advanced-prompt-optimization-job/${ResourceId}", "agent": "arn:${Partition}:bedrock:${Region}:${Account}:agent/${AgentId}", "agent-alias": "arn:${Partition}:bedrock:${Region}:${Account}:agent-alias/${AgentId}/${AgentAliasId}", "application-inference-profile": "arn:${Partition}:bedrock:${Region}:${Account}:application-inference-profile/${ResourceId}", "async-invoke": "arn:${Partition}:bedrock:${Region}:${Account}:async-invoke/${ResourceId}", "automated-reasoning-policy": "arn:${Partition}:bedrock:${Region}:${Account}:automated-reasoning-policy/${AutomatedReasoningPolicyId}", "automated-reasoning-policy-version": "arn:${Partition}:bedrock:${Region}:${Account}:automated-reasoning-policy/${AutomatedReasoningPolicyId}:${AutomatedReasoningPolicyVersion}", "bedrock-marketplace-model-endpoint": "arn:${Partition}:bedrock:${Region}:${Account}:marketplace/model-endpoint/all-access", "blueprint": "arn:${Partition}:bedrock:${Region}:${Account}:blueprint/${BlueprintId}", "blueprint-optimization-invocation": "arn:${Partition}:bedrock:${Region}:${Account}:blueprint-optimization-invocation/${ResourceId}", "custom-model": "arn:${Partition}:bedrock:${Region}:${Account}:custom-model/${ResourceId}", "custom-model-deployment": "arn:${Partition}:bedrock:${Region}:${Account}:custom-model-deployment/${ResourceId}", "data-automation-invocation-job": "arn:${Partition}:bedrock:${Region}:${Account}:data-automation-invocation/${JobId}", "data-automation-library": "arn:${Partition}:bedrock:${Region}:${Account}:data-automation-library/${DataAutomationLibraryId}", "data-automation-library-ingestion-job": "arn:${Partition}:bedrock:${Region}:${Account}:data-automation-library-ingestion-job/${IngestionJobId}", "data-automation-profile": "arn:${Partition}:bedrock:${Region}:${Account}:data-automation-profile/${ProfileId}", "data-automation-project": "arn:${Partition}:bedrock:${Region}:${Account}:data-automation-project/${ProjectId}", "default-prompt-router": "arn:${Partition}:bedrock:${Region}:${Account}:default-prompt-router/${ResourceId}", "evaluation-job": "arn:${Partition}:bedrock:${Region}:${Account}:evaluation-job/${ResourceId}", "flow": "arn:${Partition}:bedrock:${Region}:${Account}:flow/${FlowId}", "flow-alias": "arn:${Partition}:bedrock:${Region}:${Account}:flow/${FlowId}/alias/${FlowAliasId}", "flow-execution": "arn:${Partition}:bedrock:${Region}:${Account}:flow/${FlowId}/alias/${FlowAliasId}/execution/${FlowExecutionId}", "foundation-model": "arn:${Partition}:bedrock:${Region}::foundation-model/${ResourceId}", "guardrail": "arn:${Partition}:bedrock:${Region}:${Account}:guardrail/${GuardrailId}", "guardrail-profile": "arn:${Partition}:bedrock:${Region}:${Account}:guardrail-profile/${ResourceId}", "imported-model": "arn:${Partition}:bedrock:${Region}:${Account}:imported-model/${ResourceId}", "inference-profile": "arn:${Partition}:bedrock:${Region}:${Account}:inference-profile/${ResourceId}", "knowledge-base": "arn:${Partition}:bedrock:${Region}:${Account}:knowledge-base/${KnowledgeBaseId}", "model-copy-job": "arn:${Partition}:bedrock:${Region}:${Account}:model-copy-job/${ResourceId}", "model-customization-job": "arn:${Partition}:bedrock:${Region}:${Account}:model-customization-job/${ResourceId}", "model-evaluation-job": "arn:${Partition}:bedrock:${Region}:${Account}:model-evaluation-job/${ResourceId}", "model-import-job": "arn:${Partition}:bedrock:${Region}:${Account}:model-import-job/${ResourceId}", "model-invocation-job": "arn:${Partition}:bedrock:${Region}:${Account}:model-invocation-job/${JobIdentifier}", "project": "arn:${Partition}:bedrock:${Region}:${Account}:project/${ResourceId}", "prompt": "arn:${Partition}:bedrock:${Region}:${Account}:prompt/${PromptId}", "prompt-router": "arn:${Partition}:bedrock:${Region}:${Account}:prompt-router/${ResourceId}", "prompt-version": "arn:${Partition}:bedrock:${Region}:${Account}:prompt/${PromptId}:${PromptVersion}", "provisioned-model": "arn:${Partition}:bedrock:${Region}:${Account}:provisioned-model/${ResourceId}", "retrieval-instruction": "arn:${Partition}:bedrock:${Region}:${Account}:retrieval-instruction/${RetrievalInstructionId}", "session": "arn:${Partition}:bedrock:${Region}:${Account}:session/${SessionId}", "system-tool": "arn:${Partition}:bedrock::${Account}:system-tool/${ResourceId}"}, "budgets": {"budget": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}", "budgetAction": "arn:${Partition}:budgets::${Account}:budget/${BudgetName}/action/${ActionId}"}, "ce": {"anomalymonitor": "arn:${Partition}:ce::${Account}:anomalymonitor/${Identifier}", "anomalysubscription": "arn:${Partition}:ce::${Account}:anomalysubscription/${Identifier}", "billingview": "arn:${Partition}:billing::${Account}:billingview/${ResourceId}", "costcategory": "arn:${Partition}:ce::${Account}:costcategory/${Identifier}"}, "cloudformation": {"changeset": "arn:${Partition}:cloudformation:${Region}:${Account}:changeSet/${ChangeSetName}/${Id}", "generatedtemplate": "arn:${Partition}:cloudformation:${Region}:${Account}:generatedTemplate/${Id}", "resourcescan": "arn:${Partition}:cloudformation:${Region}:${Account}:resourceScan/${Id}", "stack": "arn:${Partition}:cloudformation:${Region}:${Account}:stack/${StackName}/${Id}", "stackset": "arn:${Partition}:cloudformation:${Region}:${Account}:stackset/${StackSetName}:${Id}", "stackset-target": "arn:${Partition}:cloudformation:${Region}:${Account}:stackset-target/${StackSetTarget}", "type": "arn:${Partition}:cloudformation:${Region}:${Account}:type/resource/${Type}", "typeHook": "arn:${Partition}:cloudformation:${Region}:${Account}:type/hook/${Type}"}, "cloudfront": {"anycast-ip-list": "arn:${Partition}:cloudfront::${Account}:anycast-ip-list/${Id}", "cache-policy": "arn:${Partition}:cloudfront::${Account}:cache-policy/${Id}", "connection-function": "arn:${Partition}:cloudfront::${Account}:connection-function/${Id}", "connection-group": "arn:${Partition}:cloudfront::${Account}:connection-group/${Id}", "continuous-deployment-policy": "arn:${Partition}:cloudfront::${Account}:continuous-deployment-policy/${Id}", "distribution": "arn:${Partition}:cloudfront::${Account}:distribution/${DistributionId}", "distribution-tenant": "arn:${Partition}:cloudfront::${Account}:distribution-tenant/${Id}", "field-level-encryption-config": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-config/${Id}", "field-level-encryption-profile": "arn:${Partition}:cloudfront::${Account}:field-level-encryption-profile/${Id}", "function": "arn:${Partition}:cloudfront::${Account}:function/${Name}", "key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${Name}", "origin-access-control": "arn:${Partition}:cloudfront::${Account}:origin-access-control/${Id}", "origin-access-identity": "arn:${Partition}:cloudfront::${Account}:origin-access-identity/${Id}", "origin-request-policy": "arn:${Partition}:cloudfront::${Account}:origin-request-policy/${Id}", "realtime-log-config": "arn:${Partition}:cloudfront::${Account}:realtime-log-config/${Name}", "response-headers-policy": "arn:${Partition}:cloudfront::${Account}:response-headers-policy/${Id}", "streaming-distribution": "arn:${Partition}:cloudfront::${Account}:streaming-distribution/${DistributionId}", "trust-store": "arn:${Partition}:cloudfront::${Account}:trust-store/${Id}", "vpcorigin": "arn:${Partition}:cloudfront::${Account}:vpcorigin/${Id}"}, "cloudfront-keyvaluestore": {"key-value-store": "arn:${Partition}:cloudfront::${Account}:key-value-store/${ResourceId}"}, "cloudtrail": {"channel": "arn:${Partition}:cloudtrail:${Region}:${Account}:channel/${ChannelId}", "dashboard": "arn:${Partition}:cloudtrail:${Region}:${Account}:dashboard/${DashboardName}", "eventdatastore": "arn:${Partition}:cloudtrail:${Region}:${Account}:eventdatastore/${EventDataStoreId}", "trail": "arn:${Partition}:cloudtrail:${Region}:${Account}:trail/${TrailName}"}, "codebuild": {"build": "arn:${Partition}:codebuild:${Region}:${Account}:build/${BuildId}", "build-batch": "arn:${Partition}:codebuild:${Region}:${Account}:build-batch/${BuildBatchId}", "fleet": "arn:${Partition}:codebuild:${Region}:${Account}:fleet/${FleetName}:${FleetId}", "project": "arn:${Partition}:codebuild:${Region}:${Account}:project/${ProjectName}", "report": "arn:${Partition}:codebuild:${Region}:${Account}:report/${ReportGroupName}:${ReportId}", "report-group": "arn:${Partition}:codebuild:${Region}:${Account}:report-group/${ReportGroupName}", "sandbox": "arn:${Partition}:codebuild:${Region}:${Account}:sandbox/${SandboxId}"}, "codepipeline": {"action": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}/${ActionName}", "actiontype": "arn:${Partition}:codepipeline:${Region}:${Account}:actiontype:${Owner}/${Category}/${Provider}/${Version}", "pipeline": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}", "stage": "arn:${Partition}:codepipeline:${Region}:${Account}:${PipelineName}/${StageName}", "webhook": "arn:${Partition}:codepipeline:${Region}:${Account}:webhook:${WebhookName}"}, "cognito-identity": {"identitypool": "arn:${Partition}:cognito-identity:${Region}:${Account}:identitypool/${IdentityPoolId}"}, "cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "controlcatalog": {"common-control": "arn:${Partition}:controlcatalog:::common-control/${CommonControlId}", "control": "arn:${Partition}:controlcatalog:::control/${ControlId}", "domain": "arn:${Partition}:controlcatalog:::domain/${DomainId}", "objective": "arn:${Partition}:controlcatalog:::objective/${ObjectiveId}"}, "controltower": {"Baseline": "arn:${Partition}:controltower:${Region}::baseline/${BaselineId}", "EnabledBaseline": "arn:${Partition}:controltower:${Region}:${Account}:enabledbaseline/${EnabledBaselineId}", "EnabledControl": "arn:${Partition}:controltower:${Region}:${Account}:enabledcontrol/${EnabledControlId}", "LandingZone": "arn:${Partition}:controltower:${Region}:${Account}:landingzone/${LandingZoneId}"}, "cur": {"cur": "arn:${Partition}:cur:${Region}:${Account}:definition/${ReportName}"}, "datasync": {"agent": "arn:${Partition}:datasync:${Region}:${Account}:agent/${AgentId}", "discoveryjob": "arn:${Partition}:datasync:${Region}:${Account}:system/${StorageSystemId}/job/${DiscoveryJobId}", "location": "arn:${Partition}:datasync:${Region}:${Account}:location/${LocationId}", "storagesystem": "arn:${Partition}:datasync:${Region}:${Account}:system/${StorageSystemId}", "task": "arn:${Partition}:datasync:${Region}:${Account}:task/${TaskId}", "taskexecution": "arn:${Partition}:datasync:${Region}:${Account}:task/${TaskId}/execution/${ExecutionId}"}, "dsql": {"Cluster": "arn:${Partition}:dsql:${Region}:${Account}:cluster/${Identifier}", "Stream": "arn:${Partition}:dsql:${Region}:${Account}:cluster/${ClusterId}/stream/${StreamId}"}, "dynamodb": {"backup": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/backup/${BackupName}", "bulk-operation": "arn:${Partition}:dynamodb:${Region}:${Account}:bulk-operation/${BulkOperationId}", "export": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/export/${ExportName}", "global-table": "arn:${Partition}:dynamodb::${Account}:global-table/${GlobalTableName}", "import": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/import/${ImportName}", "index": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/index/${IndexName}", "stream": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/stream/${StreamLabel}", "table": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}"}, "ec2": {"application-status-check": "arn:${Partition}:ec2:${Region}:${Account}:application-status-check/${ApplicationStatusCheckId}", "capacity-block": "arn:${Partition}:ec2:${Region}:${Account}:capacity-block/${CapacityBlockId}", "capacity-manager-data-export": "arn:${Partition}:ec2:${Region}:${Account}:capacity-manager-data-export/${CapacityManagerDataExportId}", "capacity-reservation": "arn:${Partition}:ec2:${Region}:${Account}:capacity-reservation/${CapacityReservationId}", "capacity-reservation-cancellation-quote": "arn:${Partition}:ec2:${Region}:${Account}:capacity-reservation-cancellation-quote/${CapacityReservationCancellationQuoteId}", "capacity-reservation-fleet": "arn:${Partition}:ec2:${Region}:${Account}:capacity-reservation-fleet/${CapacityReservationFleetId}", "capacity-reservation-modification-quote": "arn:${Partition}:ec2:${Region}:${Account}:capacity-reservation-modification-quote/${CapacityReservationModificationQuoteId}", "carrier-gateway": "arn:${Partition}:ec2:${Region}:${Account}:carrier-gateway/${CarrierGatewayId}", "certificate": "arn:${Partition}:acm:${Region}:${Account}:certificate/${CertificateId}", "client-vpn-endpoint": "arn:${Partition}:ec2:${Region}:${Account}:client-vpn-endpoint/${ClientVpnEndpointId}", "coip-pool": "arn:${Partition}:ec2:${Region}:${Account}:coip-pool/${Ipv4PoolCoipId}", "customer-gateway": "arn:${Partition}:ec2:${Region}:${Account}:customer-gateway/${CustomerGatewayId}", "declarative-policies-report": "arn:${Partition}:ec2:${Region}:${Account}:declarative-policies-report/${DeclarativePoliciesReportId}", "dedicated-host": "arn:${Partition}:ec2:${Region}:${Account}:dedicated-host/${DedicatedHostId}", "dhcp-options": "arn:${Partition}:ec2:${Region}:${Account}:dhcp-options/${DhcpOptionsId}", "egress-only-internet-gateway": "arn:${Partition}:ec2:${Region}:${Account}:egress-only-internet-gateway/${EgressOnlyInternetGatewayId}", "elastic-gpu": "arn:${Partition}:ec2:${Region}:${Account}:elastic-gpu/${ElasticGpuId}", "elastic-inference": "arn:${Partition}:elastic-inference:${Region}:${Account}:elastic-inference-accelerator/${AcceleratorId}", "elastic-ip": "arn:${Partition}:ec2:${Region}:${Account}:elastic-ip/${AllocationId}", "export-image-task": "arn:${Partition}:ec2:${Region}:${Account}:export-image-task/${ExportImageTaskId}", "export-instance-task": "arn:${Partition}:ec2:${Region}:${Account}:export-instance-task/${ExportTaskId}", "fleet": "arn:${Partition}:ec2:${Region}:${Account}:fleet/${FleetId}", "fpga-image": "arn:${Partition}:ec2:${Region}:${Account}:fpga-image/${FpgaImageId}", "group": "arn:${Partition}:resource-groups:${Region}:${Account}:group/${GroupName}", "host-reservation": "arn:${Partition}:ec2:${Region}:${Account}:host-reservation/${HostReservationId}", "image": "arn:${Partition}:ec2:${Region}::image/${ImageId}", "image-usage-report": "arn:${Partition}:ec2:${Region}:${Account}:image-usage-report/${ImageUsageReportId}", "import-image-task": "arn:${Partition}:ec2:${Region}:${Account}:import-image-task/${ImportImageTaskId}", "import-snapshot-task": "arn:${Partition}:ec2:${Region}:${Account}:import-snapshot-task/${ImportSnapshotTaskId}", "instance": "arn:${Partition}:ec2:${Region}:${Account}:instance/${InstanceId}", "instance-connect-endpoint": "arn:${Partition}:ec2:${Region}:${Account}:instance-connect-endpoint/${InstanceConnectEndpointId}", "instance-event-window": "arn:${Partition}:ec2:${Region}:${Account}:instance-event-window/${InstanceEventWindowId}", "internet-gateway": "arn:${Partition}:ec2:${Region}:${Account}:internet-gateway/${InternetGatewayId}", "ipam": "arn:${Partition}:ec2::${Account}:ipam/${IpamId}", "ipam-external-resource-verification-token": "arn:${Partition}:ec2::${Account}:ipam-external-resource-verification-token/${IpamExternalResourceVerificationTokenId}", "ipam-internet-registry-association": "arn:${Partition}:ec2::${Account}:ipam-internet-registry-association/${IpamInternetRegistryAssociationId}", "ipam-policy": "arn:${Partition}:ec2::${Account}:ipam-policy/${IpamPolicyId}", "ipam-pool": "arn:${Partition}:ec2::${Account}:ipam-pool/${IpamPoolId}", "ipam-pool-allocation": "arn:${Partition}:ec2:${Region}:${Account}:ipam-pool-allocation/${IpamPoolAllocationId}", "ipam-prefix-list-resolver": "arn:${Partition}:ec2::${Account}:ipam-prefix-list-resolver/${IpamPrefixListResolverId}", "ipam-prefix-list-resolver-target": "arn:${Partition}:ec2::${Account}:ipam-prefix-list-resolver-target/${IpamPrefixListResolverTargetId}", "ipam-resource-discovery": "arn:${Partition}:ec2::${Account}:ipam-resource-discovery/${IpamResourceDiscoveryId}", "ipam-resource-discovery-association": "arn:${Partition}:ec2::${Account}:ipam-resource-discovery-association/${IpamResourceDiscoveryAssociationId}", "ipam-scope": "arn:${Partition}:ec2::${Account}:ipam-scope/${IpamScopeId}", "ipv4pool-ec2": "arn:${Partition}:ec2:${Region}:${Account}:ipv4pool-ec2/${Ipv4PoolEc2Id}", "ipv6pool-ec2": "arn:${Partition}:ec2:${Region}:${Account}:ipv6pool-ec2/${Ipv6PoolEc2Id}", "key-pair": "arn:${Partition}:ec2:${Region}:${Account}:key-pair/${KeyPairName}", "launch-template": "arn:${Partition}:ec2:${Region}:${Account}:launch-template/${LaunchTemplateId}", "license-configuration": "arn:${Partition}:license-manager:${Region}:${Account}:license-configuration:${LicenseConfigurationId}", "local-gateway": "arn:${Partition}:ec2:${Region}:${Account}:local-gateway/${LocalGatewayId}", "local-gateway-route-table": "arn:${Partition}:ec2:${Region}:${Account}:local-gateway-route-table/${LocalGatewayRoutetableId}", "local-gateway-route-table-virtual-interface-group-association": "arn:${Partition}:ec2:${Region}:${Account}:local-gateway-route-table-virtual-interface-group-association/${LocalGatewayRouteTableVirtualInterfaceGroupAssociationId}", "local-gateway-route-table-vpc-association": "arn:${Partition}:ec2:${Region}:${Account}:local-gateway-route-table-vpc-association/${LocalGatewayRouteTableVpcAssociationId}", "local-gateway-virtual-interface": "arn:${Partition}:ec2:${Region}:${Account}:local-gateway-virtual-interface/${LocalGatewayVirtualInterfaceId}", "local-gateway-virtual-interface-group": "arn:${Partition}:ec2:${Region}:${Account}:local-gateway-virtual-interface-group/${LocalGatewayVirtualInterfaceGroupId}", "mac-modification-task": "arn:${Partition}:ec2:${Region}:${Account}:mac-modification-task/${MacModificationTaskId}", "natgateway": "arn:${Partition}:ec2:${Region}:${Account}:natgateway/${NatGatewayId}", "network-acl": "arn:${Partition}:ec2:${Region}:${Account}:network-acl/${NaclId}", "network-insights-access-scope": "arn:${Partition}:ec2:${Region}:${Account}:network-insights-access-scope/${NetworkInsightsAccessScopeId}", "network-insights-access-scope-analysis": "arn:${Partition}:ec2:${Region}:${Account}:network-insights-access-scope-analysis/${NetworkInsightsAccessScopeAnalysisId}", "network-insights-analysis": "arn:${Partition}:ec2:${Region}:${Account}:network-insights-analysis/${NetworkInsightsAnalysisId}", "network-insights-path": "arn:${Partition}:ec2:${Region}:${Account}:network-insights-path/${NetworkInsightsPathId}", "network-interface": "arn:${Partition}:ec2:${Region}:${Account}:network-interface/${NetworkInterfaceId}", "outpost-lag": "arn:${Partition}:ec2:${Region}:${Account}:outpost-lag/${OutpostLagId}", "placement-group": "arn:${Partition}:ec2:${Region}:${Account}:placement-group/${PlacementGroupName}", "prefix-list": "arn:${Partition}:ec2:${Region}:${Account}:prefix-list/${PrefixListId}", "replace-root-volume-task": "arn:${Partition}:ec2:${Region}:${Account}:replace-root-volume-task/${ReplaceRootVolumeTaskId}", "reserved-instances": "arn:${Partition}:ec2:${Region}:${Account}:reserved-instances/${ReservationId}", "role": "arn:${Partition}:iam::${Account}:role/${RoleNameWithPath}", "route-server": "arn:${Partition}:ec2:${Region}:${Account}:route-server/${RouteServerId}", "route-server-endpoint": "arn:${Partition}:ec2:${Region}:${Account}:route-server-endpoint/${RouteServerEndpointId}", "route-server-peer": "arn:${Partition}:ec2:${Region}:${Account}:route-server-peer/${RouteServerPeerId}", "route-table": "arn:${Partition}:ec2:${Region}:${Account}:route-table/${RouteTableId}", "secondary-interface": "arn:${Partition}:ec2:${Region}:${Account}:secondary-interface/${SecondaryInterfaceId}", "secondary-network": "arn:${Partition}:ec2:${Region}:${Account}:secondary-network/${SecondaryNetworkId}", "secondary-subnet": "arn:${Partition}:ec2:${Region}:${Account}:secondary-subnet/${SecondarySubnetId}", "security-group": "arn:${Partition}:ec2:${Region}:${Account}:security-group/${SecurityGroupId}", "security-group-rule": "arn:${Partition}:ec2:${Region}:${Account}:security-group-rule/${SecurityGroupRuleId}", "snapshot": "arn:${Partition}:ec2:${Region}::snapshot/${SnapshotId}", "spot-fleet-request": "arn:${Partition}:ec2:${Region}:${Account}:spot-fleet-request/${SpotFleetRequestId}", "spot-instances-request": "arn:${Partition}:ec2:${Region}:${Account}:spot-instances-request/${SpotInstanceRequestId}", "subnet": "arn:${Partition}:ec2:${Region}:${Account}:subnet/${SubnetId}", "subnet-cidr-reservation": "arn:${Partition}:ec2:${Region}:${Account}:subnet-cidr-reservation/${SubnetCidrReservationId}", "traffic-mirror-filter": "arn:${Partition}:ec2:${Region}:${Account}:traffic-mirror-filter/${TrafficMirrorFilterId}", "traffic-mirror-filter-rule": "arn:${Partition}:ec2:${Region}:${Account}:traffic-mirror-filter-rule/${TrafficMirrorFilterRuleId}", "traffic-mirror-session": "arn:${Partition}:ec2:${Region}:${Account}:traffic-mirror-session/${TrafficMirrorSessionId}", "traffic-mirror-target": "arn:${Partition}:ec2:${Region}:${Account}:traffic-mirror-target/${TrafficMirrorTargetId}", "transit-gateway": "arn:${Partition}:ec2:${Region}:${Account}:transit-gateway/${TransitGatewayId}", "transit-gateway-attachment": "arn:${Partition}:ec2:${Region}:${Account}:transit-gateway-attachment/${TransitGatewayAttachmentId}", "transit-gateway-connect-peer": "arn:${Partition}:ec2:${Region}:${Account}:transit-gateway-connect-peer/${TransitGatewayConnectPeerId}", "transit-gateway-metering-policy": "arn:${Partition}:ec2:${Region}:${Account}:transit-gateway-metering-policy/${TransitGatewayMeteringPolicyId}", "transit-gateway-multicast-domain": "arn:${Partition}:ec2:${Region}:${Account}:transit-gateway-multicast-domain/${TransitGatewayMulticastDomainId}", "transit-gateway-policy-table": "arn:${Partition}:ec2:${Region}:${Account}:transit-gateway-policy-table/${TransitGatewayPolicyTableId}", "transit-gateway-route-table": "arn:${Partition}:ec2:${Region}:${Account}:transit-gateway-route-table/${TransitGatewayRouteTableId}", "transit-gateway-route-table-announcement": "arn:${Partition}:ec2:${Region}:${Account}:transit-gateway-route-table-announcement/${TransitGatewayRouteTableAnnouncementId}", "verified-access-endpoint": "arn:${Partition}:ec2:${Region}:${Account}:verified-access-endpoint/${VerifiedAccessEndpointId}", "verified-access-endpoint-target": "arn:${Partition}:ec2:${Region}:${Account}:verified-access-endpoint-target/${VerifiedAccessEndpointTargetId}", "verified-access-group": "arn:${Partition}:ec2:${Region}:${Account}:verified-access-group/${VerifiedAccessGroupId}", "verified-access-instance": "arn:${Partition}:ec2:${Region}:${Account}:verified-access-instance/${VerifiedAccessInstanceId}", "verified-access-policy": "arn:${Partition}:ec2:${Region}:${Account}:verified-access-policy/${VerifiedAccessPolicyId}", "verified-access-trust-provider": "arn:${Partition}:ec2:${Region}:${Account}:verified-access-trust-provider/${VerifiedAccessTrustProviderId}", "volume": "arn:${Partition}:ec2:${Region}:${Account}:volume/${VolumeId}", "vpc": "arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}", "vpc-block-public-access-exclusion": "arn:${Partition}:ec2:${Region}:${Account}:vpc-block-public-access-exclusion/${VpcBlockPublicAccessExclusionId}", "vpc-encryption-control": "arn:${Partition}:ec2:${Region}:${Account}:vpc-encryption-control/${VpcEncryptionControlId}", "vpc-endpoint": "arn:${Partition}:ec2:${Region}:${Account}:vpc-endpoint/${VpcEndpointId}", "vpc-endpoint-connection": "arn:${Partition}:ec2:${Region}:${Account}:vpc-endpoint-connection/${VpcEndpointConnectionId}", "vpc-endpoint-service": "arn:${Partition}:ec2:${Region}:${Account}:vpc-endpoint-service/${VpcEndpointServiceId}", "vpc-endpoint-service-permission": "arn:${Partition}:ec2:${Region}:${Account}:vpc-endpoint-service-permission/${VpcEndpointServicePermissionId}", "vpc-flow-log": "arn:${Partition}:ec2:${Region}:${Account}:vpc-flow-log/${VpcFlowLogId}", "vpc-peering-connection": "arn:${Partition}:ec2:${Region}:${Account}:vpc-peering-connection/${VpcPeeringConnectionId}", "vpn-concentrator": "arn:${Partition}:ec2:${Region}:${Account}:vpn-concentrator/${VpnConcentratorId}", "vpn-connection": "arn:${Partition}:ec2:${Region}:${Account}:vpn-connection/${VpnConnectionId}", "vpn-connection-device-type": "arn:${Partition}:ec2:${Region}:${Account}:vpn-connection-device-type/${VpnConnectionDeviceTypeId}", "vpn-gateway": "arn:${Partition}:ec2:${Region}:${Account}:vpn-gateway/${VpnGatewayId}"}, "ec2-instance-connect": {"instance": "arn:${Partition}:ec2:${Region}:${Account}:instance/${InstanceId}", "instance-connect-endpoint": "arn:${Partition}:ec2:${Region}:${Account}:instance-connect-endpoint/${InstanceConnectEndpointId}"}, "ecr": {"repository": "arn:${Partition}:ecr:${Region}:${Account}:repository/${RepositoryName}"}, "ecs": {"capacity-provider": "arn:${Partition}:ecs:${Region}:${Account}:capacity-provider/${CapacityProviderName}", "cluster": "arn:${Partition}:ecs:${Region}:${Account}:cluster/${ClusterName}", "container-instance": "arn:${Partition}:ecs:${Region}:${Account}:container-instance/${ClusterName}/${ContainerInstanceId}", "daemon": "arn:${Partition}:ecs:${Region}:${Account}:daemon/${ClusterName}/${DaemonName}", "daemon-deployment": "arn:${Partition}:ecs:${Region}:${Account}:daemon-deployment/${ClusterName}/${DaemonName}/${DaemonDeploymentId}", "daemon-revision": "arn:${Partition}:ecs:${Region}:${Account}:daemon-revision/${ClusterName}/${DaemonName}/${DaemonRevisionId}", "daemon-task-definition": "arn:${Partition}:ecs:${Region}:${Account}:daemon-task-definition/${DaemonTaskDefinitionFamilyName}:${DaemonTaskDefinitionRevisionNumber}", "gateway": "arn:${Partition}:ecs:${Region}:${Account}:gateway/${GatewayName}/${GatewayId}", "gateway-route": "arn:${Partition}:ecs:${Region}:${Account}:gateway-route/${GatewayName}/${GatewayId}/${RouteId}", "service": "arn:${Partition}:ecs:${Region}:${Account}:service/${ClusterName}/${ServiceName}", "service-deployment": "arn:${Partition}:ecs:${Region}:${Account}:service-deployment/${ClusterName}/${ServiceName}/${ServiceDeploymentId}", "service-revision": "arn:${Partition}:ecs:${Region}:${Account}:service-revision/${ClusterName}/${ServiceName}/${ServiceRevisionId}", "task": "arn:${Partition}:ecs:${Region}:${Account}:task/${ClusterName}/${TaskId}", "task-definition": "arn:${Partition}:ecs:${Region}:${Account}:task-definition/${TaskDefinitionFamilyName}:${TaskDefinitionRevisionNumber}", "task-set": "arn:${Partition}:ecs:${Region}:${Account}:task-set/${ClusterName}/${ServiceName}/${TaskSetId}"}, "eks": {"access-entry": "arn:${Partition}:eks:${Region}:${Account}:access-entry/${ClusterName}/${IamIdentityType}/${IamIdentityAccountID}/${IamIdentityName}/${UUID}", "access-policy": "arn:${Partition}:eks::aws:cluster-access-policy/${AccessPolicyName}", "addon": "arn:${Partition}:eks:${Region}:${Account}:addon/${ClusterName}/${AddonName}/${UUID}", "capability": "arn:${Partition}:eks:${Region}:${Account}:capability/${ClusterName}/${CapabilityType}/${CapabilityName}/${UUID}", "cluster": "arn:${Partition}:eks:${Region}:${Account}:cluster/${ClusterName}", "dashboard": "arn:${Partition}:eks:${Region}:${Account}:dashboard/${DashboardName}", "eks-anywhere-subscription": "arn:${Partition}:eks:${Region}:${Account}:eks-anywhere-subscription/${UUID}", "fargateprofile": "arn:${Partition}:eks:${Region}:${Account}:fargateprofile/${ClusterName}/${FargateProfileName}/${UUID}", "identityproviderconfig": "arn:${Partition}:eks:${Region}:${Account}:identityproviderconfig/${ClusterName}/${IdentityProviderType}/${IdentityProviderConfigName}/${UUID}", "nodegroup": "arn:${Partition}:eks:${Region}:${Account}:nodegroup/${ClusterName}/${NodegroupName}/${UUID}", "podidentityassociation": "arn:${Partition}:eks:${Region}:${Account}:podidentityassociation/${ClusterName}/${UUID}"}, "elasticloadbalancing": {"listener-rule/app": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener-rule/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${ListenerRuleId}", "listener-rule/net": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener-rule/net/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${ListenerRuleId}", "listener/app": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "listener/gwy": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/gwy/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "listener/net": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:listener/net/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}", "loadbalancer": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/${LoadBalancerName}", "loadbalancer/app/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/app/${LoadBalancerName}/${LoadBalancerId}", "loadbalancer/gwy/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/gwy/${LoadBalancerName}/${LoadBalancerId}", "loadbalancer/net/": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:loadbalancer/net/${LoadBalancerName}/${LoadBalancerId}", "targetgroup": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:targetgroup/${TargetGroupName}/${TargetGroupId}", "truststore": "arn:${Partition}:elasticloadbalancing:${Region}:${Account}:truststore/${TrustStoreName}/${TrustStoreId}"}, "elasticmapreduce": {"cluster": "arn:${Partition}:elasticmapreduce:${Region}:${Account}:cluster/${ClusterId}", "editor": "arn:${Partition}:elasticmapreduce:${Region}:${Account}:editor/${EditorId}", "notebook-execution": "arn:${Partition}:elasticmapreduce:${Region}:${Account}:notebook-execution/${NotebookExecutionId}", "session": "arn:${Partition}:elasticmapreduce:${Region}:${Account}:cluster/${ClusterId}/session/${SessionId}", "studio": "arn:${Partition}:elasticmapreduce:${Region}:${Account}:studio/${StudioId}"}, "emr-containers": {"jobRun": "arn:${Partition}:emr-containers:${Region}:${Account}:/virtualclusters/${VirtualClusterId}/jobruns/${JobRunId}", "jobTemplate": "arn:${Partition}:emr-containers:${Region}:${Account}:/jobtemplates/${JobTemplateId}", "managedEndpoint": "arn:${Partition}:emr-containers:${Region}:${Account}:/virtualclusters/${VirtualClusterId}/endpoints/${EndpointId}", "securityConfiguration": "arn:${Partition}:emr-containers:${Region}:${Account}:/securityconfigurations/${SecurityConfigurationId}", "virtualCluster": "arn:${Partition}:emr-containers:${Region}:${Account}:/virtualclusters/${VirtualClusterId}"}, "emr-serverless": {"application": "arn:${Partition}:emr-serverless:${Region}:${Account}:/applications/${ApplicationId}", "jobRun": "arn:${Partition}:emr-serverless:${Region}:${Account}:/applications/${ApplicationId}/jobruns/${JobRunId}", "session": "arn:${Partition}:emr-serverless:${Region}:${Account}:/applications/${ApplicationId}/sessions/${SessionId}"}, "es": {"application": "arn:${Partition}:opensearch:${Region}:${Account}:application/${AppId}", "datasource": "arn:${Partition}:opensearch:${Region}:${Account}:datasource/${DataSourceName}", "domain": "arn:${Partition}:es:${Region}:${Account}:domain/${DomainName}", "es_role": "arn:${Partition}:iam::${Account}:role/aws-service-role/es.amazonaws.com/AWSServiceRoleForAmazonOpenSearchService", "opensearchservice_role": "arn:${Partition}:iam::${Account}:role/aws-service-role/opensearchservice.amazonaws.com/AWSServiceRoleForAmazonOpenSearchService"}, "events": {"alias": "arn:${Partition}:kms:${Region}:${Account}:alias/${Alias}", "api-destination": "arn:${Partition}:events:${Region}:${Account}:api-destination/${ApiDestinationName}", "archive": "arn:${Partition}:events:${Region}:${Account}:archive/${ArchiveName}", "connection": "arn:${Partition}:events:${Region}:${Account}:connection/${ConnectionName}", "create-snapshot": "arn:${Partition}:events:${Region}:${Account}:target/create-snapshot", "endpoint": "arn:${Partition}:events:${Region}:${Account}:endpoint/${EndpointName}", "event-bus": "arn:${Partition}:events:${Region}:${Account}:event-bus/${EventBusName}", "event-busv2": "arn:${Partition}:events:${Region}:${Account}:event-busv2/${EventBusName}/${OpaqueId}", "event-source": "arn:${Partition}:events:${Region}::event-source/${EventSourceName}", "event-sourcev2": "arn:${Partition}:events:${Region}:${Account}:event-sourcev2/${SourceType}/${EventSourceName}/${OpaqueId}", "key": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}", "reboot-instance": "arn:${Partition}:events:${Region}:${Account}:target/reboot-instance", "replay": "arn:${Partition}:events:${Region}:${Account}:replay/${ReplayName}", "rule-on-custom-event-bus": "arn:${Partition}:events:${Region}:${Account}:rule/${EventBusName}/${RuleName}", "rule-on-default-event-bus": "arn:${Partition}:events:${Region}:${Account}:rule/${RuleName}", "stop-instance": "arn:${Partition}:events:${Region}:${Account}:target/stop-instance", "subscriber": "arn:${Partition}:events:${Region}:${Account}:subscriber/${SubscriberName}/${OpaqueId}", "terminate-instance": "arn:${Partition}:events:${Region}:${Account}:target/terminate-instance"}, "firehose": {"deliverystream": "arn:${Partition}:firehose:${Region}:${Account}:deliverystream/${DeliveryStreamName}"}, "fis": {"action": "arn:${Partition}:fis:${Region}:${Account}:action/${Id}", "experiment": "arn:${Partition}:fis:${Region}:${Account}:experiment/${Id}", "experiment-template": "arn:${Partition}:fis:${Region}:${Account}:experiment-template/${Id}", "safety-lever": "arn:${Partition}:fis:${Region}:${Account}:safety-lever/${Id}"}, "globalaccelerator": {"accelerator": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}", "attachment": "arn:${Partition}:globalaccelerator::${Account}:attachment/${ResourceId}", "endpointgroup": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}/listener/${ListenerId}/endpoint-group/${EndpointGroupId}", "listener": "arn:${Partition}:globalaccelerator::${Account}:accelerator/${ResourceId}/listener/${ListenerId}"}, "glue": {"blueprint": "arn:${Partition}:glue:${Region}:${Account}:blueprint/${BlueprintName}", "catalog": "arn:${Partition}:glue:${Region}:${Account}:catalog/${CatalogName}", "completion": "arn:${Partition}:glue:${Region}:${Account}:completion/${CompletionId}", "connection": "arn:${Partition}:glue:${Region}:${Account}:connection/${ConnectionName}", "connectionType": "arn:${Partition}:glue:${Region}:${Account}:connectionType:${ConnectionTypeName}", "crawler": "arn:${Partition}:glue:${Region}:${Account}:crawler/${CrawlerName}", "customEntityType": "arn:${Partition}:glue:${Region}:${Account}:customEntityType/${CustomEntityTypeId}", "dataQualityEvaluationConfig": "arn:${Partition}:glue:${Region}:${Account}:dataQualityEvaluationConfig/${EvaluationConfigName}", "dataQualityRuleset": "arn:${Partition}:glue:${Region}:${Account}:dataQualityRuleset/${RulesetName}", "database": "arn:${Partition}:glue:${Region}:${Account}:database/${DatabaseName}", "devendpoint": "arn:${Partition}:glue:${Region}:${Account}:devEndpoint/${DevEndpointName}", "integration": "arn:${Partition}:glue:${Region}:${Account}:integration:${IntegrationId}", "integrationResourceProperty": "arn:${Partition}:glue:${Region}:${Account}:integrationresourceproperty/${ResourceType}/${ResourceName}", "job": "arn:${Partition}:glue:${Region}:${Account}:job/${JobName}", "mlTransform": "arn:${Partition}:glue:${Region}:${Account}:mlTransform/${TransformId}", "registry": "arn:${Partition}:glue:${Region}:${Account}:registry/${RegistryName}", "rootcatalog": "arn:${Partition}:glue:${Region}:${Account}:catalog", "schema": "arn:${Partition}:glue:${Region}:${Account}:schema/${SchemaName}", "session": "arn:${Partition}:glue:${Region}:${Account}:session/${SessionId}", "table": "arn:${Partition}:glue:${Region}:${Account}:table/${DatabaseName}/${TableName}", "tableversion": "arn:${Partition}:glue:${Region}:${Account}:tableVersion/${DatabaseName}/${TableName}/${TableVersionName}", "trigger": "arn:${Partition}:glue:${Region}:${Account}:trigger/${TriggerName}", "usageProfile": "arn:${Partition}:glue:${Region}:${Account}:usageProfile/${UsageProfileId}", "userdefinedfunction": "arn:${Partition}:glue:${Region}:${Account}:userDefinedFunction/${DatabaseName}/${UserDefinedFunctionName}", "workflow": "arn:${Partition}:glue:${Region}:${Account}:workflow/${WorkflowName}"}, "guardduty": {"customdetectionrule": "arn:${Partition}:guardduty::aws:detection-rule/custom/${RuleId}", "customdetectionruleassociation": "arn:${Partition}:guardduty:${Region}:${Account}:detection-rule/custom/${RuleId}/association/${AssociationId}", "detector": "arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}", "filter": "arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/filter/${FilterName}", "ipset": "arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/ipset/${IPSetId}", "malwareprotectionplan": "arn:${Partition}:guardduty:${Region}:${Account}:malware-protection-plan/${MalwareProtectionPlanId}", "publishingDestination": "arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/publishingdestination/${PublishingDestinationId}", "threatentityset": "arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/threatentityset/${ThreatEntitySetId}", "threatintelset": "arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/threatintelset/${ThreatIntelSetId}", "trustedentityset": "arn:${Partition}:guardduty:${Region}:${Account}:detector/${DetectorId}/trustedentityset/${TrustedEntitySetId}"}, "inspector2": {"CIS Scan Configuration": "arn:${Partition}:inspector2:${Region}:${Account}:owner/${OwnerId}/cis-configuration/${CISScanConfigurationId}", "Code Security Integration": "arn:${Partition}:inspector2:${Region}:${Account}:codesecurity-integration/${CodeSecurityIntegrationId}", "Code Security Scan Configuration": "arn:${Partition}:inspector2:${Region}:${Account}:owner/${OwnerId}/codesecurity-configuration/${CodeSecurityScanConfigurationId}", "Connector": "arn:${Partition}:inspector2:${Region}:${Account}:connector/${ConnectorId}", "Filter": "arn:${Partition}:inspector2:${Region}:${Account}:owner/${OwnerId}/filter/${FilterId}", "Finding": "arn:${Partition}:inspector2:${Region}:${Account}:finding/${FindingId}"}, "kinesis": {"channel": "arn:${Partition}:kinesis:${Region}:${Account}:channel/${ChannelId}", "consumer": "arn:${Partition}:kinesis:${Region}:${Account}:${StreamType}/${StreamName}/consumer/${ConsumerName}:${ConsumerCreationTimpstamp}", "kmsKey": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}", "queue": "arn:${Partition}:kinesis:${Region}:${Account}:queue/${QueueId}", "stream": "arn:${Partition}:kinesis:${Region}:${Account}:stream/${StreamName}"}, "kinesisanalytics": {"application": "arn:${Partition}:kinesisanalytics:${Region}:${Account}:application/${ApplicationName}", "snapshot": "arn:${Partition}:kinesisanalytics:${Region}:${Account}:snapshot/${SnapshotName}"}, "kms": {"alias": "arn:${Partition}:kms:${Region}:${Account}:alias/${Alias}", "key": "arn:${Partition}:kms:${Region}:${Account}:key/${KeyId}"}, "lambda": {"capacityProvider": "arn:${Partition}:lambda:${Region}:${Account}:capacity-provider:${CapacityProviderName}", "code signing config": "arn:${Partition}:lambda:${Region}:${Account}:code-signing-config:${CodeSigningConfigId}", "durable execution": "arn:${Partition}:lambda:${Region}:${Account}:function:${FunctionName}:${Version}/durable-execution/${ExecutionName}/${ExecutionId}", "eventSourceMapping": "arn:${Partition}:lambda:${Region}:${Account}:event-source-mapping:${UUID}", "function": "arn:${Partition}:lambda:${Region}:${Account}:function:${FunctionName}", "function alias": "arn:${Partition}:lambda:${Region}:${Account}:function:${FunctionName}:${Alias}", "function version": "arn:${Partition}:lambda:${Region}:${Account}:function:${FunctionName}:${Version}", "layer": "arn:${Partition}:lambda:${Region}:${Account}:layer:${LayerName}", "layerVersion": "arn:${Partition}:lambda:${Region}:${Account}:layer:${LayerName}:${LayerVersion}", "microvmImage": "arn:${Partition}:lambda:${Region}:${Account}:microvm-image:${MicrovmImageName}", "networkConnector": "arn:${Partition}:lambda:${Region}:${Account}:network-connector:${NetworkConnectorId}", "runtime": "arn:${Partition}:lambda:${Region}:${Account}:runtime/${RuntimeName}", "runtimeAlias": "arn:${Partition}:lambda:${Region}:${Account}:runtime/${RuntimeName}/alias/${Name}", "runtimeVersion": "arn:${Partition}:lambda:${Region}:${Account}:runtime/${RuntimeName}/version/${Name}", "webFunction": "arn:${Partition}:lambda:${Region}:${Account}:web-function/${FunctionName}", "webFunctionEndpoint": "arn:${Partition}:lambda:${Region}:${Account}:web-function/${FunctionName}/endpoint/${EndpointName}", "webFunctionRevision": "arn:${Partition}:lambda:${Region}:${Account}:web-function/${FunctionName}/revision/${RevisionId}"}, "logs": {"anomaly-detector": "arn:${Partition}:logs:${Region}:${Account}:anomaly-detector:${DetectorId}", "delivery": "arn:${Partition}:logs:${Region}:${Account}:delivery:${DeliveryName}", "delivery-destination": "arn:${Partition}:logs:${Region}:${Account}:delivery-destination:${DeliveryDestinationName}", "delivery-source": "arn:${Partition}:logs:${Region}:${Account}:delivery-source:${DeliverySourceName}", "destination": "arn:${Partition}:logs:${Region}:${Account}:destination:${DestinationName}", "log-group": "arn:${Partition}:logs:${Region}:${Account}:log-group:${LogGroupName}", "log-stream": "arn:${Partition}:logs:${Region}:${Account}:log-group:${LogGroupName}:log-stream:${LogStreamName}", "lookup-table": "arn:${Partition}:logs:${Region}:${Account}:lookup-table:${LookupTableName}", "scheduled-query": "arn:${Partition}:logs:${Region}:${Account}:scheduled-query:${ScheduledQueryId}"}, "macie2": {"AllowList": "arn:${Partition}:macie2:${Region}:${Account}:allow-list/${ResourceId}", "ClassificationJob": "arn:${Partition}:macie2:${Region}:${Account}:classification-job/${ResourceId}", "CustomDataIdentifier": "arn:${Partition}:macie2:${Region}:${Account}:custom-data-identifier/${ResourceId}", "FindingsFilter": "arn:${Partition}:macie2:${Region}:${Account}:findings-filter/${ResourceId}", "Member": "arn:${Partition}:macie2:${Region}:${Account}:member/${ResourceId}"}, "oam": {"Link": "arn:${Partition}:oam:${Region}:${Account}:link/${ResourceId}", "Sink": "arn:${Partition}:oam:${Region}:${Account}:sink/${ResourceId}"}, "payment-cryptography": {"alias": "arn:${Partition}:payment-cryptography:${Region}:${Account}:alias/${Alias}", "approval-team": "arn:${Partition}:mpa:${Region}:${Account}:approval-team/${ApprovalTeamId}", "key": "arn:${Partition}:payment-cryptography:${Region}:${Account}:key/${KeyId}"}, "pipes": {"pipe": "arn:${Partition}:pipes:${Region}:${Account}:pipe/${Name}"}, "quicksight": {"accessControlApplication": "arn:${Partition}:quicksight:${Region}:${Account}:access-control-application/${ResourceId}", "account": "arn:${Partition}:quicksight:${Region}:${Account}:account/${ResourceId}", "actionconnector": "arn:${Partition}:quicksight:${Region}:${Account}:action-connector/${ResourceId}", "agent": "arn:${Partition}:quicksight:${Region}:${Account}:agent/${ResourceId}", "analysis": "arn:${Partition}:quicksight:${Region}:${Account}:analysis/${ResourceId}", "app": "arn:${Partition}:quicksight:${Region}:${Account}:app/${ResourceId}", "approvalPolicy": "arn:${Partition}:quicksight:${Region}:${Account}:approval-policy/${ResourceId}", "assetBundleExportJob": "arn:${Partition}:quicksight:${Region}:${Account}:asset-bundle-export-job/${ResourceId}", "assetBundleImportJob": "arn:${Partition}:quicksight:${Region}:${Account}:asset-bundle-import-job/${ResourceId}", "assignment": "arn:${Partition}:quicksight::${Account}:assignment/${ResourceId}", "automation": "arn:${Partition}:quicksight:${Region}:${Account}:automation-group/${AutomationGroupId}/automation/${ResourceId}", "automationGroup": "arn:${Partition}:quicksight:${Region}:${Account}:automation-group/${ResourceId}", "automationJob": "arn:${Partition}:quicksight:${Region}:${Account}:automation-group/${AutomationGroupId}/automation/${AutomationId}/job/${ResourceId}", "brand": "arn:${Partition}:quicksight:${Region}:${Account}:brand/${ResourceId}", "customization": "arn:${Partition}:quicksight:${Region}:${Account}:customization/${ResourceId}", "custompermissions": "arn:${Partition}:quicksight:${Region}:${Account}:custompermissions/${ResourceId}", "dashboard": "arn:${Partition}:quicksight:${Region}:${Account}:dashboard/${ResourceId}", "dashboardSnapshotJob": "arn:${Partition}:quicksight:${Region}:${Account}:dashboard/${DashboardId}/snapshot-job/${ResourceId}", "dataset": "arn:${Partition}:quicksight:${Region}:${Account}:dataset/${ResourceId}", "datasource": "arn:${Partition}:quicksight:${Region}:${Account}:datasource/${ResourceId}", "dlpSetting": "arn:${Partition}:quicksight:${Region}:${Account}:dlpsetting/${ResourceId}", "emailCustomizationTemplate": "arn:${Partition}:quicksight:${Region}:${Account}:email-customization-template/${ResourceId}", "extension": "arn:${Partition}:quicksight:${Region}:${Account}:extension/${ResourceId}", "extensionaccess": "arn:${Partition}:quicksight:${Region}:${Account}:extension-access/${ResourceId}", "flow": "arn:${Partition}:quicksight:${Region}:${Account}:flow/${ResourceId}", "folder": "arn:${Partition}:quicksight:${Region}:${Account}:folder/${ResourceId}", "group": "arn:${Partition}:quicksight:${Region}:${Account}:group/${ResourceId}", "inboundConnector": "arn:${Partition}:quicksight:${Region}:${Account}:inbound-connector/${ResourceId}", "ingestion": "arn:${Partition}:quicksight:${Region}:${Account}:dataset/${DatasetId}/ingestion/${ResourceId}", "knowledgeBase": "arn:${Partition}:quicksight:${Region}:${Account}:knowledge-base/${ResourceId}", "limitsProfile": "arn:${Partition}:quicksight:${Region}:${Account}:limits-profile/${ResourceId}", "namespace": "arn:${Partition}:quicksight:${Region}:${Account}:namespace/${ResourceId}", "oauthClientApplication": "arn:${Partition}:quicksight:${Region}:${Account}:oauthClientApplication/${ResourceId}", "refreshschedule": "arn:${Partition}:quicksight:${Region}:${Account}:dataset/${DatasetId}/refresh-schedule/${ResourceId}", "space": "arn:${Partition}:quicksight:${Region}:${Account}:space/${ResourceId}", "template": "arn:${Partition}:quicksight:${Region}:${Account}:template/${ResourceId}", "theme": "arn:${Partition}:quicksight:${Region}:${Account}:theme/${ResourceId}", "topic": "arn:${Partition}:quicksight:${Region}:${Account}:topic/${ResourceId}", "user": "arn:${Partition}:quicksight:${Region}:${Account}:user/${ResourceId}", "vpcconnection": "arn:${Partition}:quicksight:${Region}:${Account}:vpcConnection/${ResourceId}"}, "ram": {"customer-managed-permission": "arn:${Partition}:ram:${Region}:${Account}:permission/${ResourcePath}", "permission": "arn:${Partition}:ram::aws:permission/${ResourcePath}", "resource-share": "arn:${Partition}:ram:${Region}:${Account}:resource-share/${ResourcePath}", "resource-share-invitation": "arn:${Partition}:ram:${Region}:${Account}:resource-share-invitation/${ResourcePath}"}, "rds": {"auto-backup": "arn:${Partition}:rds:${Region}:${Account}:auto-backup:${DbInstanceAutomatedBackupId}", "cev": "arn:${Partition}:rds:${Region}:${Account}:cev:${Engine}/${EngineVersion}/${CustomDbEngineVersionId}", "cluster": "arn:${Partition}:rds:${Region}:${Account}:cluster:${DbClusterInstanceName}", "cluster-auto-backup": "arn:${Partition}:rds:${Region}:${Account}:cluster-auto-backup:${DbClusterAutomatedBackupId}", "cluster-endpoint": "arn:${Partition}:rds:${Region}:${Account}:cluster-endpoint:${DbClusterEndpoint}", "cluster-pg": "arn:${Partition}:rds:${Region}:${Account}:cluster-pg:${ClusterParameterGroupName}", "cluster-snapshot": "arn:${Partition}:rds:${Region}:${Account}:cluster-snapshot:${ClusterSnapshotName}", "db": "arn:${Partition}:rds:${Region}:${Account}:db:${DbInstanceName}", "db-capacity-reservation": "arn:${Partition}:rds:${Region}:${Account}:db-capacity-reservation:${DBCapacityReservationIdentifier}", "deployment": "arn:${Partition}:rds:${Region}:${Account}:deployment:${BlueGreenDeploymentIdentifier}", "es": "arn:${Partition}:rds:${Region}:${Account}:es:${SubscriptionName}", "global-cluster": "arn:${Partition}:rds::${Account}:global-cluster:${GlobalCluster}", "integration": "arn:${Partition}:rds:${Region}:${Account}:integration:${IntegrationIdentifier}", "og": "arn:${Partition}:rds:${Region}:${Account}:og:${OptionGroupName}", "pg": "arn:${Partition}:rds:${Region}:${Account}:pg:${ParameterGroupName}", "proxy": "arn:${Partition}:rds:${Region}:${Account}:db-proxy:${DbProxyId}", "proxy-endpoint": "arn:${Partition}:rds:${Region}:${Account}:db-proxy-endpoint:${DbProxyEndpointId}", "ri": "arn:${Partition}:rds:${Region}:${Account}:ri:${ReservedDbInstanceName}", "secgrp": "arn:${Partition}:rds:${Region}:${Account}:secgrp:${SecurityGroupName}", "shardgrp": "arn:${Partition}:rds:${Region}:${Account}:shard-group:${DbShardGroupResourceId}", "snapshot": "arn:${Partition}:rds:${Region}:${Account}:snapshot:${SnapshotName}", "snapshot-tenant-database": "arn:${Partition}:rds:${Region}:${Account}:snapshot-tenant-database:${SnapshotName}:${TenantResourceId}", "subgrp": "arn:${Partition}:rds:${Region}:${Account}:subgrp:${SubnetGroupName}", "target-group": "arn:${Partition}:rds:${Region}:${Account}:target-group:${TargetGroupId}", "tenant-database": "arn:${Partition}:rds:${Region}:${Account}:tenant-database:${TenantResourceId}"}, "redshift": {"cluster": "arn:${Partition}:redshift:${Region}:${Account}:cluster:${ClusterName}", "datashare": "arn:${Partition}:redshift:${Region}:${Account}:datashare:${ProducerClusterNamespace}/${DataShareName}", "dbgroup": "arn:${Partition}:redshift:${Region}:${Account}:dbgroup:${ClusterName}/${DbGroup}", "dbname": "arn:${Partition}:redshift:${Region}:${Account}:dbname:${ClusterName}/${DbName}", "dbuser": "arn:${Partition}:redshift:${Region}:${Account}:dbuser:${ClusterName}/${DbUser}", "eventsubscription": "arn:${Partition}:redshift:${Region}:${Account}:eventsubscription:${EventSubscriptionName}", "hsmclientcertificate": "arn:${Partition}:redshift:${Region}:${Account}:hsmclientcertificate:${HSMClientCertificateId}", "hsmconfiguration": "arn:${Partition}:redshift:${Region}:${Account}:hsmconfiguration:${HSMConfigurationId}", "integration": "arn:${Partition}:redshift:${Region}:${Account}:integration:${IntegrationIdentifier}", "namespace": "arn:${Partition}:redshift:${Region}:${Account}:namespace:${ClusterNamespace}", "parametergroup": "arn:${Partition}:redshift:${Region}:${Account}:parametergroup:${ParameterGroupName}", "qev2idcapplication": "arn:${Partition}:redshift:${Region}:${Account}:qev2idcapplication:${Qev2IdcApplicationId}", "redshiftidcapplication": "arn:${Partition}:redshift:${Region}:${Account}:redshiftidcapplication:${RedshiftIdcApplicationId}", "securitygroup": "arn:${Partition}:redshift:${Region}:${Account}:securitygroup:${SecurityGroupName}/ec2securitygroup/${Owner}/${Ec2SecurityGroupId}", "securitygroupingress-cidr": "arn:${Partition}:redshift:${Region}:${Account}:securitygroupingress:${SecurityGroupName}/cidrip/${IpRange}", "securitygroupingress-ec2securitygroup": "arn:${Partition}:redshift:${Region}:${Account}:securitygroupingress:${SecurityGroupName}/ec2securitygroup/${Owner}/${Ece2SecuritygroupId}", "snapshot": "arn:${Partition}:redshift:${Region}:${Account}:snapshot:${ClusterName}/${SnapshotName}", "snapshotcopygrant": "arn:${Partition}:redshift:${Region}:${Account}:snapshotcopygrant:${SnapshotCopyGrantName}", "snapshotschedule": "arn:${Partition}:redshift:${Region}:${Account}:snapshotschedule:${ScheduleIdentifier}", "subnetgroup": "arn:${Partition}:redshift:${Region}:${Account}:subnetgroup:${SubnetGroupName}", "usagelimit": "arn:${Partition}:redshift:${Region}:${Account}:usagelimit:${UsageLimitId}"}, "redshift-data": {"cluster": "arn:${Partition}:redshift:${Region}:${Account}:cluster:${ClusterName}", "managed-workgroup": "arn:${Partition}:redshift-serverless:${Region}:${Account}:managed-workgroup/${ManagedWorkgroupId}", "workgroup": "arn:${Partition}:redshift-serverless:${Region}:${Account}:workgroup/${WorkgroupId}"}, "redshift-serverless": {"endpointAccess": "arn:${Partition}:redshift-serverless:${Region}:${Account}:managedvpcendpoint/${EndpointAccessId}", "managed-workgroup": "arn:${Partition}:redshift-serverless:${Region}:${Account}:managed-workgroup/${ManagedWorkgroupName}", "namespace": "arn:${Partition}:redshift-serverless:${Region}:${Account}:namespace/${NamespaceId}", "recoveryPoint": "arn:${Partition}:redshift-serverless:${Region}:${Account}:recoverypoint/${RecoveryPointId}", "snapshot": "arn:${Partition}:redshift-serverless:${Region}:${Account}:snapshot/${SnapshotId}", "workgroup": "arn:${Partition}:redshift-serverless:${Region}:${Account}:workgroup/${WorkgroupId}"}, "rekognition": {"collection": "arn:${Partition}:rekognition:${Region}:${Account}:collection/${CollectionId}", "dataset": "arn:${Partition}:rekognition:${Region}:${Account}:project/${ProjectName}/dataset/${DatasetType}/${CreationTimestamp}", "project": "arn:${Partition}:rekognition:${Region}:${Account}:project/${ProjectName}/${CreationTimestamp}", "projectversion": "arn:${Partition}:rekognition:${Region}:${Account}:project/${ProjectName}/version/${VersionName}/${CreationTimestamp}", "streamprocessor": "arn:${Partition}:rekognition:${Region}:${Account}:streamprocessor/${StreamprocessorId}"}, "resource-explorer-2": {"index": "arn:${Partition}:resource-explorer-2:${Region}:${Account}:index/${IndexUuid}", "managed-view": "arn:${Partition}:resource-explorer-2:${Region}:${Account}:managed-view/${ManagedViewName}/${ManagedViewUuid}", "view": "arn:${Partition}:resource-explorer-2:${Region}:${Account}:view/${ViewName}/${ViewUuid}"}, "resource-groups": {"group": "arn:${Partition}:resource-groups:${Region}:${Account}:group/${GroupName}", "tagSyncTask": "arn:${Partition}:resource-groups:${Region}:${Account}:group/${GroupName}/tag-sync-task/${TaskId}"}, "route53": {"change": "arn:${Partition}:route53:::change/${Id}", "cidrcollection": "arn:${Partition}:route53:::cidrcollection/${Id}", "delegationset": "arn:${Partition}:route53:::delegationset/${Id}", "healthcheck": "arn:${Partition}:route53:::healthcheck/${Id}", "healthchecksource": "arn:${Partition}:route53:::healthchecksource/${Id}", "hostedzone": "arn:${Partition}:route53:::hostedzone/${Id}", "queryloggingconfig": "arn:${Partition}:route53:::queryloggingconfig/${Id}", "trafficpolicy": "arn:${Partition}:route53:::trafficpolicy/${Id}", "trafficpolicyinstance": "arn:${Partition}:route53:::trafficpolicyinstance/${Id}", "vpc": "arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}"}, "s3": {"accessgrant": "arn:${Partition}:s3:${Region}:${Account}:access-grants/default/grant/${Token}", "accessgrantsinstance": "arn:${Partition}:s3:${Region}:${Account}:access-grants/default", "accessgrantslocation": "arn:${Partition}:s3:${Region}:${Account}:access-grants/default/location/${Token}", "accesspoint": "arn:${Partition}:s3:${Region}:${Account}:accesspoint/${AccessPointName}", "accesspointobject": "arn:${Partition}:s3:${Region}:${Account}:accesspoint/${AccessPointName}/object/${ObjectName}", "bucket": "arn:${Partition}:s3:::${BucketName}", "job": "arn:${Partition}:s3:${Region}:${Account}:job/${JobId}", "multiregionaccesspoint": "arn:${Partition}:s3::${Account}:accesspoint/${AccessPointAlias}", "multiregionaccesspointrequestarn": "arn:${Partition}:s3:us-west-2:${Account}:async-request/mrap/${Operation}/${Token}", "object": "arn:${Partition}:s3:::${BucketName}/${ObjectName}", "objectlambdaaccesspoint": "arn:${Partition}:s3-object-lambda:${Region}:${Account}:accesspoint/${AccessPointName}", "storagelensconfiguration": "arn:${Partition}:s3:${Region}:${Account}:storage-lens/${ConfigId}", "storagelensgroup": "arn:${Partition}:s3:${Region}:${Account}:storage-lens-group/${Name}"}, "s3tables": {"Table": "arn:${Partition}:s3tables:${Region}:${Account}:bucket/${TableBucketName}/table/${TableID}", "TableBucket": "arn:${Partition}:s3tables:${Region}:${Account}:bucket/${TableBucketName}"}, "s3vectors": {"Index": "arn:${Partition}:s3vectors:${Region}:${Account}:bucket/${BucketName}/index/${IndexName}", "VectorBucket": "arn:${Partition}:s3vectors:${Region}:${Account}:bucket/${BucketName}"}, "scheduler": {"schedule": "arn:${Partition}:scheduler:${Region}:${Account}:schedule/${GroupName}/${ScheduleName}", "schedule-group": "arn:${Partition}:scheduler:${Region}:${Account}:schedule-group/${GroupName}"}, "secretsmanager": {"Secret": "arn:${Partition}:secretsmanager:${Region}:${Account}:secret:${SecretId}"}, "securityhub": {"aggregatorv2": "arn:${Partition}:securityhub:${Region}:${Account}:aggregatorv2/${AggregatorV2Id}", "automation-rule": "arn:${Partition}:securityhub:${Region}:${Account}:automation-rule/${AutomationRuleId}", "automation-rulev2": "arn:${Partition}:securityhub:${Region}:${Account}:automation-rulev2/${AutomationRuleV2Id}", "configuration-policy": "arn:${Partition}:securityhub:${Region}:${Account}:configuration-policy/${ConfigurationPolicyId}", "connector": "arn:${Partition}:securityhub:${Region}:${Account}:connector/${ConnectorId}", "connectorv2": "arn:${Partition}:securityhub:${Region}:${Account}:connectorv2/${ConnectorV2Id}", "finding-aggregator": "arn:${Partition}:securityhub:${Region}:${Account}:finding-aggregator/${FindingAggregatorId}", "hub": "arn:${Partition}:securityhub:${Region}:${Account}:hub/default", "hubv2": "arn:${Partition}:securityhub:${Region}:${Account}:hubv2/${HubV2Id}", "product": "arn:${Partition}:securityhub:${Region}:${Account}:product/${Company}/${ProductId}"}, "servicediscovery": {"namespace": "arn:${Partition}:servicediscovery:${Region}:${Account}:namespace/${NamespaceId}", "service": "arn:${Partition}:servicediscovery:${Region}:${Account}:service/${ServiceId}"}, "servicequotas": {"quota": "arn:${Partition}:servicequotas:${Region}:${Account}:${ServiceCode}/${QuotaCode}"}, "signer": {"signing-job": "arn:${Partition}:signer:${Region}:${Account}:/signing-jobs/${JobId}", "signing-profile": "arn:${Partition}:signer:${Region}:${Account}:/signing-profiles/${ProfileName}"}, "sns": {"topic": "arn:${Partition}:sns:${Region}:${Account}:${TopicName}"}, "sqs": {"queue": "arn:${Partition}:sqs:${Region}:${Account}:${QueueName}"}, "ssm": {"association": "arn:${Partition}:ssm:${Region}:${Account}:association/${AssociationId}", "automation-definition": "arn:${Partition}:ssm:${Region}:${Account}:automation-definition/${AutomationDefinitionName}:${VersionId}", "automation-execution": "arn:${Partition}:ssm:${Region}:${Account}:automation-execution/${AutomationExecutionId}", "bucket": "arn:${Partition}:s3:::${BucketName}", "cloud-connector": "arn:${Partition}:ssm:${Region}:${Account}:cloud-connector/${CloudConnectorId}", "document": "arn:${Partition}:ssm:${Region}:${Account}:document/${DocumentName}", "iam-role": "arn:${Partition}:iam::${Account}:role/${RoleName}", "instance": "arn:${Partition}:ec2:${Region}:${Account}:instance/${InstanceId}", "maintenancewindow": "arn:${Partition}:ssm:${Region}:${Account}:maintenancewindow/${ResourceId}", "managed-instance": "arn:${Partition}:ssm:${Region}:${Account}:managed-instance/${InstanceId}", "managed-instance-inventory": "arn:${Partition}:ssm:${Region}:${Account}:managed-instance-inventory/${InstanceId}", "opsitem": "arn:${Partition}:ssm:${Region}:${Account}:opsitem/${ResourceId}", "opsitemgroup": "arn:${Partition}:ssm:${Region}:${Account}:opsitemgroup/default", "opsmetadata": "arn:${Partition}:ssm:${Region}:${Account}:opsmetadata/${ResourceId}", "parameter": "arn:${Partition}:ssm:${Region}:${Account}:parameter/${ParameterNameWithoutLeadingSlash}", "patchbaseline": "arn:${Partition}:ssm:${Region}:${Account}:patchbaseline/${PatchBaselineIdResourceId}", "resourcedatasync": "arn:${Partition}:ssm:${Region}:${Account}:resource-data-sync/${SyncName}", "servicesetting": "arn:${Partition}:ssm:${Region}:${Account}:servicesetting/${ResourceId}", "session": "arn:${Partition}:ssm:${Region}:${Account}:session/${SessionId}", "task": "arn:${Partition}:ecs:${Region}:${Account}:task/${TaskId}", "windowtarget": "arn:${Partition}:ssm:${Region}:${Account}:windowtarget/${WindowTargetId}", "windowtask": "arn:${Partition}:ssm:${Region}:${Account}:windowtask/${WindowTaskId}"}, "sso": {"Account": "arn:${Partition}:sso:::account/${AccountId}", "Application": "arn:${Partition}:sso::${Account}:application/${InstanceId}/${ApplicationId}", "ApplicationProvider": "arn:${Partition}:sso::aws:applicationProvider/${ApplicationProviderId}", "Instance": "arn:${Partition}:sso:::instance/${InstanceId}", "PermissionSet": "arn:${Partition}:sso:::permissionSet/${InstanceId}/${PermissionSetId}", "TrustedTokenIssuer": "arn:${Partition}:sso::${Account}:trustedTokenIssuer/${InstanceId}/${TrustedTokenIssuerId}"}, "states": {"activity": "arn:${Partition}:states:${Region}:${Account}:activity:${ActivityName}", "execution": "arn:${Partition}:states:${Region}:${Account}:execution:${StateMachineName}:${ExecutionId}", "express": "arn:${Partition}:states:${Region}:${Account}:express:${StateMachineName}:${ExecutionId}:${ExpressId}", "labelled execution": "arn:${Partition}:states:${Region}:${Account}:execution:${StateMachineName}/${MapRunLabel}:${ExecutionId}", "labelled express": "arn:${Partition}:states:${Region}:${Account}:express:${StateMachineName}/${MapRunLabel}:${ExecutionId}:${ExpressId}", "maprun": "arn:${Partition}:states:${Region}:${Account}:mapRun:${StateMachineName}/${MapRunLabel}:${MapRunId}", "statemachine": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}", "statemachinealias": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}:${StateMachineAliasName}", "statemachineversion": "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}:${StateMachineVersionId}"}, "sts": {"context-provider": "arn:${Partition}:iam::aws:contextProvider/${ContextProviderName}", "federated-user": "arn:${Partition}:sts::${Account}:federated-user/${FederatedUserName}", "role": "arn:${Partition}:iam::${Account}:role/${RoleNameWithPath}", "root-user": "arn:${Partition}:iam::${Account}:root", "self-session": "arn:${Partition}:sts::${Account}:self"}, "textract": {"adapter": "arn:${Partition}:textract:${Region}:${Account}:/adapters/${AdapterId}", "adapterversion": "arn:${Partition}:textract:${Region}:${Account}:/adapters/${AdapterId}/versions/${AdapterVersion}", "blueprint": "arn:${Partition}:textract:${Region}:${Account}:blueprint/${BlueprintId}", "job": "arn:${Partition}:textract:${Region}:${Account}:job/${JobId}", "project": "arn:${Partition}:textract:${Region}:${Account}:project/${ProjectId}"}, "timestream-influxdb": {"db-backup": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-backup/${DbBackupId}", "db-cluster": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-cluster/${DbClusterId}", "db-instance": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-instance/${DbInstanceIdentifier}", "db-parameter-group": "arn:${Partition}:timestream-influxdb:${Region}:${Account}:db-parameter-group/${DbParameterGroupIdentifier}"}, "translate": {"parallel-data": "arn:${Partition}:translate:${Region}:${Account}:parallel-data/${ResourceName}", "terminology": "arn:${Partition}:translate:${Region}:${Account}:terminology/${ResourceName}"}, "xray": {"group": "arn:${Partition}:xray:${Region}:${Account}:group/${GroupName}/${Id}", "sampling-rule": "arn:${Partition}:xray:${Region}:${Account}:sampling-rule/${SamplingRuleName}"}}, @@ -1561,7 +1561,72 @@ "dsql:TagResource": {"action": "dsql:TagResource", "types": ["Cluster", "Stream"], "resources": [{"types": ["Cluster", "Stream"], "arn": "resourceArn"}], "located": {"resourceArn": "{resourceArn}"}}, "dsql:UntagResource": {"action": "dsql:UntagResource", "types": ["Cluster", "Stream"], "resources": [{"types": ["Cluster", "Stream"], "arn": "resourceArn"}], "located": {"resourceArn": "{resourceArn}"}}, "dsql:UpdateCluster": {"action": "dsql:UpdateCluster", "types": ["Cluster"], "resources": [{"type": "Cluster", "fill": {"Identifier": "identifier"}}], "located": {"identifier": "{identifier}"}}, + "dynamodb:BatchExecuteStatement": {"action": "dynamodb:BatchExecuteStatement", "types": [], "actions": {"dynamodb:PartiQLSelect": ["index", "table"], "dynamodb:PartiQLInsert": ["table"], "dynamodb:PartiQLUpdate": ["table"], "dynamodb:PartiQLDelete": ["table"]}, "resources": [{"types": ["index", "table"], "statement": "Statements[].Statement", "verb": "SELECT", "names": {"TableName": "table", "IndexName": "index"}, "action": "dynamodb:PartiQLSelect"}, {"types": ["table"], "statement": "Statements[].Statement", "verb": "INSERT", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLInsert"}, {"types": ["table"], "statement": "Statements[].Statement", "verb": "UPDATE", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLUpdate"}, {"types": ["table"], "statement": "Statements[].Statement", "verb": "DELETE", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLDelete"}]}, + "dynamodb:BatchGetItem": {"action": "dynamodb:BatchGetItem", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "RequestItems{}"}}]}, + "dynamodb:BatchWriteItem": {"action": "dynamodb:BatchWriteItem", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "RequestItems{}"}}]}, + "dynamodb:CancelBulkOperation": {"action": "dynamodb:CancelBulkOperation", "types": ["bulk-operation"], "resources": [{"types": ["bulk-operation"], "arn": "BulkOperationArn"}]}, + "dynamodb:CreateBackup": {"action": "dynamodb:CreateBackup", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:CreateGlobalTable": {"action": "dynamodb:CreateGlobalTable", "types": ["global-table", "table"], "resources": [{"type": "global-table", "fill": {"GlobalTableName": "GlobalTableName"}}]}, + "dynamodb:CreateTable": {"action": "dynamodb:CreateTable", "types": ["table"], "resources": [{"types": ["table"], "arn": "GlobalTableSourceArn"}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DeleteBackup": {"action": "dynamodb:DeleteBackup", "types": ["backup"], "resources": [{"types": ["backup"], "arn": "BackupArn"}]}, + "dynamodb:DeleteItem": {"action": "dynamodb:DeleteItem", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DeleteResourcePolicy": {"action": "dynamodb:DeleteResourcePolicy", "types": ["stream", "table"], "resources": [{"types": ["stream", "table"], "arn": "ResourceArn"}]}, + "dynamodb:DeleteTable": {"action": "dynamodb:DeleteTable", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DescribeBackup": {"action": "dynamodb:DescribeBackup", "types": ["backup"], "resources": [{"types": ["backup"], "arn": "BackupArn"}]}, + "dynamodb:DescribeBulkOperation": {"action": "dynamodb:DescribeBulkOperation", "types": ["bulk-operation"], "resources": [{"types": ["bulk-operation"], "arn": "BulkOperationArn"}]}, + "dynamodb:DescribeContinuousBackups": {"action": "dynamodb:DescribeContinuousBackups", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DescribeContributorInsights": {"action": "dynamodb:DescribeContributorInsights", "types": ["index", "table"], "resources": [{"type": "index", "fill": {"IndexName": "IndexName", "TableName": "TableName"}, "unless": {"IndexName": [null]}}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DescribeEndpoints": {"action": "dynamodb:DescribeEndpoints", "types": [], "resources": []}, + "dynamodb:DescribeExport": {"action": "dynamodb:DescribeExport", "types": ["export"], "resources": [{"types": ["export"], "arn": "ExportArn"}]}, + "dynamodb:DescribeGlobalTable": {"action": "dynamodb:DescribeGlobalTable", "types": ["global-table"], "resources": [{"type": "global-table", "fill": {"GlobalTableName": "GlobalTableName"}}]}, + "dynamodb:DescribeGlobalTableSettings": {"action": "dynamodb:DescribeGlobalTableSettings", "types": ["global-table"], "resources": [{"type": "global-table", "fill": {"GlobalTableName": "GlobalTableName"}}]}, + "dynamodb:DescribeImport": {"action": "dynamodb:DescribeImport", "types": ["import"], "resources": [{"types": ["import"], "arn": "ImportArn"}]}, + "dynamodb:DescribeKinesisStreamingDestination": {"action": "dynamodb:DescribeKinesisStreamingDestination", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DescribeLimits": {"action": "dynamodb:DescribeLimits", "types": [], "resources": []}, + "dynamodb:DescribeStream": {"action": "dynamodb:DescribeStream", "types": ["stream"], "resources": [{"types": ["stream"], "arn": "StreamArn"}]}, + "dynamodb:DescribeTable": {"action": "dynamodb:DescribeTable", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DescribeTableReplicaAutoScaling": {"action": "dynamodb:DescribeTableReplicaAutoScaling", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DescribeTimeToLive": {"action": "dynamodb:DescribeTimeToLive", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:DisableKinesisStreamingDestination": {"action": "dynamodb:DisableKinesisStreamingDestination", "types": ["table"], "resources": [{"types": ["table"], "arn": "StreamArn"}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:EnableKinesisStreamingDestination": {"action": "dynamodb:EnableKinesisStreamingDestination", "types": ["table"], "resources": [{"types": ["table"], "arn": "StreamArn"}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:ExecuteStatement": {"action": "dynamodb:ExecuteStatement", "types": [], "actions": {"dynamodb:PartiQLSelect": ["index", "table"], "dynamodb:PartiQLInsert": ["table"], "dynamodb:PartiQLUpdate": ["table"], "dynamodb:PartiQLDelete": ["table"]}, "resources": [{"types": ["index", "table"], "statement": "Statement", "verb": "SELECT", "names": {"TableName": "table", "IndexName": "index"}, "action": "dynamodb:PartiQLSelect"}, {"types": ["table"], "statement": "Statement", "verb": "INSERT", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLInsert"}, {"types": ["table"], "statement": "Statement", "verb": "UPDATE", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLUpdate"}, {"types": ["table"], "statement": "Statement", "verb": "DELETE", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLDelete"}]}, + "dynamodb:ExecuteTransaction": {"action": "dynamodb:ExecuteTransaction", "types": [], "actions": {"dynamodb:PartiQLSelect": ["index", "table"], "dynamodb:PartiQLInsert": ["table"], "dynamodb:PartiQLUpdate": ["table"], "dynamodb:PartiQLDelete": ["table"]}, "resources": [{"types": ["index", "table"], "statement": "TransactStatements[].Statement", "verb": "SELECT", "names": {"TableName": "table", "IndexName": "index"}, "action": "dynamodb:PartiQLSelect"}, {"types": ["table"], "statement": "TransactStatements[].Statement", "verb": "INSERT", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLInsert"}, {"types": ["table"], "statement": "TransactStatements[].Statement", "verb": "UPDATE", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLUpdate"}, {"types": ["table"], "statement": "TransactStatements[].Statement", "verb": "DELETE", "names": {"TableName": "table"}, "action": "dynamodb:PartiQLDelete"}]}, + "dynamodb:ExportTableToPointInTime": {"action": "dynamodb:ExportTableToPointInTime", "types": ["table"], "resources": [{"types": ["table"], "arn": "TableArn"}]}, + "dynamodb:GetItem": {"action": "dynamodb:GetItem", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:GetRecords": {"action": "dynamodb:GetRecords", "types": ["stream"], "resources": []}, + "dynamodb:GetResourcePolicy": {"action": "dynamodb:GetResourcePolicy", "types": ["stream", "table"], "resources": [{"types": ["stream", "table"], "arn": "ResourceArn"}]}, + "dynamodb:GetShardIterator": {"action": "dynamodb:GetShardIterator", "types": ["stream"], "resources": [{"types": ["stream"], "arn": "StreamArn"}]}, + "dynamodb:ImportTable": {"action": "dynamodb:ImportTable", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableCreationParameters.TableName"}}]}, + "dynamodb:ListBackups": {"action": "dynamodb:ListBackups", "types": [], "resources": []}, + "dynamodb:ListBulkOperations": {"action": "dynamodb:ListBulkOperations", "types": [], "resources": []}, + "dynamodb:ListContributorInsights": {"action": "dynamodb:ListContributorInsights", "types": [], "resources": []}, + "dynamodb:ListExports": {"action": "dynamodb:ListExports", "types": ["table"], "resources": [{"types": ["table"], "arn": "TableArn"}, {"type": "table", "fill": {}, "when": {"TableArn": [null]}, "default": true}]}, + "dynamodb:ListGlobalTables": {"action": "dynamodb:ListGlobalTables", "types": [], "resources": []}, + "dynamodb:ListImports": {"action": "dynamodb:ListImports", "types": ["table"], "resources": [{"types": ["table"], "arn": "TableArn"}, {"type": "table", "fill": {}, "when": {"TableArn": [null]}, "default": true}]}, + "dynamodb:ListStreams": {"action": "dynamodb:ListStreams", "types": [], "resources": []}, "dynamodb:ListTables": {"action": "dynamodb:ListTables", "types": [], "resources": [{"type": "table", "fill": {}}]}, + "dynamodb:ListTagsOfResource": {"action": "dynamodb:ListTagsOfResource", "types": ["stream", "table"], "resources": [{"types": ["stream", "table"], "arn": "ResourceArn"}]}, + "dynamodb:PutItem": {"action": "dynamodb:PutItem", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:PutResourcePolicy": {"action": "dynamodb:PutResourcePolicy", "types": ["stream", "table"], "resources": [{"types": ["stream", "table"], "arn": "ResourceArn"}]}, + "dynamodb:Query": {"action": "dynamodb:Query", "types": ["index", "table"], "resources": [{"type": "index", "fill": {"IndexName": "IndexName", "TableName": "TableName"}, "unless": {"IndexName": [null]}}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:RestoreTableFromBackup": {"action": "dynamodb:RestoreTableFromBackup", "types": ["backup", "table"], "resources": [{"types": ["backup", "table"], "arn": "BackupArn"}, {"type": "table", "fill": {"TableName": "TargetTableName"}}]}, + "dynamodb:RestoreTableToPointInTime": {"action": "dynamodb:RestoreTableToPointInTime", "types": ["table"], "resources": [{"types": ["table"], "arn": "SourceTableArn"}, {"type": "table", "fill": {"TableName": "SourceTableName"}}]}, + "dynamodb:Scan": {"action": "dynamodb:Scan", "types": ["index", "table"], "resources": [{"type": "index", "fill": {"IndexName": "IndexName", "TableName": "TableName"}, "unless": {"IndexName": [null]}}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:SearchVectors": {"action": "dynamodb:SearchVectors", "types": ["index", "table"], "resources": [{"type": "index", "fill": {"IndexName": "IndexName", "TableName": "TableName"}}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:StartBulkPutItems": {"action": "dynamodb:StartBulkPutItems", "types": [], "resources": []}, + "dynamodb:TagResource": {"action": "dynamodb:TagResource", "types": ["stream", "table"], "resources": [{"types": ["stream", "table"], "arn": "ResourceArn"}]}, + "dynamodb:TransactGetItems": {"action": "dynamodb:GetItem", "types": ["table"], "actions": {"dynamodb:GetItem": ["table"]}, "resources": [{"type": "table", "fill": {"TableName": "TransactItems[].Get.TableName"}, "action": "dynamodb:GetItem"}]}, + "dynamodb:TransactWriteItems": {"action": "dynamodb:TransactWriteItems", "types": [], "actions": {"dynamodb:ConditionCheckItem": ["table"], "dynamodb:PutItem": ["table"], "dynamodb:DeleteItem": ["table"], "dynamodb:UpdateItem": ["table"]}, "resources": [{"type": "table", "fill": {"TableName": "TransactItems[].ConditionCheck.TableName"}, "action": "dynamodb:ConditionCheckItem"}, {"type": "table", "fill": {"TableName": "TransactItems[].Put.TableName"}, "action": "dynamodb:PutItem"}, {"type": "table", "fill": {"TableName": "TransactItems[].Delete.TableName"}, "action": "dynamodb:DeleteItem"}, {"type": "table", "fill": {"TableName": "TransactItems[].Update.TableName"}, "action": "dynamodb:UpdateItem"}]}, + "dynamodb:UntagResource": {"action": "dynamodb:UntagResource", "types": ["stream", "table"], "resources": [{"types": ["stream", "table"], "arn": "ResourceArn"}]}, + "dynamodb:UpdateContinuousBackups": {"action": "dynamodb:UpdateContinuousBackups", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:UpdateContributorInsights": {"action": "dynamodb:UpdateContributorInsights", "types": ["index", "table"], "resources": [{"type": "index", "fill": {"IndexName": "IndexName", "TableName": "TableName"}, "unless": {"IndexName": [null]}}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:UpdateGlobalTable": {"action": "dynamodb:UpdateGlobalTable", "types": ["global-table", "table"], "resources": [{"type": "global-table", "fill": {"GlobalTableName": "GlobalTableName"}}]}, + "dynamodb:UpdateGlobalTableSettings": {"action": "dynamodb:UpdateGlobalTableSettings", "types": ["global-table", "table"], "resources": [{"types": ["global-table", "table"], "arn": "GlobalTableProvisionedWriteCapacityAutoScalingSettingsUpdate.AutoScalingRoleArn"}, {"type": "global-table", "fill": {"GlobalTableName": "GlobalTableName"}}]}, + "dynamodb:UpdateItem": {"action": "dynamodb:UpdateItem", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:UpdateKinesisStreamingDestination": {"action": "dynamodb:UpdateKinesisStreamingDestination", "types": ["table"], "resources": [{"types": ["table"], "arn": "StreamArn"}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:UpdateTable": {"action": "dynamodb:UpdateTable", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:UpdateTableReplicaAutoScaling": {"action": "dynamodb:UpdateTableReplicaAutoScaling", "types": ["table"], "resources": [{"types": ["table"], "arn": "ProvisionedWriteCapacityAutoScalingUpdate.AutoScalingRoleArn"}, {"type": "table", "fill": {"TableName": "TableName"}}]}, + "dynamodb:UpdateTimeToLive": {"action": "dynamodb:UpdateTimeToLive", "types": ["table"], "resources": [{"type": "table", "fill": {"TableName": "TableName"}}]}, "ec2-instance-connect:SendSSHPublicKey": {"action": "ec2-instance-connect:SendSSHPublicKey", "types": ["instance"], "resources": [{"type": "instance", "fill": {"InstanceId": "InstanceId"}}]}, "ec2-instance-connect:SendSerialConsoleSSHPublicKey": {"action": "ec2-instance-connect:SendSerialConsoleSSHPublicKey", "types": ["instance"], "resources": [{"type": "instance", "fill": {"InstanceId": "InstanceId"}}]}, "ec2:AcceptAddressTransfer": {"action": "ec2:AcceptAddressTransfer", "types": ["elastic-ip"], "resources": []}, diff --git a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java index 84cb73618a..7a30272f10 100644 --- a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java @@ -952,8 +952,8 @@ class IamConditionContextResolverTest { + "\"Key\":{\"PK\":{\"S\":\"USER_alice\"}}," + extra + "}}]}"); JsonNode original = body.deepCopy(); when(request.getProperty("floci.bufferedJsonBody")).thenReturn(body); - Map> context = resolver.dynamoDbTransactionItems("dynamodb:TransactGetItems", - request, "us-east-1", "000000000000").getFirst().context(); + Map> context = resolver.resolvePart("dynamodb", "dynamodb:GetItem", + "dynamodb:TransactGetItems", request, body.path("TransactItems").path(0).path("Get"), "us-east-1"); assertEquals(List.of("ALL_ATTRIBUTES"), context.get("dynamodb:Select")); assertEquals(List.of("PK"), context.get("dynamodb:Attributes")); assertEquals(List.of("USER_alice"), context.get("dynamodb:LeadingKeys")); diff --git a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java index 31d26a552b..be29afbc27 100644 --- a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java @@ -234,13 +234,11 @@ class RequestResourceMembersTest { assertTrue(table.namespaces().contains("lambda")); assertFalse(table.handBuilt().contains("lambda")); assertFalse(table.handBuilt().contains("logs")); - assertEquals(Set.of("dynamodb"), table.namespaces().stream().filter(table.handBuilt()::contains) + assertEquals(Set.of(), table.namespaces().stream().filter(table.handBuilt()::contains) .collect(Collectors.toSet())); - // What AWS was measured to check where the Service Reference lists no resource type (MEASURED). - assertEquals(Set.of("dynamodb:ListTables"), table.operations().keySet().stream() + assertEquals(Set.of(), table.operations().keySet().stream() .filter(operation -> table.handBuilt().contains(operation.substring(0, operation.indexOf(':')))) - .collect(Collectors.toSet()), - "only what MEASURED gives is read in a hand-built namespace"); + .collect(Collectors.toSet()), "nothing is read in a hand-built namespace"); assertTrue(table.namespaces().stream().noneMatch(table.notCovered()::contains)); assertTrue(table.operations().containsKey("rds:CreateDBParameterGroup")); assertTrue(table.operations().containsKey("rds:CreateDBProxy")); @@ -371,9 +369,10 @@ class RequestResourceMembersTest { + "{\"resources\":[],\"creates\":[{\"type\":\"part\",\"parent\":\"thing\",\"arn\":\"ThingArn\"}]}}}"), part); } - // A member past one structure, or filling a variable from a list in a list. + // An ARN member past one structure, a member filling a variable past two, or one filling it from a list in a + // list. assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"types\":[\"thing\"],\"arn\":\"A[].B.ThingArn\"}"))); - for (String bad : List.of("A.Names[]", "A[].Names[]", "A[].B.Name")) { + for (String bad : List.of("A.Names[]", "A[].Names[]", "A[].B.C.Name")) { assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"" + bad + "\"}}")), bad); } @@ -782,7 +781,9 @@ class RequestResourceMembersTest { /** The value at the member's path in a body: in its list's first element, and in its field's structure. */ private static void put(ObjectNode body, Member member, String value) { if (member.field() == null) { - if (member.list()) { + if (member.map()) { + body.putObject(member.name()).putObject(value); + } else if (member.list()) { body.putArray(member.name()).add(value); } else { body.put(member.name(), value); diff --git a/src/test/java/io/floci/aws/core/common/RequestResourcesTest.java b/src/test/java/io/floci/aws/core/common/RequestResourcesTest.java index e022ec5ca6..530281406b 100644 --- a/src/test/java/io/floci/aws/core/common/RequestResourcesTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestResourcesTest.java @@ -280,7 +280,8 @@ class RequestResourcesTest { @Test void listTablesIsCheckedOnTheTableCollectionAwsWasMeasuredToCheck() { assertTrue(RequestResources.reads("dynamodb:ListTables")); - assertFalse(RequestResources.reads("dynamodb:DescribeLimits")); + assertEquals(List.of(), RequestResources.of("dynamodb:DescribeLimits", json("{}"), "aws-us-gov", + "us-gov-west-1", "111122223333")); for (String body : List.of("{}", "{\"TableName\":\"ignored\",\"ExclusiveStartTableName\":\"cursor\"}")) { assertEquals(List.of("arn:aws-us-gov:dynamodb:us-gov-west-1:111122223333:table/*"), RequestResources.of("dynamodb:ListTables", json(body), "aws-us-gov", "us-gov-west-1", diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeysTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeysTest.java index 0b17f3711a..45899e70cf 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeysTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbConditionKeysTest.java @@ -482,28 +482,11 @@ class DynamoDbConditionKeysTest { assertTrue(result.attributes().contains("inStock"), result.attributes().toString()); } - @ParameterizedTest - @CsvSource({"BatchExecuteStatement, Statements", "ExecuteTransaction, TransactStatements"}) - void partiQLStatementRequestsFollowTheRecordedMemberPaths(String operation, String member) { - JsonNode body = json("{\"" + member + "\":[{\"Statement\":\"SELECT * FROM a\"}," - + "{\"Statement\":\"DELETE FROM b WHERE PK = ?\",\"Parameters\":[{\"S\":\"k\"}]}," - + "\"not-an-object\"]}"); - - List requests = DynamoDbConditionKeys.partiQLStatementRequests(operation, body); - - assertEquals(3, requests.size()); - assertEquals("SELECT * FROM a", DynamoDbConditionKeys.partiQLStatement(requests.get(0))); - assertEquals("DELETE FROM b WHERE PK = ?", DynamoDbConditionKeys.partiQLStatement(requests.get(1))); - assertEquals("k", requests.get(1).path("Parameters").path(0).path("S").asText()); - assertNull(DynamoDbConditionKeys.partiQLStatement(requests.get(2))); - } - @Test - void partiQLStatementRequestsIgnoreTheOtherOperationsMember() { - JsonNode body = json("{\"Statements\":[{\"Statement\":\"SELECT * FROM a\"}]}"); - - assertTrue(DynamoDbConditionKeys.partiQLStatementRequests("ExecuteTransaction", body).isEmpty()); - assertTrue(DynamoDbConditionKeys.partiQLStatementRequests("BatchExecuteStatement", null).isEmpty()); + void partiQLStatementReadsTheTextOfOneStatementRequest() { + assertEquals("DELETE FROM b WHERE PK = ?", DynamoDbConditionKeys.partiQLStatement( + json("{\"Statement\":\"DELETE FROM b WHERE PK = ?\",\"Parameters\":[{\"S\":\"k\"}]}"))); assertNull(DynamoDbConditionKeys.partiQLStatement(json("{\"Statement\":1}"))); + assertNull(DynamoDbConditionKeys.partiQLStatement(json("\"not-an-object\""))); } } diff --git a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParserTest.java b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParserTest.java index 87954581aa..3b52ca54d1 100644 --- a/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParserTest.java +++ b/src/test/java/io/floci/aws/services/dynamodb/DynamoDbPartiQLParserTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.params.provider.ValueSource; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; +import java.util.Optional; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -205,7 +206,32 @@ class DynamoDbPartiQLParserTest { assertEquals(2, update.sets().size()); assertEquals("b", update.removes().getFirst().root()); assertEquals(DynamoDbPartiQLParser.Returning.ALL_NEW, update.returning()); - assertEquals("dynamodb:PartiQLUpdate", DynamoDbPartiQLParser.iamAction("FROM \"t\" WHERE pk = 'p' SET c = 1")); + assertEquals(Optional.of(new DynamoDbPartiQLParser.StatementTarget("UPDATE", "t", null)), + DynamoDbPartiQLParser.target("FROM \"t\" WHERE pk = 'p' SET c = 1")); + } + + /** + * A statement's verb and the table and index it names, as IAM checks it, an EXISTS statement's those of the SELECT + * it evaluates; none for a statement of another verb. + */ + @Test + void aStatementsTargetIsItsVerbTableAndIndex() { + assertEquals(Optional.of(new DynamoDbPartiQLParser.StatementTarget("SELECT", "t", "byName")), + DynamoDbPartiQLParser.target("SELECT * FROM \"t\".\"byName\" WHERE pk = 'p'")); + assertEquals(Optional.of(new DynamoDbPartiQLParser.StatementTarget("SELECT", "t", "byName")), + DynamoDbPartiQLParser.target("SELECT * FROM \"t\".\"byName\" WHERE pk = ?")); + assertEquals(Optional.of(new DynamoDbPartiQLParser.StatementTarget("DELETE", "t", null)), + DynamoDbPartiQLParser.target("DELETE FROM \"t\" WHERE pk = ? AND sk = ?")); + assertEquals(Optional.of(new DynamoDbPartiQLParser.StatementTarget("SELECT", "t", null)), + DynamoDbPartiQLParser.target("EXISTS(SELECT * FROM \"t\" WHERE pk = 'p' AND v = 1)")); + assertEquals(Optional.of(new DynamoDbPartiQLParser.StatementTarget("SELECT", "t", null)), + DynamoDbPartiQLParser.target("SELECT * FROM \"t\" WHERE pk = 'p'")); + assertEquals(Optional.of(new DynamoDbPartiQLParser.StatementTarget("INSERT", "t", null)), + DynamoDbPartiQLParser.target("INSERT INTO \"t\" VALUE {'pk': 'p'}")); + assertEquals(Optional.of(new DynamoDbPartiQLParser.StatementTarget("DELETE", "t", null)), + DynamoDbPartiQLParser.target("DELETE FROM \"t\" WHERE pk = 'p'")); + assertEquals(Optional.empty(), DynamoDbPartiQLParser.target("not a statement \"")); + assertEquals(Optional.empty(), DynamoDbPartiQLParser.target(null)); } @Test diff --git a/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java index 2b0c4f118d..10be0183c1 100644 --- a/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java +++ b/src/test/java/io/floci/aws/services/iam/ResourceArnBuilderTest.java @@ -8,6 +8,7 @@ import io.floci.aws.core.common.ProtocolClaim; import io.floci.aws.core.common.RegionResolver; import io.floci.aws.core.common.RequestContext; import io.floci.aws.core.common.RequestPathLabels; +import io.floci.aws.core.common.RequestResources; import io.floci.aws.core.common.StoredResourceArns; import io.floci.aws.core.common.WireProtocol; import io.floci.aws.core.storage.AccountAwareStorageBackend; @@ -15,6 +16,8 @@ import io.floci.aws.core.storage.InMemoryStorage; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsDeliveryService; import io.floci.aws.services.cloudwatch.logs.CloudWatchLogsStoredResourceArns; import io.floci.aws.services.cloudwatch.logs.model.Delivery; +import io.floci.aws.services.dynamodb.DynamoDbStoredResourceArns; +import io.floci.aws.services.dynamodb.backend.DynamoDbTableAccess; import io.floci.aws.services.eks.EksService; import io.floci.aws.services.eks.EksStoredResourceArns; import io.floci.aws.services.iam.model.AccessKey; @@ -55,6 +58,7 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -1135,183 +1139,148 @@ class ResourceArnBuilderTest { ctx, "us-east-1", ACCOUNT, "aws")); } + private static final String DDB = "arn:aws:dynamodb:us-east-1:000000000000:table/"; + + /** The resources a DynamoDB request is checked on, as the table reads {@code operation}. */ + private List dynamoDb(String operation) { + return builder.buildResources("dynamodb", "dynamodb:" + operation, ctx, "us-east-1", ACCOUNT, "aws"); + } + + /** The checks of a DynamoDB request checked by its parts, each statement parsed as DynamoDB parses it. */ + private List dynamoDbTargets(String operation) { + return reading(new DynamoDbStoredResourceArns(mock(DynamoDbTableAccess.class))) + .targets("dynamodb", "dynamodb:" + operation, ctx, "us-east-1", ACCOUNT, "aws"); + } + @Test - void dynamoDbBuildsArnFromShortTableName() { + void dynamoDbChecksTheTableItsRequestNames() { setJsonBody("{\"TableName\":\"FgacTable\"}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable", arn); + assertEquals(List.of(DDB + "FgacTable"), dynamoDb("GetItem")); + // A bare name that merely looks ARN-ish is still a name, not an ARN. + setJsonBody("{\"TableName\":\"arn:aws:dynamodb:us-east-1\"}"); + assertEquals(List.of(DDB + "arn:aws:dynamodb:us-east-1"), dynamoDb("GetItem")); + setJsonBody("{\"TableName\":\"" + DDB + "FgacTable\"}"); + assertEquals(List.of(DDB + "FgacTable"), dynamoDb("GetItem")); + setJsonBody("{\"TableCreationParameters\":{\"TableName\":\"ImportTarget\"},\"InputFormat\":\"DYNAMODB_JSON\"}"); + assertEquals(List.of(DDB + "ImportTarget"), dynamoDb("ImportTable")); + setJsonBody("{}"); + assertEquals(List.of("*"), dynamoDb("GetItem")); } /** - * Pass-through used to be a {@code startsWith("arn:aws:dynamodb:")} probe, so a table ARN from - * any other partition was not recognised as an ARN at all and got rebuilt as - * {@code table/arn:aws-cn:dynamodb:...}, a resource name that matches no policy. + * A table ARN of any partition is checked as given, and as the caller's table of that name, which DynamoDB acts on: + * a {@code startsWith("arn:aws:dynamodb:")} probe once rebuilt another partition's ARN as {@code table/arn:...}. */ @Test - void dynamoDbReturnsExactArnForAnyPartition() { - for (String fullArn : List.of( - "arn:aws-us-gov:dynamodb:us-gov-west-1:000000000000:table/FgacTable", + void dynamoDbChecksATableArnOfAnyPartitionAsGiven() { + for (String fullArn : List.of("arn:aws-us-gov:dynamodb:us-gov-west-1:000000000000:table/FgacTable", "arn:aws-cn:dynamodb:cn-north-1:000000000000:table/FgacTable")) { setJsonBody("{\"TableName\":\"" + fullArn + "\"}"); - assertEquals(fullArn, builder.build("dynamodb", ctx, "us-east-1", "000000000000")); + List checked = dynamoDb("GetItem"); + assertEquals(fullArn, checked.getFirst()); + assertTrue(checked.contains(DDB + "FgacTable"), checked.toString()); } } - /** A bare name that merely looks ARN-ish is still a name, not an ARN. */ @Test - void dynamoDbTreatsAnIncompleteArnAsATableName() { - setJsonBody("{\"TableName\":\"arn:aws:dynamodb:us-east-1\"}"); - assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/arn:aws:dynamodb:us-east-1", - builder.build("dynamodb", ctx, "us-east-1", "000000000000")); + void dynamoDbChecksTheResourceAnArnMemberHolds() { + setJsonBody("{\"ResourceArn\":\"" + DDB + "FgacTable\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"dev\"}]}"); + assertEquals(List.of(DDB + "FgacTable"), dynamoDb("TagResource")); + setJsonBody("{\"TableArn\":\"" + DDB + "ExportTable\",\"S3Bucket\":\"my-bucket\"}"); + assertEquals(List.of(DDB + "ExportTable"), dynamoDb("ExportTableToPointInTime")); + String stream = DDB + "FgacTable/stream/2026-09-01T00:00:00.000"; + setJsonBody("{\"StreamArn\":\"" + stream + "\"}"); + assertEquals(List.of(stream), dynamoDb("DescribeStream")); + String export = DDB + "FgacTable/export/01693526400000-abcd"; + setJsonBody("{\"ExportArn\":\"" + export + "\"}"); + assertEquals(List.of(export), dynamoDb("DescribeExport")); } @Test - void dynamoDbReturnsExactArnIfTableNameIsAlreadyArn() { - String fullArn = "arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable"; - setJsonBody("{\"TableName\":\"" + fullArn + "\"}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(fullArn, arn); - } - - @Test - void dynamoDbBuildsArnFromResourceArn() { - String tagArn = "arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable"; - setJsonBody("{\"ResourceArn\":\"" + tagArn + "\",\"Tags\":[{\"Key\":\"env\",\"Value\":\"dev\"}]}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(tagArn, arn); - } - - @Test - void dynamoDbBuildsArnFromTableArn() { - String exportArn = "arn:aws:dynamodb:us-east-1:000000000000:table/ExportTable"; - setJsonBody("{\"TableArn\":\"" + exportArn + "\",\"S3Bucket\":\"my-bucket\"}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(exportArn, arn); - } - - @Test - void dynamoDbBuildsArnFromStreamArn() { - String streamArn = "arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable/stream/2026-09-01T00:00:00.000"; - setJsonBody("{\"StreamArn\":\"" + streamArn + "\"}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(streamArn, arn); - } - - @Test - void dynamoDbBuildsArnFromExportArn() { - String exportArn = "arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable/export/01693526400000-abcd"; - setJsonBody("{\"ExportArn\":\"" + exportArn + "\"}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(exportArn, arn); - } - - @Test - void dynamoDbBuildsArnFromTheSourceOfAPointInTimeRestore() { + void dynamoDbChecksThePointInTimeRestoreOnItsSourceTable() { setJsonBody("{\"SourceTableName\":\"Music\",\"TargetTableName\":\"MusicCopy\"}"); - assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/Music", - builder.build("dynamodb", ctx, "us-east-1", "000000000000")); - String sourceArn = "arn:aws:dynamodb:eu-west-2:000000000000:table/Music"; - setJsonBody("{\"SourceTableArn\":\"" + sourceArn + "\",\"TargetTableName\":\"MusicCopy\"}"); - assertEquals(sourceArn, builder.build("dynamodb", ctx, "us-east-1", "000000000000")); + assertEquals(List.of(DDB + "Music"), dynamoDb("RestoreTableToPointInTime")); + String source = "arn:aws:dynamodb:eu-west-2:000000000000:table/Music"; + setJsonBody("{\"SourceTableArn\":\"" + source + "\",\"TargetTableName\":\"MusicCopy\"}"); + assertEquals(source, dynamoDb("RestoreTableToPointInTime").getFirst()); } + /** A batch's tables are the keys of its RequestItems, which botocore keys by the shape a table's name has. */ @Test - void dynamoDbBuildsArnFromSingleTableBatchRequest() { + void dynamoDbChecksABatchOnEveryTableItsRequestItemsKey() { setJsonBody("{\"RequestItems\":{\"MyTable\":{\"Keys\":[]}}}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/MyTable", arn); - } - - @Test - void dynamoDbBuildsArnsFromMultiTableBatchRequest() { + assertEquals(List.of(DDB + "MyTable"), dynamoDb("BatchGetItem")); setJsonBody("{\"RequestItems\":{\"TableA\":{\"Keys\":[]},\"TableB\":{\"Keys\":[]}}}"); - List arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of( - "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", - "arn:aws:dynamodb:us-east-1:000000000000:table/TableB" - ), arns); + assertEquals(List.of(DDB + "TableA", DDB + "TableB"), dynamoDb("BatchGetItem")); + assertEquals(List.of(DDB + "TableA", DDB + "TableB"), dynamoDb("BatchWriteItem")); } + /** + * Each of a transaction's items is checked as the action the developer guide gives its kind, on its own table, + * with the item it comes from: {@code Put} as {@code dynamodb:PutItem}, {@code ConditionCheck} as + * {@code dynamodb:ConditionCheckItem}, {@code Get} as {@code dynamodb:GetItem}; the transaction's own action never. + */ @Test - void dynamoDbBuildsArnFromSingleTableTransactRequest() { - setJsonBody("{\"TransactItems\":[{\"Put\":{\"TableName\":\"MyTable\"}},{\"Delete\":{\"TableName\":\"MyTable\"}}]}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/MyTable", arn); + void dynamoDbChecksEachTransactionItemAsItsKindsAction() { + setJsonBody("{\"TransactItems\":[{\"Put\":{\"TableName\":\"TableA\"}}," + + "{\"ConditionCheck\":{\"TableName\":\"TableB\"}},{\"Delete\":{\"TableName\":\"TableA\"}}]}"); + assertTrue(RequestResources.checkedByParts("dynamodb:TransactWriteItems")); + List targets = dynamoDbTargets("TransactWriteItems"); + assertEquals(List.of("dynamodb:ConditionCheckItem", "dynamodb:PutItem", "dynamodb:DeleteItem"), + targets.stream().map(RequestResources.Target::action).toList()); + assertEquals(List.of(List.of(DDB + "TableB"), List.of(DDB + "TableA"), List.of(DDB + "TableA")), + targets.stream().map(RequestResources.Target::resources).toList()); + assertEquals("TableB", targets.getFirst().element().path("TableName").asText()); + setJsonBody("{\"TransactItems\":[{\"Get\":{\"TableName\":\"MyTable\"}}]}"); + assertEquals(List.of(new RequestResources.Target("dynamodb:GetItem", List.of(DDB + "MyTable"), + dynamoDbTargets("TransactGetItems").getFirst().element())), + dynamoDbTargets("TransactGetItems")); + assertEquals(List.of(), dynamoDbTargets("GetItem")); } + /** + * A PartiQL statement is checked as the action the developer guide gives its verb, on the table or index it names, + * as DynamoDB parses it, a quoted keyword or name included; each statement of a batch or transaction apart. + */ @Test - void dynamoDbBuildsArnsFromMultiTableTransactRequest() { - setJsonBody("{\"TransactItems\":[{\"Put\":{\"TableName\":\"TableA\"}},{\"Delete\":{\"TableName\":\"TableB\"}},{\"Get\":{\"TableName\":\"TableA\"}}]}"); - List arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of( - "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", - "arn:aws:dynamodb:us-east-1:000000000000:table/TableB" - ), arns); - } - - @Test - void dynamoDbBuildsArnFromPartiQLStatement() { - setJsonBody("{\"Statement\":\"SELECT * FROM \\\"UsersTable\\\" WHERE id = '1'\"}"); - List arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/UsersTable"), arns); - - setJsonBody("{\"Statement\":\"INSERT INTO OrdersTable VALUE {'id': '1'}\"}"); - arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/OrdersTable"), arns); - - setJsonBody("{\"Statement\":\"UPDATE \\\"ProductsTable\\\" SET price=10 WHERE id='1'\"}"); - arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/ProductsTable"), arns); - - setJsonBody("{\"Statement\":\"DELETE FROM \\\"LogsTable\\\" WHERE id='1'\"}"); - arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/LogsTable"), arns); - - setJsonBody("{\"Statement\":\"SELECT * FROM \\\"Table With Spaces & Special:Chars\\\" WHERE id = '1'\"}"); - arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/Table With Spaces & Special:Chars"), arns); - - setJsonBody("{\"Statement\":\"SELECT * FROM 'Table.With.Single.Quotes#1' WHERE id = '1'\"}"); - arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/Table.With.Single.Quotes#1"), arns); - - setJsonBody("{\"Statement\":\"SELECT \\\"FROM TableEvil\\\" FROM \\\"TableA\\\" WHERE pk = 1\"}"); - arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/TableA"), arns); - } - - @Test - void dynamoDbBuildsArnsFromPartiQLBatchStatements() { - setJsonBody("{\"Statements\":[{\"Statement\":\"SELECT * FROM \\\"TableA\\\" WHERE id = '1'\"},{\"Statement\":\"SELECT * FROM TableB WHERE id = '2'\"}]}"); - List arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of( - "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", - "arn:aws:dynamodb:us-east-1:000000000000:table/TableB" - ), arns); - } - - @Test - void dynamoDbBuildsArnsFromPartiQLTransactStatements() { - setJsonBody("{\"TransactStatements\":[{\"Statement\":\"INSERT INTO \\\"TableA\\\" VALUE {'id': '1'}\"},{\"Statement\":\"UPDATE \\\"TableB\\\" SET x=1 WHERE id='2'\"}]}"); - List arns = builder.buildResources("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals(List.of( - "arn:aws:dynamodb:us-east-1:000000000000:table/TableA", - "arn:aws:dynamodb:us-east-1:000000000000:table/TableB" - ), arns); - } - - @Test - void dynamoDbBuildsArnFromTableCreationParameters() { - setJsonBody("{\"TableCreationParameters\":{\"TableName\":\"ImportTarget\"},\"InputFormat\":\"DYNAMODB_JSON\"}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/ImportTarget", arn); - } - - @Test - void dynamoDbReturnsWildcardWhenNoTableSpecified() { - setJsonBody("{}"); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals("*", arn); + void dynamoDbChecksEachPartiQLStatementAsItsVerbsAction() { + Map statements = new LinkedHashMap<>(); + statements.put("SELECT * FROM \\\"UsersTable\\\" WHERE id = '1'", "dynamodb:PartiQLSelect UsersTable"); + statements.put("INSERT INTO OrdersTable VALUE {'id': '1'}", "dynamodb:PartiQLInsert OrdersTable"); + statements.put("UPDATE \\\"ProductsTable\\\" SET price=10 WHERE id='1'", + "dynamodb:PartiQLUpdate ProductsTable"); + statements.put("DELETE FROM \\\"LogsTable\\\" WHERE id='1'", "dynamodb:PartiQLDelete LogsTable"); + statements.put("SELECT * FROM \\\"Table With Spaces & Special:Chars\\\" WHERE id = '1'", + "dynamodb:PartiQLSelect Table With Spaces & Special:Chars"); + statements.put("SELECT \\\"FROM TableEvil\\\" FROM \\\"TableA\\\" WHERE pk = 1", + "dynamodb:PartiQLSelect TableA"); + statements.forEach((statement, expected) -> { + setJsonBody("{\"Statement\":\"" + statement + "\"}"); + List targets = dynamoDbTargets("ExecuteStatement"); + String[] parts = expected.split(" ", 2); + assertEquals(List.of(new RequestResources.Target(parts[0], List.of(DDB + parts[1]), null)), targets, + statement); + }); + setJsonBody("{\"Statement\":\"SELECT * FROM \\\"Music\\\".\\\"byArtist\\\" WHERE a = 'x'\"}"); + assertEquals(List.of(new RequestResources.Target("dynamodb:PartiQLSelect", + List.of(DDB + "Music/index/byArtist"), null)), dynamoDbTargets("ExecuteStatement")); + setJsonBody("{\"Statements\":[{\"Statement\":\"SELECT * FROM \\\"TableA\\\" WHERE id = '1'\"}," + + "{\"Statement\":\"DELETE FROM TableB WHERE id = '2'\"}]}"); + List batch = dynamoDbTargets("BatchExecuteStatement"); + assertEquals(List.of("dynamodb:PartiQLSelect TableA", "dynamodb:PartiQLDelete TableB"), batch.stream() + .map(target -> target.action() + " " + target.resources().getFirst().substring(DDB.length())).toList()); + assertTrue(batch.getFirst().element().path("Statement").asText().contains("TableA")); + setJsonBody("{\"TransactStatements\":[{\"Statement\":\"INSERT INTO \\\"TableA\\\" VALUE {'id': '1'}\"}," + + "{\"Statement\":\"UPDATE \\\"TableB\\\" SET x=1 WHERE id='2'\"}]}"); + assertEquals(List.of("dynamodb:PartiQLInsert", "dynamodb:PartiQLUpdate"), + dynamoDbTargets("ExecuteTransaction").stream().map(RequestResources.Target::action).sorted().toList()); + setJsonBody("{\"TransactStatements\":[{\"Statement\":\"INSERT INTO \\\"TableA\\\" VALUE {'id': '1'}\"}," + + "{\"Statement\":\"EXISTS(SELECT * FROM \\\"TableB\\\" WHERE id = ? AND x = 1)\"}]}"); + assertEquals(List.of("dynamodb:PartiQLSelect TableB", "dynamodb:PartiQLInsert TableA"), + dynamoDbTargets("ExecuteTransaction").stream().map(target -> target.action() + " " + + target.resources().getFirst().substring(DDB.length())).toList()); + setJsonBody("{\"Statements\":[{\"Statement\":\"-- nothing\"}]}"); + assertEquals(List.of(), dynamoDbTargets("BatchExecuteStatement")); } @Test @@ -1319,8 +1288,7 @@ class ResourceArnBuilderTest { String json = "{\"TableName\":\"FgacTable\",\"Item\":{\"PK\":{\"S\":\"USER_1\"}}}"; setJsonBody(json); - String arn = builder.build("dynamodb", ctx, "us-east-1", "000000000000"); - assertEquals("arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable", arn); + assertEquals(List.of(DDB + "FgacTable"), dynamoDb("PutItem")); InputStream entityStream = ctx.getEntityStream(); assertNotNull(entityStream); @@ -1611,14 +1579,20 @@ class ResourceArnBuilderTest { ResourceArnBuilder backed = backedBy(kms); setJsonBody("{\"CiphertextBlob\":\"" + encoded + "\",\"DestinationKeyId\":\"alias/destination\"}"); - assertEquals(Map.of("kms:ReEncryptFrom", List.of(KMS_OTHER_KEY_ARN), "kms:ReEncryptTo", List.of(KMS_KEY_ARN)), - backed.checkedAs("kms", "kms:ReEncrypt", ctx, "us-east-1", ACCOUNT, "aws")); + assertEquals(List.of(new RequestResources.Target("kms:ReEncryptFrom", List.of(KMS_OTHER_KEY_ARN), null), + new RequestResources.Target("kms:ReEncryptTo", List.of(KMS_KEY_ARN), null)), + backed.targets("kms", "kms:ReEncrypt", ctx, "us-east-1", ACCOUNT, "aws")); setJsonBody("{\"CiphertextBlob\":\"" + encoded + "\",\"SourceKeyId\":\"alias/source\"," + "\"DestinationKeyId\":\"alias/destination\"}"); - assertEquals(List.of("kms:ReEncryptFrom", "kms:ReEncryptTo"), - List.copyOf(backed.checkedAs("kms", "kms:ReEncrypt", ctx, "us-east-1", ACCOUNT, "aws").keySet())); + assertEquals(List.of(new RequestResources.Target("kms:ReEncryptFrom", List.of(KMS_OTHER_KEY_ARN), null), + new RequestResources.Target("kms:ReEncryptTo", List.of(KMS_KEY_ARN), null)), + backed.targets("kms", "kms:ReEncrypt", ctx, "us-east-1", ACCOUNT, "aws")); + // A source no member names, nor the ciphertext, is not checked; the destination is. + setJsonBody("{\"CiphertextBlob\":\"not base64!\",\"DestinationKeyId\":\"alias/destination\"}"); + assertEquals(List.of(new RequestResources.Target("kms:ReEncryptTo", List.of(KMS_KEY_ARN), null)), + backed.targets("kms", "kms:ReEncrypt", ctx, "us-east-1", ACCOUNT, "aws")); assertEquals(List.of("*"), kms(backed, "ReEncrypt")); - assertEquals(Map.of(), backed.checkedAs("kms", "kms:Encrypt", ctx, "us-east-1", ACCOUNT, "aws")); + assertEquals(List.of(), backed.targets("kms", "kms:Encrypt", ctx, "us-east-1", ACCOUNT, "aws")); } /** @@ -1630,8 +1604,9 @@ class ResourceArnBuilderTest { KmsService kms = mock(KmsService.class); when(kms.findKeyArnOfAccount(KMS_KEY_ID, ACCOUNT, "us-east-1")).thenReturn(Optional.of(KMS_KEY_ARN)); setJsonBody("{\"KeyId\":\"" + KMS_KEY_ID + "\",\"ReplicaRegion\":\"us-west-2\"}"); - assertEquals(Map.of("kms:ReplicateKey", List.of(KMS_KEY_ARN), "kms:CreateKey", List.of("*")), - backedBy(kms).checkedAs("kms", "kms:ReplicateKey", ctx, "us-east-1", ACCOUNT, "aws")); + assertEquals(List.of(new RequestResources.Target("kms:ReplicateKey", List.of(KMS_KEY_ARN), null), + new RequestResources.Target("kms:CreateKey", List.of("*"), null)), + backedBy(kms).targets("kms", "kms:ReplicateKey", ctx, "us-east-1", ACCOUNT, "aws")); } /** diff --git a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java index 8fe1181517..1faea6cc41 100644 --- a/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java +++ b/src/test/java/io/floci/aws/services/stepfunctions/TaskPermissionsTest.java @@ -205,13 +205,15 @@ class TaskPermissionsTest { assertEquals(Optional.empty(), TaskPermissions.of(integration("dynamodb:query"), json("{\"TableName\":\"t\"}"), machine("aws"))); } + /** A table named by its ARN is checked as given and as the state machine's own, the table execution reaches. */ @Test - void aTableNamedByItsArnIsEvaluatedAsGiven() throws Exception { + void aTableNamedByItsArnIsEvaluatedAsGivenAndAsTheMachinesOwn() throws Exception { String arn = "arn:aws:dynamodb:eu-west-1:444455556666:table/orders"; - assertEquals(List.of(new Permission("dynamodb:PutItem", arn)), sdkPermissions("putItem", "{\"TableName\":\"" + arn + "\"}")); - assertEquals(List.of(new Permission("dynamodb:PutItem", arn)), - TaskPermissions.of(integration("dynamodb:putItem"), json("{\"TableName\":\"" + arn + "\"}"), machine("aws")) - .orElseThrow().permissions()); + List both = List.of(new Permission("dynamodb:PutItem", arn), + new Permission("dynamodb:PutItem", table("orders"))); + assertEquals(both, sdkPermissions("putItem", "{\"TableName\":\"" + arn + "\"}")); + assertEquals(both, TaskPermissions.of(integration("dynamodb:putItem"), json("{\"TableName\":\"" + arn + "\"}"), + machine("aws")).orElseThrow().permissions()); } @Test @@ -233,10 +235,10 @@ class TaskPermissionsTest { @Test void aTransactWriteNeedsEachItemsOwnActionOnItsTable() throws Exception { Map> enclosing = Map.of("dynamodb:EnclosingOperation", List.of("TransactWriteItems")); - assertEquals(List.of(new Permission("dynamodb:PutItem", table("aaa"), enclosing), + assertEquals(List.of(new Permission("dynamodb:ConditionCheckItem", table("ccc"), enclosing), + new Permission("dynamodb:PutItem", table("aaa"), enclosing), new Permission("dynamodb:DeleteItem", table("bbb"), enclosing), - new Permission("dynamodb:UpdateItem", table("aaa"), enclosing), - new Permission("dynamodb:ConditionCheckItem", table("ccc"), enclosing)), + new Permission("dynamodb:UpdateItem", table("aaa"), enclosing)), sdkPermissions("transactWriteItems", """ {"TransactItems":[{"Put":{"TableName":"aaa"}},{"Delete":{"TableName":"bbb"}}, {"Update":{"TableName":"aaa"}},{"ConditionCheck":{"TableName":"ccc"}}]}""")); @@ -250,22 +252,20 @@ class TaskPermissionsTest { sdkPermissions("transactGetItems", "{\"TransactItems\":[{\"Get\":{\"TableName\":\"aaa\"}},{\"Get\":{\"TableName\":\"bbb\"}}]}")); } - /** Execution resolves an ARN within the request's account, so that is the table the item is checked on. */ + /** Execution resolves an ARN within the request's account, so the item is checked on that table too. */ @Test - void aTransactItemNamedByAnArnIsTheTableItsExecutionReaches() throws Exception { - assertEquals(List.of(new Permission("dynamodb:PutItem", table("aaa"), - Map.of("dynamodb:EnclosingOperation", List.of("TransactWriteItems")))), + void aTransactItemNamedByAnArnIsAlsoTheTableItsExecutionReaches() throws Exception { + Map> enclosing = Map.of("dynamodb:EnclosingOperation", List.of("TransactWriteItems")); + assertEquals(List.of(new Permission("dynamodb:PutItem", "arn:aws:dynamodb:eu-west-1:444455556666:table/aaa", + enclosing), new Permission("dynamodb:PutItem", table("aaa"), enclosing)), sdkPermissions("transactWriteItems", """ {"TransactItems":[{"Put":{"TableName":"arn:aws:dynamodb:eu-west-1:444455556666:table/aaa"}}]}""")); } @ParameterizedTest @ValueSource(strings = {"{}", "{\"TransactItems\":\"x\"}", "{\"TransactItems\":[{\"Put\":{}}]}", - "{\"TransactItems\":[{\"Get\":{\"TableName\":\"aaa\"}}]}", - "{\"TransactItems\":[{\"Put\":{\"TableName\":\"arn:aws:dynamodb:ap-south-1:444455556666:table/aaa\"}}]}", - "{\"TransactItems\":[{\"Put\":{\"TableName\":\"a\"}}]}", - "{\"TransactItems\":[{\"Put\":{\"TableName\":\"arn:aws:s3:::aaa\"}}]}"}) - void aTransactionNamingNoTableItCanReachNeedsNoPermission(String request) throws Exception { + "{\"TransactItems\":[{\"Get\":{\"TableName\":\"aaa\"}}]}"}) + void aTransactionNamingNoTableNeedsNoPermission(String request) throws Exception { assertEquals(List.of(), sdkPermissions("transactWriteItems", request)); } @@ -287,9 +287,40 @@ class TaskPermissionsTest { sdkPermissions("executeStatement", "{\"Statement\":\"INSERT INTO \\\"a\\\" VALUE {'pk':'x'}\"}")); } + /** Each statement of a batch or a transaction is checked apart, a transaction's as enclosed by it. */ @Test - void aResourceThatIsNotAnArnNeedsNoPermission() throws Exception { - assertEquals(List.of(), sdkPermissions("tagResource", "{\"ResourceArn\":\"not-an-arn\"}")); + void eachStatementOfABatchIsAuthorizedByWhatItDoesOnWhatItNames() throws Exception { + assertEquals(List.of(new Permission("dynamodb:PartiQLSelect", table("a") + "/index/byName"), + new Permission("dynamodb:PartiQLDelete", table("b"))), + sdkPermissions("batchExecuteStatement", """ + {"Statements":[{"Statement":"DELETE FROM \\"b\\" WHERE pk = 'x'"}, + {"Statement":"SELECT * FROM \\"a\\".\\"byName\\" WHERE pk = 'x'"}]}""")); + Map> enclosing = Map.of("dynamodb:EnclosingOperation", List.of("ExecuteTransaction")); + assertEquals(List.of(new Permission("dynamodb:PartiQLInsert", table("a"), enclosing), + new Permission("dynamodb:PartiQLDelete", table("b"), enclosing)), + sdkPermissions("executeTransaction", """ + {"TransactStatements":[{"Statement":"DELETE FROM \\"b\\" WHERE pk = 'x'"}, + {"Statement":"INSERT INTO \\"a\\" VALUE {'pk':'x'}"}]}""")); + } + + /** An EXISTS statement runs the SELECT it evaluates, so it needs PartiQLSelect on that SELECT's table. */ + @Test + void anExistsStatementIsAuthorizedAsTheSelectItEvaluates() throws Exception { + Map> enclosing = Map.of("dynamodb:EnclosingOperation", List.of("ExecuteTransaction")); + assertEquals(List.of(new Permission("dynamodb:PartiQLSelect", table("b"), enclosing), + new Permission("dynamodb:PartiQLInsert", table("a"), enclosing)), + sdkPermissions("executeTransaction", """ + {"TransactStatements":[{"Statement":"INSERT INTO \\"a\\" VALUE {'pk':'x'}"}, + {"Statement":"EXISTS(SELECT * FROM \\"b\\" WHERE pk = 'x' AND v = 1)"}]}""")); + assertEquals(List.of(), + sdkPermissions("executeTransaction", "{\"TransactStatements\":[{\"Statement\":\"-- nothing\"}]}")); + } + + /** A value naming no resource of the action's types names none, so the call is checked on any resource. */ + @Test + void aResourceThatIsNotAnArnIsCheckedOnAnyResource() throws Exception { + assertEquals(List.of(new Permission("dynamodb:TagResource", "*")), + sdkPermissions("tagResource", "{\"ResourceArn\":\"not-an-arn\"}")); } @ParameterizedTest diff --git a/tools/aws/fetch_dynamodb_permissions.py b/tools/aws/fetch_dynamodb_permissions.py new file mode 100644 index 0000000000..b4b6f77132 --- /dev/null +++ b/tools/aws/fetch_dynamodb_permissions.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Vendor what the Amazon DynamoDB developer guide says its PartiQL statements and transaction items need permission +for into tools/aws/sources/dynamodb-permissions.json, a source of the IAM tables. + +The Service Reference authorizes ExecuteStatement, BatchExecuteStatement and ExecuteTransaction by the four PartiQL +actions and TransactWriteItems by ConditionCheckItem, DeleteItem, PutItem and UpdateItem, but not which statement or +item takes which; botocore does not say it either. The developer guide does: + + The following permissions are required: + To read items using PartiQL for DynamoDB, you must have dynamodb:PartiQLSelect permission on the table or index. + To insert items using PartiQL for DynamoDB, you must have dynamodb:PartiQLInsert permission on the table or index. + (update and delete alike) + + https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-iam.html + + Permissions for Put, Update, Delete, and Get actions are governed by the permissions used for the underlying + PutItem, UpdateItem, DeleteItem, and GetItem operations. For the ConditionCheck action, you can use the + dynamodb:ConditionCheckItem permission in IAM policies. + + https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis-iam.html + +This script copies the PartiQL page's list of required permissions and the transactions page's paragraph on the +permissions of each kind of item, sentence by sentence, each with the names the page sets as code, as they stand. +Nothing in the output is written by hand, and the generator reads it against botocore's requests. + +Run from anywhere in the repo: + python3 tools/aws/fetch_dynamodb_permissions.py # rewrite the vendored file from the pages + python3 tools/aws/fetch_dynamodb_permissions.py --verify # online: the file still says what the pages do +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +PARTIQL_PAGE = "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-iam.html" +TRANSACTIONS_PAGE = "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis-iam.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/dynamodb-permissions.json" + +PARTIQL_LEAD = "The following permissions are required:" +# The transactions page's paragraph on what each kind of item needs, by the words it starts with. +TRANSACTIONS_LEAD = "Permissions for" +CODE_RE = re.compile(r'(.*?)', re.S) + + +def text(fragment: str) -> str: + """A fragment of the page as text, spaces collapsed.""" + return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + + +def sentence(fragment: str) -> dict: + """A sentence of the page as text, with the names it sets as code, in order.""" + return {"text": re.sub(r"\s+([.,])", r"\1", text(fragment)), + "code": [text(code) for code in CODE_RE.findall(fragment)]} + + +def read_partiql(page: str) -> dict: + """The PartiQL page's list of the permissions its statements require, each item with its code.""" + found = re.search(r"

\s*" + re.escape(PARTIQL_LEAD) + r"\s*

\s*]*>\s*]*>(.*?)", page, re.S) + if found is None: + raise ValueError(f"{PARTIQL_PAGE} gives no list after '{PARTIQL_LEAD}': its layout changed") + items = [sentence(item) for item in re.findall(r"]*>(.*?)", found.group(1), re.S)] + if len(items) < 4 or not all(item["code"] for item in items): + raise ValueError(f"{PARTIQL_PAGE}'s list names {len(items)} permissions, not one in each of its four items: " + f"its layout changed") + return {"page": PARTIQL_PAGE, "lead": PARTIQL_LEAD, "items": items} + + +def read_transactions(page: str) -> dict: + """The transactions page's paragraph on the permissions of each kind of item, sentence by sentence.""" + for paragraph in re.findall(r"

(.*?)

", page, re.S): + if text(paragraph).startswith(TRANSACTIONS_LEAD): + sentences = [sentence(part) for part in re.split(r"(?<=\.)\s*(?=[A-Z<])", paragraph.strip()) if text(part)] + return {"page": TRANSACTIONS_PAGE, "sentences": sentences} + raise ValueError(f"{TRANSACTIONS_PAGE} gives no paragraph starting '{TRANSACTIONS_LEAD}': its layout changed") + + +def build(partiql_page: str, transactions_page: str) -> dict: + return { + "_source": { + "pages": [PARTIQL_PAGE, TRANSACTIONS_PAGE], + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "The PartiQL page's list of required permissions and the transactions page's paragraph on the " + "permissions of each kind of item, sentence by sentence, each with the names the page sets as " + "code, copied as they stand.", + }, + "partiql": read_partiql(partiql_page), + "transactions": read_transactions(transactions_page), + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def fetch_all(fetch=fetch_url) -> tuple[str, str]: + """The PartiQL page and the transactions page.""" + return fetch(PARTIQL_PAGE), fetch(TRANSACTIONS_PAGE) + + +def stale(vendored: dict, partiql_page: str, transactions_page: str) -> bool: + """Whether the pages now give something other than the vendored file, its date aside.""" + built = build(partiql_page, transactions_page) + return any(vendored.get(key) != built[key] for key in built if key != "_source") + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages") + args = parser.parse_args(argv) + try: + pages = fetch_all(fetch) + except OSError as e: + print(f"error: could not read the Amazon DynamoDB developer guide ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, *pages): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what {PARTIQL_PAGE} and " + f"{TRANSACTIONS_PAGE} do: run tools/aws/fetch_dynamodb_permissions.py and then make " + f"iam-request-resources-sync", file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches {PARTIQL_PAGE} and {TRANSACTIONS_PAGE}") + return 0 + built = build(*pages) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['partiql']['items'])} PartiQL permissions, " + f"{len(built['transactions']['sentences'])} transaction sentences)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index 7695a01e69..89376ec6ca 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -232,6 +232,14 @@ each resource the one it is checked as (`action`); an action on no resource is c reference says KMS reads its resource out of another's metadata names it through that one when the request leaves it out (`with_from_metadata`: Decrypt's `KeyId`, `CiphertextBlob`), and a type the key identifiers give a name of that is another identifier's ARN's resource is named by that resource whole (`named_resources`, `partialArn`: `alias/`). +DynamoDB's developer guide is granted the same way, its PartiQL page and its transactions page vendored by their own +script: each item of a transaction is checked as the action the transactions page gives its kind, on the table its +`TableName` names (`item_resources`: `TransactItems[].Put.TableName` as `dynamodb:PutItem`), and each PartiQL +statement as the action the PartiQL page gives its verb, on the table or index it names, which the reader asks the +service's parser for (`statement_resources`, `statement`, `verb`, `names`); an operation checked so records the +actions (`actions`) and is checked on each element of a list apart. A top-level map keyed by a shape named after a type, +held by a member named as the type's one variable elsewhere, names that type by its keys (`with_map_keys`: +BatchGetItem's `RequestItems{}`). A qualified type the reference gives an action, one whose format is another type's and one more `:${...}` (Lambda's `function alias` and `function version`), which no member fills alone, is named by that type's member and the request's one member documented as naming the qualified types ("The version number or alias name"): Lambda's @@ -299,6 +307,7 @@ from pathlib import Path import fetch_apigateway_arn_formats import fetch_athena_glue_ddl_permissions +import fetch_dynamodb_permissions import fetch_kms_api_permissions from regen_iam_authorized_actions import (ROUTES as ROUTES_FILE, authorized_actions, fetch_references, load_s3_required, s3_query_parameters, s3_version_choices, @@ -331,10 +340,10 @@ NAMESPACES = ("access-analyzer", "account", "acm", "application-autoscaling", "a "servicequotas", "ssm", "sso", "states", "textract", "timestream-influxdb", "translate", "signer", "xray", "securityhub", "guardduty", "secretsmanager", "scheduler", "lambda", "cloudformation", "glue", "sqs", "sns", "kinesis", "pipes", "dsql", "sts", "eks", "resource-groups", "logs", - "ec2-instance-connect", "s3", "bedrock", "apigateway", "kms") + "ec2-instance-connect", "s3", "bedrock", "apigateway", "kms", "dynamodb") # The namespaces whose resources ResourceArnBuilder builds itself. -HAND_BUILT = ("dynamodb", "iam") +HAND_BUILT = ("iam",) # --------------------------------------------------------------------------------------------------------------------- # MEASURED: what AWS was measured to check where neither botocore nor the Service Reference says it. @@ -457,16 +466,28 @@ PATH_SOURCES: dict[str, Path] = { # on where a request names several, and where the service reads a resource the request leaves out, and the vendored # pages that say so. # -# Granted for KMS alone, whose developer guide's permissions table says it ("kms:ReEncryptFrom on the KMS key used to -# decrypt", "kms:ReEncryptTo on the KMS key used to encrypt"; UpdateAlias "on three resources: The alias, The currently -# associated KMS key, The newly associated KMS key") and whose API reference says Decrypt's key may come from its -# ciphertext ("AWS KMS can get the KMS key from metadata that it adds to the symmetric ciphertext blob"), and whose -# key identifiers give an alias name as the alias ARN's resource ("alias/"). Its file is written by its own -# script from those pages, unchanged (tools/aws/fetch_kms_api_permissions.py), and the generator only reads it -# (`permission_resources`, `with_from_metadata`, `named_resources`): nothing about an operation is stated here. +# Granted for KMS and DynamoDB. KMS's developer guide's permissions table says it ("kms:ReEncryptFrom on the KMS key +# used to decrypt", "kms:ReEncryptTo on the KMS key used to encrypt"; UpdateAlias "on three resources: The alias, The +# currently associated KMS key, The newly associated KMS key"), its API reference says Decrypt's key may come from its +# ciphertext ("AWS KMS can get the KMS key from metadata that it adds to the symmetric ciphertext blob"), and its key +# identifiers give an alias name as the alias ARN's resource ("alias/"); +# tools/aws/fetch_kms_api_permissions.py vendors those pages and `permission_resources`, `with_from_metadata` and +# `named_resources` read them. DynamoDB's +# developer guide gives the action each PartiQL statement's verb and each transaction item's kind is checked as ("To +# read items using PartiQL for DynamoDB, you must have dynamodb:PartiQLSelect permission on the table or index"; +# "Permissions for Put, Update, Delete, and Get actions are governed by the permissions used for the underlying +# PutItem, UpdateItem, DeleteItem, and GetItem operations"); tools/aws/fetch_dynamodb_permissions.py vendors those +# pages and `item_resources` and `statement_resources` read them. Each file is written by its own script from the +# pages, unchanged, and the generator only reads it: nothing about an operation is stated here. # --------------------------------------------------------------------------------------------------------------------- PERMISSION_SOURCES: dict[str, Path] = { "kms": REPO_ROOT / "tools/aws/sources/kms-api-permissions.json", + "dynamodb": REPO_ROOT / "tools/aws/sources/dynamodb-permissions.json", +} +# The script that writes each namespace's permission source, whose pages `verify_permission_sources` reads it against. +PERMISSION_FETCHERS = { + "kms": fetch_kms_api_permissions, + "dynamodb": fetch_dynamodb_permissions, } # A resource a permissions row's list names, after the action it is checked as when it names one: "kms:ReEncryptFrom # on the KMS key used to decrypt", "The alias (in an IAM policy)"; an action checked on no resource names none ("in an @@ -2434,18 +2455,24 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d resources = with_documented_creation(resources, operation, types, formats, models) resources = with_made(resources, operation, formats) source = load_permission_source(namespace_of(operation)) - if source is not None: + known = {upstream["action"]: types, **(upstream.get("actions") or {})} + if source is not None and "permissions" in source: name = operation.split(":", 1)[1] row = next((found for found in source["permissions"] if found["operation"] == name), None) - resources, actions = permission_resources(operation, upstream["action"], resources, row, - {upstream["action"]: types, **(upstream.get("actions") or {})}, - formats, models) + resources, actions = permission_resources(operation, upstream["action"], resources, row, known, formats, + models) resources = with_from_metadata(resources, operation, [found for found in source["fromMetadata"] if found["operation"] == name], models) named = named_resources(source["identifiers"], formats) resources = [dict(resource, partialArn=True) if resource.get("type") in named and len(resource.get("fill") or {}) == 1 else resource for resource in resources] + if source is not None and "partiql" in source: + each = item_resources(operation, item_actions(source, namespace_of(operation)), known, formats, models) \ + or statement_resources(operation, source, known, formats, models) + if each: + resources = each + actions = {action: known[action] for action in dict.fromkeys(row["action"] for row in each)} uses = MEASURED.get(operation, (None, ""))[0] # An entry naming only another action AWS checks gives the operation no resources of its own. if uses is not None and not (uses and all("action" in use for use in uses)): @@ -3075,6 +3102,131 @@ def named_resources(identifiers: list[dict], formats: dict[str, str]) -> set[str return found +def with_map_keys(resources: list[dict], types: list[str], formats: dict[str, str], models: dict[str, dict], + operation: str) -> list[dict]: + """The resources, and a type no rule names that a top-level map of the request names by its keys: one whose botocore + key shape is named after the type and is a shape the service's structures hold a member named as the type's one + variable in (DynamoDB's BatchGetItem `RequestItems`, a `BatchGetRequestMap` keyed by `TableArn`, the shape + `Put.TableName` holds), each key filling that variable (`RequestItems{}`). A key of a shape any string takes + (EMR's `EnvironmentVariables`, keyed by `XmlStringMaxLen256`) names nothing.""" + named = {kind for resource in resources for kind in _kinds(resource)} + found = list(resources) + for kind in types: + variables = [v for v in VARIABLE_RE.findall(formats.get(kind, "")) if v not in KNOWN_VARIABLES] + if kind in named or len(variables) != 1: + continue + held = _held_shapes(models, variables[0]) + for model in models.values(): + spec = model["operations"].get(operation) + if spec is None or "input" not in spec: + continue + for member, value in model["shapes"][spec["input"]["shape"]].get("members", {}).items(): + shape = model["shapes"][value["shape"]] + row = {"type": kind, "fill": {variables[0]: f"{member}{{}}"}} + key = shape.get("key", {}).get("shape", "") + if shape.get("type") == "map" and key in held and related(stem(key), stem(kind)) and row not in found: + found.append(row) + break + return found + + +def item_actions(source: dict, namespace: str) -> dict[str, str]: + """The action each kind of a transaction's item is checked as, as the vendored transactions page pairs them, each + sentence naming the kinds and then, in the same order, their operations or actions ("Permissions for Put, Update, + Delete, and Get actions are governed by the permissions used for the underlying PutItem, UpdateItem, DeleteItem, and + GetItem operations"; "For the ConditionCheck action, you can use the dynamodb:ConditionCheckItem permission").""" + found: dict[str, str] = {} + for sentence in source.get("transactions", {}).get("sentences", []): + codes = sentence["code"] + if not codes or len(codes) % 2: + raise ValueError(f"the vendored transactions sentence '{sentence['text']}' pairs no kinds with actions") + half = len(codes) // 2 + for kind, action in zip(codes[:half], codes[half:]): + found[kind] = action if ":" in action else f"{namespace}:{action}" + return found + + +def item_resources(operation: str, kinds: dict[str, str], known: dict[str, list[str]], formats: dict[str, str], + models: dict[str, dict]) -> list[dict]: + """The resources of a transaction, each item checked as the action the vendored page gives its kind (`kinds`), on + the resource of each type that action acts on whose one variable a member of that name in the item fills: a + TransactWriteItems' `TransactItems[].Put.TableName` as `dynamodb:PutItem`, its `TransactItems[].ConditionCheck. + TableName` as `dynamodb:ConditionCheckItem`. The request's items are the elements of a top-level list whose botocore + structure holds members named as those kinds. None for a request of no such list.""" + name = operation.split(":", 1)[1] + rows: list[dict] = [] + for model in models.values(): + spec = model["operations"].get(name) + if spec is None or "input" not in spec: + continue + for member, held in model["shapes"][spec["input"]["shape"]].get("members", {}).items(): + listed = model["shapes"][held["shape"]] + element = model["shapes"].get(listed.get("member", {}).get("shape", ""), {}) + if listed.get("type") != "list" or element.get("type") != "structure": + continue + for kind, item in element.get("members", {}).items(): + action = kinds.get(kind) + fields = model["shapes"][item["shape"]].get("members", {}) + for type_ in (known.get(action) or []) if action else []: + variables = [v for v in VARIABLE_RE.findall(formats.get(type_, "")) if v not in KNOWN_VARIABLES] + if len(variables) == 1 and variables[0] in fields: + row = {"type": type_, "fill": {variables[0]: f"{member}[].{kind}.{variables[0]}"}, + "action": action} + if row not in rows: + rows.append(row) + break + return rows + + +def statement_resources(operation: str, source: dict, known: dict[str, list[str]], formats: dict[str, str], + models: dict[str, dict]) -> list[dict]: + """The resources of a request carrying statements in the language the vendored PartiQL page names, each checked as + the action the page gives its verb, on the types of its "table or index" the action acts on (`statement`, `verb`): + the reader asks the service for each statement's verb and the names of what it acts on, as its parser reads them, + and checks it as the action named after that verb (`dynamodb:PartiQLSelect` for a SELECT). The statements are the + request's members, top-level or a field of each element of a top-level list, holding the botocore shape named as + that language and `Statement` (`PartiQLStatement`: ExecuteStatement's `Statement`, BatchExecuteStatement's + `Statements[].Statement`). Each variable of those types takes the name the service gives what the statement acts on + by the variable's stem (`names`: a table's `TableName` its `table`, an index's `IndexName` its `index`). None for a + request carrying none.""" + name = operation.split(":", 1)[1] + items = source.get("partiql", {}).get("items", []) + languages = {match.group(1) for item in items if (match := re.search(r"\busing (\w+) for\b", item["text"]))} + if len(languages) != 1: + raise ValueError(f"the vendored PartiQL page names {sorted(languages)} as its language, not one") + shape_name = languages.pop() + "Statement" + paths: list[str] = [] + for model in models.values(): + spec = model["operations"].get(name) + if spec is None or "input" not in spec: + continue + for member, held in model["shapes"][spec["input"]["shape"]].get("members", {}).items(): + if held["shape"] == shape_name: + paths.append(member) + listed = model["shapes"][held["shape"]] + element = model["shapes"].get(listed.get("member", {}).get("shape", ""), {}) + if listed.get("type") == "list": + paths += [f"{member}[].{field}" for field, value in element.get("members", {}).items() + if value["shape"] == shape_name] + break + rows: list[dict] = [] + for path in paths: + for item in items: + action = next((code for code in item["code"] if ":" in code), None) + words = re.search(r"\bon the ([a-z ]+?)\.?$", item["text"]) + if action not in known or words is None or not action.split(":", 1)[1].startswith(shape_name[:-9]): + raise ValueError(f"{operation}: the vendored PartiQL permission '{item['text']}' names no action of " + f"the namespace on its resources") + named = set(re.findall(r"[a-z]+", words.group(1))) + kinds = [kind for kind in known[action] if kind in named and kind in formats] + names = {variable: stem(variable) for kind in kinds for variable in VARIABLE_RE.findall(formats[kind]) + if variable not in KNOWN_VARIABLES} + rows.append({"types": kinds, "statement": path, + "verb": action.split(":", 1)[1][len(shape_name) - 9:].upper(), "names": names, + "action": action}) + return rows + + def read_resources(operation: str, types: list[str], formats: dict[str, str], models: dict[str, dict]) -> list[dict]: """The resources the rules read from the request of the clients given.""" name = operation.split(":", 1)[1] @@ -3115,6 +3267,7 @@ def read_resources(operation: str, types: list[str], formats: dict[str, str], mo resources = with_optional_qualifier(resources, optional) resources = with_qualifier(resources, types, formats, members, models, name) resources = with_partial_arns(resources, partial_arn_members(models, name, formats)) + resources = with_map_keys(resources, types, formats, models, name) # Two rules naming the same resource the same way name it once. return [resource for index, resource in enumerate(resources) if resource not in resources[:index]] @@ -4086,8 +4239,8 @@ PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[])?$") BODY_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[])?(\.[A-Za-z][A-Za-z0-9_]*(\[])?)*$") # A member filling a variable may also be a field of a structure, or of each element of a list of structures, one # value for each. -FILL_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[]|\[]\.[A-Za-z][A-Za-z0-9_]*|\{}\.[A-Za-z][A-Za-z0-9_]*" - r"|\.[A-Za-z][A-Za-z0-9_]*)?$") +FILL_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[]|\[]\.[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)?|\{}" + r"|\{}\.[A-Za-z][A-Za-z0-9_]*|\.[A-Za-z][A-Za-z0-9_]*)?$") # ARN paths can traverse structures, array elements ([]) and map values ({}). ARN_PATH_RE = re.compile(r"^(?:[A-Za-z][A-Za-z0-9_]*(\[])?(\.[A-Za-z][A-Za-z0-9_]*(\[])?)?" r"|[A-Za-z][A-Za-z0-9_]*\{\}(\.[A-Za-z][A-Za-z0-9_]*){1,2})$") @@ -4217,7 +4370,7 @@ def validate(document: dict) -> list[str]: continue several = entry.get("actions") if several is not None and (namespace not in PERMISSION_SOURCES or not isinstance(several, dict) - or len(several) < 2 or not all( + or not several or not all( isinstance(action, str) and OPERATION_RE.match(action) and namespace_of(action) == namespace and isinstance(kinds, list) and all(isinstance(kind, str) and kind in formats.get(namespace, {}) for kind in kinds) @@ -4306,6 +4459,17 @@ def validate(document: dict) -> list[str]: def _resource_problems(operation: str, resource: object, types: set[str], formats: dict[str, str]) -> list[str]: + if isinstance(resource, dict) and "statement" in resource: + kinds = _kinds(resource) + names = resource.get("names") + if set(resource) != {"types", "statement", "verb", "names"} or not kinds or not isinstance(names, dict) \ + or set(names) != {v for kind in kinds for v in VARIABLE_RE.findall(formats.get(kind, "")) + if v not in KNOWN_VARIABLES} or not all( + isinstance(word, str) and re.fullmatch(r"[a-z0-9]+", word) for word in names.values()) or not all( + kind in types and kind in formats for kind in kinds) or not isinstance(resource["statement"], str) \ + or not FILL_PATH_RE.match(resource["statement"]) or not re.fullmatch(r"[A-Z]+", str(resource["verb"])): + return [f"{operation} names {resource!r}, which is no statement member, verb and types its action acts on"] + return [] if not isinstance(resource, dict) or not ({"types", "arn"} <= set(resource) <= {"types", "arn", "made", "endpoint"} or {"types", "through"} <= set(resource) <= {"types", "through", "when", "endpoint"} @@ -4579,13 +4743,14 @@ def verify_permission_sources() -> list[str]: untrue: list[str] = [] for namespace, path in sorted(PERMISSION_SOURCES.items()): source = json.loads(path.read_text(encoding="utf-8")) + fetcher = PERMISSION_FETCHERS[namespace] try: - changed = fetch_kms_api_permissions.stale(source, *fetch_kms_api_permissions.fetch_all()) + changed = fetcher.stale(source, *fetcher.fetch_all()) except (OSError, ValueError) as e: raise OSError(f"could not read {' and '.join(source['_source']['pages'])} ({e})") from e if changed: - untrue.append(f"{' and '.join(source['_source']['pages'])} and the API reference pages they link to no " - f"longer give what {path.name} holds for {namespace}: run {source['_source']['fetcher']}") + untrue.append(f"{' and '.join(source['_source']['pages'])} and the pages they link to no longer give what " + f"{path.name} holds for {namespace}: run {source['_source']['fetcher']}") return untrue diff --git a/tools/aws/sources/dynamodb-permissions.json b/tools/aws/sources/dynamodb-permissions.json new file mode 100644 index 0000000000..9c317628e4 --- /dev/null +++ b/tools/aws/sources/dynamodb-permissions.json @@ -0,0 +1,66 @@ +{ + "_source": { + "pages": [ + "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-iam.html", + "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis-iam.html" + ], + "fetcher": "tools/aws/fetch_dynamodb_permissions.py", + "retrieved": "2026-11-22", + "note": "The PartiQL page's list of required permissions and the transactions page's paragraph on the permissions of each kind of item, sentence by sentence, each with the names the page sets as code, copied as they stand." + }, + "partiql": { + "page": "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-iam.html", + "lead": "The following permissions are required:", + "items": [ + { + "text": "To read items using PartiQL for DynamoDB, you must have dynamodb:PartiQLSelect permission on the table or index.", + "code": [ + "dynamodb:PartiQLSelect" + ] + }, + { + "text": "To insert items using PartiQL for DynamoDB, you must have dynamodb:PartiQLInsert permission on the table or index.", + "code": [ + "dynamodb:PartiQLInsert" + ] + }, + { + "text": "To update items using PartiQL for DynamoDB, you must have dynamodb:PartiQLUpdate permission on the table or index.", + "code": [ + "dynamodb:PartiQLUpdate" + ] + }, + { + "text": "To delete items using PartiQL for DynamoDB, you must have dynamodb:PartiQLDelete permission on the table or index.", + "code": [ + "dynamodb:PartiQLDelete" + ] + } + ] + }, + "transactions": { + "page": "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transaction-apis-iam.html", + "sentences": [ + { + "text": "Permissions for Put, Update, Delete, and Get actions are governed by the permissions used for the underlying PutItem, UpdateItem, DeleteItem, and GetItem operations.", + "code": [ + "Put", + "Update", + "Delete", + "Get", + "PutItem", + "UpdateItem", + "DeleteItem", + "GetItem" + ] + }, + { + "text": "For the ConditionCheck action, you can use the dynamodb:ConditionCheckItem permission in IAM policies.", + "code": [ + "ConditionCheck", + "dynamodb:ConditionCheckItem" + ] + } + ] + } +} diff --git a/tools/aws/test_fetch_dynamodb_permissions.py b/tools/aws/test_fetch_dynamodb_permissions.py new file mode 100644 index 0000000000..defde05e8a --- /dev/null +++ b/tools/aws/test_fetch_dynamodb_permissions.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Tests for fetch_dynamodb_permissions.py, on pages in the Amazon DynamoDB developer guide's markup.""" +from __future__ import annotations + +import pytest + +import fetch_dynamodb_permissions as f + +PARTIQL = ('

IAM security policies with PartiQL for DynamoDB

The following permissions are ' + 'required:

    ' + "".join( + f'
  • To {verb} items using PartiQL for DynamoDB, you must have ' + f'dynamodb:PartiQL{action} permission on the table or index.

  • ' + for verb, action in (("read", "Select"), ("insert", "Insert"), ("update", "Update"), + ("delete", "Delete"))) + '

Example

') +TRANSACTIONS = ('

You can use AWS Identity and Access Management (IAM) to restrict the actions.

' + '

Permissions for Put, Update, and ' + 'Get actions are governed by the permissions used for the underlying ' + 'PutItem, UpdateItem, and ' + 'GetItem operations. For the ConditionCheck ' + 'action, you can use the dynamodb:ConditionCheckItem permission in IAM ' + 'policies.

The following are examples.

') + + +def test_the_partiql_page_gives_each_required_permission_with_its_action(): + read = f.read_partiql(PARTIQL) + assert read["lead"] == "The following permissions are required:" + assert read["items"][0] == {"text": "To read items using PartiQL for DynamoDB, you must have " + "dynamodb:PartiQLSelect permission on the table or index.", + "code": ["dynamodb:PartiQLSelect"]} + assert [item["code"] for item in read["items"]] == [["dynamodb:PartiQLSelect"], ["dynamodb:PartiQLInsert"], + ["dynamodb:PartiQLUpdate"], ["dynamodb:PartiQLDelete"]] + + +def test_the_transactions_page_gives_each_sentence_with_its_kinds_and_actions(): + assert f.read_transactions(TRANSACTIONS)["sentences"] == [ + {"text": "Permissions for Put, Update, and Get actions are governed by the permissions used for the " + "underlying PutItem, UpdateItem, and GetItem operations.", + "code": ["Put", "Update", "Get", "PutItem", "UpdateItem", "GetItem"]}, + {"text": "For the ConditionCheck action, you can use the dynamodb:ConditionCheckItem permission in IAM " + "policies.", "code": ["ConditionCheck", "dynamodb:ConditionCheckItem"]}] + + +def test_a_page_whose_layout_changed_is_refused(): + with pytest.raises(ValueError, match="no list"): + f.read_partiql("") + with pytest.raises(ValueError, match="four items"): + f.read_partiql(PARTIQL.replace('dynamodb:PartiQLDelete', "dynamodb:PartiQLDelete")) + with pytest.raises(ValueError, match="no paragraph"): + f.read_transactions("

Nothing here.

") + + +def test_the_file_is_stale_when_a_page_says_something_else(): + vendored = f.build(PARTIQL, TRANSACTIONS) + assert not f.stale(vendored, PARTIQL, TRANSACTIONS) + assert f.stale(vendored, PARTIQL, TRANSACTIONS.replace("ConditionCheckItem", "ConditionItem")) diff --git a/tools/aws/test_regen_iam_request_resources.py b/tools/aws/test_regen_iam_request_resources.py index e643656e4e..2a8a1a2a9c 100644 --- a/tools/aws/test_regen_iam_request_resources.py +++ b/tools/aws/test_regen_iam_request_resources.py @@ -3074,3 +3074,137 @@ def test_an_operation_checked_as_several_actions_checks_each_resource_as_one_of_ isolated.setattr(r, "PERMISSION_SOURCES", {}) document["operations"]["svc:ReEncrypt"] = entry assert any("vendored permissions" in problem for problem in r.validate(document)) + + +def test_every_permission_source_is_written_by_its_own_fetcher(): + assert set(r.PERMISSION_FETCHERS) == set(r.PERMISSION_SOURCES) + for namespace, path in r.PERMISSION_SOURCES.items(): + assert r.PERMISSION_FETCHERS[namespace].OUTPUT == path, namespace + + +def test_each_permission_source_is_verified_against_the_pages_its_own_fetcher_reads(isolated, tmp_path): + class Fetcher: + def __init__(self, page: str): + self.page = page + + def fetch_all(self): + return (self.page,) + + def stale(self, source, page): + return source["says"] != page + + sources = {} + for namespace, says in (("first", "kept"), ("second", "kept")): + sources[namespace] = tmp_path / f"{namespace}.json" + sources[namespace].write_text(json.dumps({"_source": {"pages": [f"https://{namespace}"], + "fetcher": f"fetch_{namespace}.py"}, "says": says})) + isolated.setattr(r, "PERMISSION_SOURCES", sources) + isolated.setattr(r, "PERMISSION_FETCHERS", {"first": Fetcher("kept"), "second": Fetcher("kept")}) + assert r.verify_permission_sources() == [] + isolated.setattr(r, "PERMISSION_FETCHERS", {"first": Fetcher("kept"), "second": Fetcher("changed")}) + assert r.verify_permission_sources() == ["https://second and the pages they link to no longer give what " + "second.json holds for second: run fetch_second.py"] + + +# --------------------------------------------------------------------------- # +# PERMISSION_SOURCES: the vendored DynamoDB permissions +# --------------------------------------------------------------------------- # +TABLES_FORMATS = {"table": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}", + "index": "arn:${Partition}:dynamodb:${Region}:${Account}:table/${TableName}/index/${IndexName}"} +TABLES_ACTIONS = {"dynamodb:PutItem": ["table"], "dynamodb:DeleteItem": ["table"], "dynamodb:GetItem": ["table"], + "dynamodb:ConditionCheckItem": ["table"], "dynamodb:PartiQLSelect": ["index", "table"], + "dynamodb:PartiQLInsert": ["table"]} +TABLES_SOURCE = { + "partiql": {"items": [ + {"text": "To read items using PartiQL for DynamoDB, you must have dynamodb:PartiQLSelect permission on the " + "table or index.", "code": ["dynamodb:PartiQLSelect"]}, + {"text": "To insert items using PartiQL for DynamoDB, you must have dynamodb:PartiQLInsert permission on the " + "table or index.", "code": ["dynamodb:PartiQLInsert"]}]}, + "transactions": {"sentences": [ + {"text": "Permissions for Put, Delete, and Get actions are governed by the permissions used for the underlying " + "PutItem, DeleteItem, and GetItem operations.", + "code": ["Put", "Delete", "Get", "PutItem", "DeleteItem", "GetItem"]}, + {"text": "For the ConditionCheck action, you can use the dynamodb:ConditionCheckItem permission in IAM " + "policies.", "code": ["ConditionCheck", "dynamodb:ConditionCheckItem"]}]}, +} + + +def dynamodb_model() -> dict: + """A model shaped as DynamoDB's: a transaction's items, PartiQL statements alone and in a list, a batch keyed by + the shape a table's name has, and a map keyed by any string.""" + shapes = { + "TableArn": {"type": "string"}, "PartiQLStatement": {"type": "string"}, "Name": {"type": "string"}, + "Item": {"type": "structure", "members": {"TableName": {"shape": "TableArn"}}}, + "TransactWriteItem": {"type": "structure", "members": {"ConditionCheck": {"shape": "Item"}, + "Put": {"shape": "Item"}, "Delete": {"shape": "Item"}}}, + "TransactWriteItemList": {"type": "list", "member": {"shape": "TransactWriteItem"}}, + "BatchStatementRequest": {"type": "structure", "members": {"Statement": {"shape": "PartiQLStatement"}}}, + "PartiQLBatchRequest": {"type": "list", "member": {"shape": "BatchStatementRequest"}}, + "BatchGetRequestMap": {"type": "map", "key": {"shape": "TableArn"}, "value": {"shape": "Item"}}, + "VariablesMap": {"type": "map", "key": {"shape": "Name"}, "value": {"shape": "Name"}}, + "TransactWriteItemsInput": {"type": "structure", "members": {"TransactItems": {"shape": + "TransactWriteItemList"}}}, + "ExecuteStatementInput": {"type": "structure", "members": {"Statement": {"shape": "PartiQLStatement"}}}, + "BatchExecuteStatementInput": {"type": "structure", + "members": {"Statements": {"shape": "PartiQLBatchRequest"}}}, + "BatchGetItemInput": {"type": "structure", "members": {"RequestItems": {"shape": "BatchGetRequestMap"}, + "Variables": {"shape": "VariablesMap"}}}, + } + operations = {name: {"name": name, "input": {"shape": f"{name}Input"}} + for name in ("TransactWriteItems", "ExecuteStatement", "BatchExecuteStatement", "BatchGetItem")} + return {"metadata": {"protocol": "json", "endpointPrefix": "dynamodb"}, "operations": operations, "shapes": shapes} + + +def test_each_transaction_item_is_checked_as_the_action_the_vendored_page_gives_its_kind(): + kinds = r.item_actions(TABLES_SOURCE, "dynamodb") + assert kinds == {"Put": "dynamodb:PutItem", "Delete": "dynamodb:DeleteItem", "Get": "dynamodb:GetItem", + "ConditionCheck": "dynamodb:ConditionCheckItem"} + assert r.item_resources("dynamodb:TransactWriteItems", kinds, TABLES_ACTIONS, TABLES_FORMATS, + {"dynamodb": dynamodb_model()}) == [ + {"type": "table", "fill": {"TableName": "TransactItems[].ConditionCheck.TableName"}, + "action": "dynamodb:ConditionCheckItem"}, + {"type": "table", "fill": {"TableName": "TransactItems[].Put.TableName"}, "action": "dynamodb:PutItem"}, + {"type": "table", "fill": {"TableName": "TransactItems[].Delete.TableName"}, "action": "dynamodb:DeleteItem"}] + assert r.item_resources("dynamodb:ExecuteStatement", kinds, TABLES_ACTIONS, TABLES_FORMATS, + {"dynamodb": dynamodb_model()}) == [] + with pytest.raises(ValueError, match="pairs no kinds"): + r.item_actions({"transactions": {"sentences": [{"text": "Put.", "code": ["Put"]}]}}, "dynamodb") + + +def test_each_statement_is_checked_as_the_action_of_its_verb_on_its_table_or_index(): + models = {"dynamodb": dynamodb_model()} + assert r.statement_resources("dynamodb:ExecuteStatement", TABLES_SOURCE, TABLES_ACTIONS, TABLES_FORMATS, + models) == [ + {"types": ["index", "table"], "statement": "Statement", "verb": "SELECT", + "names": {"TableName": "table", "IndexName": "index"}, "action": "dynamodb:PartiQLSelect"}, + {"types": ["table"], "statement": "Statement", "verb": "INSERT", "names": {"TableName": "table"}, + "action": "dynamodb:PartiQLInsert"}] + assert [row["statement"] for row in r.statement_resources( + "dynamodb:BatchExecuteStatement", TABLES_SOURCE, TABLES_ACTIONS, TABLES_FORMATS, models)] == \ + ["Statements[].Statement", "Statements[].Statement"] + assert r.statement_resources("dynamodb:TransactWriteItems", TABLES_SOURCE, TABLES_ACTIONS, TABLES_FORMATS, + models) == [] + unknown = {"partiql": {"items": [{"text": "To scan items using PartiQL for DynamoDB, you must have " + "dynamodb:PartiQLScan permission on the table.", + "code": ["dynamodb:PartiQLScan"]}]}} + with pytest.raises(ValueError, match="names no action"): + r.statement_resources("dynamodb:ExecuteStatement", unknown, TABLES_ACTIONS, TABLES_FORMATS, models) + + +def test_a_map_keyed_by_the_shape_a_types_name_has_names_that_type_by_its_keys(): + models = {"dynamodb": dynamodb_model()} + assert r.with_map_keys([], ["table"], TABLES_FORMATS, models, "BatchGetItem") == [ + {"type": "table", "fill": {"TableName": "RequestItems{}"}}] + # A type a rule already names, and a map keyed by any string, add nothing. + named = [{"type": "table", "fill": {"TableName": "TableName"}}] + assert r.with_map_keys(named, ["table"], TABLES_FORMATS, models, "BatchGetItem") == named + assert r.FILL_PATH_RE.match("RequestItems{}") and r.FILL_PATH_RE.match("TransactItems[].Put.TableName") + + +def test_a_statement_resource_names_its_member_verb_and_every_variable_of_its_types(): + good = {"types": ["index", "table"], "statement": "Statements[].Statement", "verb": "SELECT", + "names": {"TableName": "table", "IndexName": "index"}} + assert r._resource_problems("dynamodb:BatchExecuteStatement", good, {"index", "table"}, TABLES_FORMATS) == [] + for bad in (dict(good, verb="select"), dict(good, names={"TableName": "table"}), + dict(good, statement="a.b.c.d"), dict(good, types=["stream"])): + assert r._resource_problems("dynamodb:BatchExecuteStatement", bad, {"index", "table"}, TABLES_FORMATS)