Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(iam): check requests on the resources they name (#6511)

Priamo Germosen932af22f4adc
diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml
index 52cc1c32b5..20130c6a20 100644
--- a/.github/workflows/iam-data-drift.yml
+++ b/.github/workflows/iam-data-drift.yml
@@ -1,10 +1,11 @@
name: IAM Data Drift
-# Checks the five vendored files that come from AWS's live service reference rather than from a
+# Checks the six vendored files that come from AWS's live service reference rather than from a
# pinned dependency: the IAM service namespace list, the map of which resource each IAM action is
# authorized against, the map of operations AWS authorizes as an action of another name, the
-# table of the operations that pass a role and the services they pass it to, and the table of the
-# tagging actions operations that tag what they create need. That
+# table of the operations that pass a role and the services they pass it to, the table of the
+# tagging actions operations that tag what they create need, and the table of the resources each
+# operation's request names. That
# needs the live service reference index, so unlike every other check here it can
# fail without anything in the repository having changed: an AWS outage, or a namespace AWS has
# retired. It therefore runs on its own, never as part of a job that ordinary changes trigger.
@@ -44,6 +45,9 @@ on:
- 'src/main/resources/aws/iam-tag-on-create.json'
- 'tools/aws/regen_iam_tag_on_create.py'
- 'tools/aws/test_regen_iam_tag_on_create.py'
+ - 'src/main/resources/aws/iam-request-resources.json'
+ - 'tools/aws/regen_iam_request_resources.py'
+ - 'tools/aws/test_regen_iam_request_resources.py'
- '.github/workflows/iam-data-drift.yml'
schedule:
# Mondays at 06:00 UTC, before the working week rather than during it.
diff --git a/Makefile b/Makefile
index fb3834d30b..1f999c92ee 100644
--- a/Makefile
+++ b/Makefile
@@ -68,7 +68,8 @@ PREFIX ?= $(HOME)/.local
cfn-property-types-sync cfn-property-types-check cfn-property-types-verify cfn-property-types-test \
iam-authorized-actions-verify iam-authorized-actions-test iam-passed-roles-sync iam-passed-roles-check \
iam-passed-roles-verify iam-passed-roles-test iam-tag-on-create-sync iam-tag-on-create-check \
- iam-tag-on-create-verify iam-tag-on-create-test iam-data-verify
+ iam-tag-on-create-verify iam-tag-on-create-test iam-request-resources-sync iam-request-resources-check \
+ iam-request-resources-verify iam-request-resources-test iam-data-verify
help: ## List the targets below
@grep -hE '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}'
@@ -318,6 +319,7 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation
}
@$(MAKE) --no-print-directory iam-passed-roles-check
@$(MAKE) --no-print-directory iam-tag-on-create-check
+ @$(MAKE) --no-print-directory iam-request-resources-check
aws-data-test: ## Run the AWS data generators' unit tests
$(PYTHON) -m pytest tools/aws -q
@@ -378,14 +380,15 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A
@# Both halves run even when the first fails, so one file's drift cannot hide the other's
@# state. Sequential steps in CI stop at the first failure, which once left the action
@# resource gate unexercised while the namespace list was stale.
- @namespaces=0; actions=0; authorized=0; passed=0; tagged=0; \
+ @namespaces=0; actions=0; authorized=0; passed=0; tagged=0; requested=0; \
$(MAKE) --no-print-directory iam-namespaces-verify || namespaces=$$?; \
$(MAKE) --no-print-directory iam-action-resources-verify || actions=$$?; \
$(MAKE) --no-print-directory iam-authorized-actions-verify || authorized=$$?; \
$(MAKE) --no-print-directory iam-passed-roles-verify || passed=$$?; \
$(MAKE) --no-print-directory iam-tag-on-create-verify || tagged=$$?; \
+ $(MAKE) --no-print-directory iam-request-resources-verify || requested=$$?; \
if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ] || [ $$passed -ne 0 ] \
- || [ $$tagged -ne 0 ]; then \
+ || [ $$tagged -ne 0 ] || [ $$requested -ne 0 ]; then \
echo ""; \
echo "error: vendored IAM data does not match upstream:"; \
if [ $$namespaces -ne 0 ]; then \
@@ -403,6 +406,9 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A
if [ $$tagged -ne 0 ]; then \
echo " the table of the tagging actions creates need, see its message above"; \
fi; \
+ if [ $$requested -ne 0 ]; then \
+ echo " the table of the resources requests name, see its message above"; \
+ fi; \
exit 1; \
fi
@@ -491,6 +497,34 @@ iam-tag-on-create-verify: ## CI gate (online): every vendored operation must sti
iam-tag-on-create-test: ## Run the IAM tag-on-create generator's unit tests
$(PYTHON) -m pytest tools/aws/test_regen_iam_tag_on_create.py -q
+iam-request-resources-sync: ## Regenerate src/main/resources/aws/iam-request-resources.json from AWS and botocore (commit the result)
+ $(PYTHON) tools/aws/regen_iam_request_resources.py
+
+iam-request-resources-check: ## CI gate (offline): every vendored operation's resources must be what the pinned botocore gives
+ @$(PYTHON) tools/aws/regen_iam_request_resources.py --check || { \
+ echo ""; \
+ echo "error: src/main/resources/aws/iam-request-resources.json is malformed or out of date."; \
+ echo " Run 'make iam-request-resources-sync' and commit the result."; \
+ exit 1; \
+ }
+
+iam-request-resources-verify: ## CI gate (online): every vendored operation must still be checked on the resource types AWS gives
+ @$(PYTHON) tools/aws/regen_iam_request_resources.py --verify; status=$$?; \
+ if [ $$status -eq 2 ]; then \
+ echo ""; \
+ echo "error: could not reach AWS's service reference, so nothing was verified."; \
+ exit 1; \
+ elif [ $$status -ne 0 ]; then \
+ echo ""; \
+ echo "error: the vendored table checks an operation as an action, or on resource types or"; \
+ echo " ARN formats, AWS does not give it."; \
+ echo " Run 'make iam-request-resources-sync' and commit the result."; \
+ exit 1; \
+ fi
+
+iam-request-resources-test: ## Run the IAM request resource generator's unit tests
+ $(PYTHON) -m pytest tools/aws/test_regen_iam_request_resources.py -q
+
cfn-property-types-sync: ## Regenerate src/main/resources/aws/cfn-property-types.json from AWS's resource schemas (commit the result)
$(PYTHON) tools/aws/regen_cfn_property_types.py
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 345f9fe258..5d6d4dadbf 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1421,6 +1421,41 @@ requests. REST-JSON requests return HTTP 403 `AccessDeniedException`; AWS Query
requests retain HTTP 403 XML `AccessDenied` responses. The routed protocol determines
the status, not just the request's content type.
+A request is checked against the resources it names. Floci builds their ARNs itself for S3, Lambda,
+SQS, SNS, DynamoDB, Kinesis, SSM, KMS, IAM, Resource Groups, EventBridge Scheduler, EventBridge
+Pipes, Aurora DSQL, EKS, CloudWatch Logs, Secrets Manager and STS. For Elastic Load Balancing, ECR,
+Step Functions and Amazon Cognito user pools they come from a table generated from AWS's Service
+Reference and botocore, `src/main/resources/aws/iam-request-resources.json`, which gives each
+operation's action, the resource types that action acts on with their ARN formats, and the request
+members that name them: a member holding a resource's ARN, which counts when it matches the format
+of a type the action acts on, or members filling the variables of a type's format. A variable the
+request does not fill is `*`, as the service mints a new resource's id, so `CreateTargetGroup` is
+checked on `targetgroup/<Name>/*`; a v2 `CreateLoadBalancer` is checked on the load balancer of its
+`Type`, `loadbalancer/app/<Name>/*` when it gives none, and one of a `Type` outside `application`,
+`network` and `gateway` is refused, as AWS refuses it. The members read are those of the
+operation the request is dispatched as, the one its action is checked as (the Query `Action`, the
+JSON `X-Amz-Target`, or the operation in a Smithy RPC v2 path), so an `X-Amz-Target` an RPC v2
+request also carries names nothing, and as its handler reads them: a list only from a list, so
+`DescribeRepositories` with a single name for `repositoryNames`, which ECR's handler reads as none
+and answers with every repository, names no repository, and a number or a null as its text. A
+member whose botocore shape is an account id gives the account the type is in: ECR's `registryId`
+selects the registry its handler acts in, so `repository/<name>` is checked in that account, and a
+`registryId` that is no account id names no repository, while a null one is the caller's, as ECR
+reads it. `StartExecution` and
+`StartSyncExecution` take Step Functions Local's `<stateMachineArn>#<test case>` and run the
+machine before the `#`, so that machine is the one checked. A state machine's version or alias
+(`stateMachine:<name>:<qualifier>`) is checked on the state machine's ARN, as Step Functions
+authorizes it, so a grant or a deny on `stateMachine:<name>` covers its versions and aliases, and
+an execution started through one is the state machine's. An ARN naming another account or
+Region than the request's is checked as given and as each resource of that name a handler may act
+on instead, in the ARN's account or the caller's and in the ARN's Region or the request's (ECR's
+tag handlers keep the ARN's account in the request's Region), and the request is refused if any is
+denied. Every other request is checked on `*`, as is an operation whose action acts on no
+resource type or whose request names none, where AWS checks `*` too. `make
+iam-request-resources-check` re-derives the table from the pinned botocore, `make
+iam-request-resources-verify` checks it against AWS, and the namespaces it does not read yet are
+listed in it with their reason.
+
A REST request is authorized as the operation of the route it reached. An `X-Amz-Target` header, a
Query `Action` field or a `smithy-protocol` header on it does not change the action it is checked
as, and its path is matched still percent-encoded, as the router matches it, so an encoded `/`
@@ -1732,7 +1767,15 @@ tagged: an instance's on `arn:aws:ec2:<Region>:<account>:instance/*`, from the A
Reference gives the type. Other tags are checked on the resources the operation itself is checked
on: Lambda's `CreateFunction` is checked on the function its body names, in the caller's account and
Region, as the Service Reference gives it the `function` resource, so a function's tags are checked
-there too. Where the tagging action takes
+there too, and a create of a service the table of request resources reads is checked on the resource
+it creates (a target group on `targetgroup/<Name>/*`, an application load balancer on
+`loadbalancer/app/<Name>/*`). A create of a resource under a parent its action acts on tags the new
+resource, so its tags are checked on that one, built from the parent's ARN with its own id open:
+`CreateListener` acts on a load balancer and its tags are checked on
+`listener/app/<load balancer name>/<load balancer id>/*`, and `CreateRule`'s on the new
+`listener-rule/...` under its listener. So the AWS Load Balancer Controller's policy, which allows
+`AddTags` at creation only on target groups and application and network load balancers, and on
+listeners and rules, holds. Where the tagging action takes
its namespace's `CreateAction` key, as `ec2:CreateTags`, `ecs:TagResource`, CloudFormation's
`TagResource` and Elastic Load Balancing's `AddTags` do, the key is the operation's name:
`ec2:CreateAction` is `RunInstances` for an instance launched with tags. The operation's own action
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index 28cc5193d2..180a0a1fb3 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -427,7 +427,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
List<String> resources = resolveResourceArns(credentialScope,
- targetResources(credentialScope, action, ctx, region, accountId));
+ targetResources(credentialScope, action, resolvedAuthorization.operation(), ctx, region, accountId));
Optional<PresignedScope> presignedScope = iamService.presignedScope(akid);
if (presignedScope.isPresent()) {
@@ -976,7 +976,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
/**
* A request that tags what it creates also needs the service's tagging action (see {@link TagOnCreate}),
* checked as the caller for each set of tags, under any spelling a handler might read: on the resource a
- * tag specification names, else on the
+ * tag specification names, else on the resource a create makes under a parent its action acts on, else on the
* resources the operation is checked on, with the set's tags as {@code aws:RequestTag/<key>} and
* {@code aws:TagKeys}, the operation as the namespace's {@code CreateAction} key where the tagging action
* takes one, and the keys that say who is calling. Returns true when the request was aborted.
@@ -986,13 +986,16 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
String operation, TagOnCreate.Tagging tagging,
String credentialScope, List<String> resources,
String region, String accountId, String akid) {
+ // A create of a resource under a parent its action acts on tags the new one (see RequestResources).
+ List<String> created = RequestResources.created(operation, ctx, AwsRegions.partitionFor(region), region,
+ accountId);
+ List<String> made = created.isEmpty() ? resources : created;
for (TagOnCreate.TagSet set : tagging.checked()) {
Map<String, List<String>> context = TagOnCreate.conditionContext(tagging, set, operation);
if (callerArns != null) {
callerArns.putPrincipalKeys(context);
}
- List<String> tagged = TagOnCreate.resources(operation, set, requestPartition(), region, accountId,
- resources);
+ List<String> tagged = TagOnCreate.resources(operation, set, requestPartition(), region, accountId, made);
if (abortIfDenied(ctx, caller, principal, tagging.action(), action, credentialScope, tagged,
List.of(context), region, accountId, akid)) {
return true;
@@ -1583,10 +1586,12 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
/**
* Logs and Secrets Manager targets depend on the serving operation and the request's partition, STS
* targets on the serving operation;
- * Scheduler and Pipes targets on the request's partition, which those services mint their ARNs in.
+ * Scheduler and Pipes targets on the request's partition, which those services mint their ARNs in; and the
+ * targets of a namespace the table of request resources reads on {@code operation}, the one the request is
+ * dispatched as (see {@link RequestResources}).
*/
- private List<String> targetResources(String credentialScope, String action, ContainerRequestContext ctx,
- String region, String accountId) {
+ private List<String> targetResources(String credentialScope, String action, String operation,
+ ContainerRequestContext ctx, String region, String accountId) {
if ("logs".equals(credentialScope)) {
return arnBuilder.buildLogResources(action, ctx, region, accountId, requestPartition());
}
@@ -1599,7 +1604,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
if ("scheduler".equals(credentialScope) || "pipes".equals(credentialScope) || "dsql".equals(credentialScope)) {
return arnBuilder.buildResources(credentialScope, ctx, region, accountId, requestPartition());
}
- return arnBuilder.buildResources(credentialScope, ctx, region, accountId);
+ return arnBuilder.buildResources(credentialScope, operation, ctx, region, accountId,
+ AwsRegions.partitionFor(region));
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java
new file mode 100644
index 0000000000..5912fdc67f
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java
@@ -0,0 +1,263 @@
+package io.github.hectorvent.floci.core.common;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * The resources each operation's request names, for the namespaces whose ARNs {@code ResourceArnBuilder} does not
+ * build itself, read once from the vendored {@code aws/iam-request-resources.json}.
+ *
+ * <p>The file is generated by {@code tools/aws/regen_iam_request_resources.py} from AWS's Service Reference, which
+ * lists the resource types each action acts on and each type's ARN formats, and from botocore's model of the
+ * request, which gives the members that name them. {@code make iam-request-resources-check} re-derives every
+ * operation from botocore and {@code make iam-request-resources-verify} checks them against AWS.
+ *
+ * <p>A missing or malformed resource is a build defect, so loading fails with {@link IllegalStateException}
+ * rather than leaving every operation it reads checked on {@code *}.
+ */
+final class RequestResourceMembers {
+
+ static final String RESOURCE_NAME = "aws/iam-request-resources.json";
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+ private static final Pattern VARIABLE = Pattern.compile("\\$\\{(\\w+)}");
+ private static final Pattern MEMBER = Pattern.compile("[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-]*)(.*)$");
+ /** The one id a child type's format appends to its parent's. */
+ private static final Pattern APPENDED_ID = Pattern.compile("[/:]\\$\\{\\w+}");
+
+ /** A top-level request member that holds a string, or a list of them when {@code list}. */
+ record Member(String name, boolean list) {
+ }
+
+ /**
+ * A resource type's ARN format, with {@code ${Partition}}, {@code ${Region}}, {@code ${Account}} and the
+ * variables a request fills, and the pattern an ARN of the type matches; {@code unqualified} when its service
+ * checks an ARN of it given with a qualifier, one more {@code :<name>} past the format, without that qualifier
+ * (Step Functions checks a version or an alias on its state machine's ARN).
+ */
+ record ArnFormat(String format, Pattern pattern, boolean unqualified) {
+
+ /** The ARN as its service checks it: an unqualified type's without the qualifier it may carry. */
+ String checked(String arn) {
+ if (!unqualified) {
+ return arn;
+ }
+ long colons = format.chars().filter(c -> c == ':').count();
+ int at = -1;
+ for (long found = 0; found <= colons; found++) {
+ at = arn.indexOf(':', at + 1);
+ if (at < 0) {
+ return arn;
+ }
+ }
+ return arn.substring(0, at);
+ }
+ }
+
+ /**
+ * A resource a request names: by a member holding its ARN, which names a resource of one of {@code types} when
+ * it matches the type's format, or by members filling the variables of one type's format, the others open,
+ * only {@code when} each member named has one of its values, an empty one for the member absent, in the
+ * account an {@code account} member gives (ECR's {@code registryId}), or else the request's. An ARN member's
+ * value is read up to the character {@code before}, when there is one, as its handler drops the rest.
+ */
+ record Resource(List<String> types, Member arn, Map<String, Member> fill, Map<String, List<String>> when,
+ Member account, String before) {
+ }
+
+ /**
+ * A resource a create makes under a parent its action acts on, from a member holding the parent's ARN: the
+ * parent's resource with its leading type word {@code parentWord} replaced by {@code childWord} and an open
+ * id appended after {@code separator} ({@code listener/app/<lb>/<id>/*} under {@code loadbalancer/app/...}).
+ */
+ record Created(String type, String parent, Member arn, String parentWord, String childWord, String separator) {
+ }
+
+ /**
+ * The file: each operation's resources and the resources it creates under a parent, as
+ * {@code <namespace>:<Operation>}, each namespace's ARN formats, and the namespaces it reads, those built by
+ * hand, those not read yet, and the others with resource types.
+ */
+ record Table(Map<String, List<Resource>> operations, Map<String, List<Created>> creates,
+ Map<String, Map<String, ArnFormat>> formats, Set<String> namespaces, Set<String> handBuilt,
+ Set<String> notCovered, Set<String> otherNamespaces) {
+ }
+
+ private static final class Holder {
+ static final Table TABLE = VendoredResources.read(RESOURCE_NAME, "IAM request resources table",
+ RequestResourceMembers::parse);
+ }
+
+ private RequestResourceMembers() {
+ }
+
+ static Table table() {
+ return Holder.TABLE;
+ }
+
+ static Table parse(InputStream in) throws IOException {
+ JsonNode document = MAPPER.readTree(in);
+ JsonNode operations = document.path("operations");
+ if (!operations.isObject() || operations.isEmpty()) {
+ throw new IllegalStateException(RESOURCE_NAME + " carries no operations");
+ }
+ Set<String> namespaces = Set.copyOf(document.path("namespaces").propertyStream().map(Map.Entry::getKey).toList());
+ Map<String, Map<String, ArnFormat>> formats = new LinkedHashMap<>();
+ document.path("arnFormats").properties().forEach(namespace -> {
+ Set<String> unqualified = names(document.path("unqualified").path(namespace.getKey()));
+ Map<String, ArnFormat> types = new LinkedHashMap<>();
+ namespace.getValue().properties().forEach(type -> {
+ String format = type.getValue().asText("");
+ if (!format.startsWith("arn:${Partition}:")) {
+ throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + "'s "
+ + type.getKey() + " no ARN format");
+ }
+ types.put(type.getKey(), new ArnFormat(format, pattern(format), unqualified.contains(type.getKey())));
+ });
+ formats.put(namespace.getKey(), Map.copyOf(types));
+ });
+ document.path("unqualified").properties().forEach(namespace -> {
+ Set<String> types = formats.getOrDefault(namespace.getKey(), Map.of()).keySet();
+ if (!namespace.getValue().isArray() || !types.containsAll(names(namespace.getValue()))) {
+ throw new IllegalStateException(RESOURCE_NAME + " checks " + namespace.getKey() + "'s "
+ + namespace.getValue() + " without a qualifier, no types with an ARN format");
+ }
+ });
+ Map<String, List<Resource>> entries = new LinkedHashMap<>();
+ Map<String, List<Created>> creates = new LinkedHashMap<>();
+ operations.properties().forEach(operation -> {
+ String namespace = operation.getKey().substring(0, Math.max(0, operation.getKey().indexOf(':')));
+ if (!namespaces.contains(namespace)) {
+ throw new IllegalStateException(RESOURCE_NAME + " reads " + operation.getKey()
+ + ", of no namespace it reads");
+ }
+ List<Resource> resources = new ArrayList<>();
+ for (JsonNode resource : operation.getValue().path("resources")) {
+ resources.add(resource(operation.getKey(), resource, formats.getOrDefault(namespace, Map.of())));
+ }
+ entries.put(operation.getKey(), List.copyOf(resources));
+ List<Created> made = new ArrayList<>();
+ for (JsonNode created : operation.getValue().path("creates")) {
+ made.add(created(operation.getKey(), created, formats.getOrDefault(namespace, Map.of())));
+ }
+ if (!made.isEmpty()) {
+ creates.put(operation.getKey(), List.copyOf(made));
+ }
+ });
+ return new Table(Map.copyOf(entries), Map.copyOf(creates), Map.copyOf(formats), namespaces,
+ names(document.path("handBuilt")),
+ Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
+ names(document.path("otherNamespaces")));
+ }
+
+ private static Set<String> names(JsonNode list) {
+ return Set.copyOf(list.valueStream().map(JsonNode::asText).toList());
+ }
+
+ private static Resource resource(String operation, JsonNode resource, Map<String, ArnFormat> formats) {
+ if (resource.has("arn")) {
+ List<String> types = resource.path("types").valueStream().map(JsonNode::asText).toList();
+ if (types.isEmpty() || !formats.keySet().containsAll(types)) {
+ throw new IllegalStateException(RESOURCE_NAME + " reads an ARN for " + operation
+ + " of types with no format: " + types);
+ }
+ String before = resource.has("before") ? resource.path("before").asText("") : null;
+ if (before != null && before.length() != 1) {
+ throw new IllegalStateException(RESOURCE_NAME + " reads an ARN for " + operation
+ + " before " + before + ", no one character");
+ }
+ return new Resource(types, member(operation, resource.path("arn").asText("")), Map.of(), Map.of(), null,
+ before);
+ }
+ String type = resource.path("type").asText("");
+ ArnFormat format = formats.get(type);
+ if (format == null || !resource.path("fill").isObject()) {
+ throw new IllegalStateException(RESOURCE_NAME + " names a " + type + " for " + operation
+ + ", a type with no format or no variables to fill");
+ }
+ Set<String> variables = Set.copyOf(VARIABLE.matcher(format.format()).results().map(m -> m.group(1)).toList());
+ Map<String, Member> fill = new LinkedHashMap<>();
+ resource.path("fill").properties().forEach(variable -> {
+ if (!variables.contains(variable.getKey())) {
+ throw new IllegalStateException(RESOURCE_NAME + " fills " + variable.getKey() + " for " + operation
+ + ", no variable of " + type + "'s format");
+ }
+ fill.put(variable.getKey(), member(operation, variable.getValue().asText("")));
+ });
+ if (fill.values().stream().filter(Member::list).count() > 1) {
+ throw new IllegalStateException(RESOURCE_NAME + " fills " + type + " for " + operation
+ + " from more than one list");
+ }
+ Map<String, List<String>> when = new LinkedHashMap<>();
+ resource.path("when").properties().forEach(member -> {
+ if (member(operation, member.getKey()).list() || !member.getValue().isArray() || member.getValue().isEmpty()) {
+ throw new IllegalStateException(RESOURCE_NAME + " names a " + type + " for " + operation
+ + " when " + member.getKey() + " has no values");
+ }
+ when.put(member.getKey(), member.getValue().valueStream().map(value -> value.isNull() ? "" : value.asText())
+ .toList());
+ });
+ Member account = resource.has("account") ? member(operation, resource.path("account").asText("")) : null;
+ if (account != null && (account.list() || !format.format().contains("${Account}"))) {
+ throw new IllegalStateException(RESOURCE_NAME + " takes " + type + "'s account for " + operation
+ + " from " + account.name() + ", no member of one account or a type of none");
+ }
+ return new Resource(List.of(type), null, Map.copyOf(fill), Map.copyOf(when), account, null);
+ }
+
+ private static Created created(String operation, JsonNode created, Map<String, ArnFormat> formats) {
+ String type = created.path("type").asText("");
+ String parent = created.path("parent").asText("");
+ Matcher child = formats.containsKey(type) ? RESOURCE_PART.matcher(formats.get(type).format()) : null;
+ Matcher under = formats.containsKey(parent) ? RESOURCE_PART.matcher(formats.get(parent).format()) : null;
+ if (child == null || under == null || !child.matches() || !under.matches()
+ || child.group(1).equals(under.group(1)) || !child.group(2).startsWith(under.group(2))
+ || !APPENDED_ID.matcher(child.group(2).substring(under.group(2).length())).matches()) {
+ throw new IllegalStateException(RESOURCE_NAME + " creates a " + type + " for " + operation
+ + " under a " + parent + ", no parent of it");
+ }
+ String separator = child.group(2).substring(under.group(2).length(), under.group(2).length() + 1);
+ return new Created(type, parent, member(operation, created.path("arn").asText("")), under.group(1),
+ child.group(1), separator);
+ }
+
+ private static Member member(String operation, String path) {
+ if (!MEMBER.matcher(path).matches()) {
+ throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path + ", which is no member");
+ }
+ return path.endsWith("[]") ? new Member(path.substring(0, path.length() - 2), true) : new Member(path, false);
+ }
+
+ /**
+ * What an ARN of the format matches: its literal parts, a partition, any Region and account, and anything for
+ * each other variable but nothing.
+ */
+ static Pattern pattern(String format) {
+ StringBuilder regex = new StringBuilder("^");
+ Matcher variable = VARIABLE.matcher(format);
+ int at = 0;
+ while (variable.find()) {
+ regex.append(Pattern.quote(format.substring(at, variable.start())));
+ regex.append(switch (variable.group(1)) {
+ case "Partition" -> "[^:]+";
+ case "Region", "Account" -> "[^:]*";
+ default -> ".+";
+ });
+ at = variable.end();
+ }
+ return Pattern.compile(regex.append(Pattern.quote(format.substring(at))).append('$').toString());
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java
new file mode 100644
index 0000000000..dd88a43ef6
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java
@@ -0,0 +1,268 @@
+package io.github.hectorvent.floci.core.common;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import jakarta.ws.rs.container.ContainerRequestContext;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * The resources a request names, as ARNs, for the namespaces {@link RequestResourceMembers} reads: those whose
+ * ARNs {@code ResourceArnBuilder} does not build itself, which are otherwise checked on {@code *}, so a grant
+ * scoped to a resource is refused and a deny scoped to one never applies.
+ *
+ * <p>A request names a resource by a member holding its ARN, which counts when it matches the ARN format of a
+ * resource type the action acts on, or by members filling the variables of a type's format, the others open as
+ * {@code *} (a resource a request creates has the id its service mints). An ARN with a qualifier its service drops
+ * to check it is checked without one (a state machine's version or alias, on the state machine). An ARN naming
+ * another account or Region than the request's is checked as given and as each resource of that name a handler may
+ * act on instead, in the ARN's account or the caller's and in the ARN's Region or the request's, and the request is
+ * refused if any is denied, as handlers mix them (ECR's tag handlers keep the ARN's account in the request's
+ * Region).
+ */
+public final class RequestResources {
+
+ private static final Pattern VARIABLE = Pattern.compile("\\$\\{(\\w+)}");
+ private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
+
+ private RequestResources() {
+ }
+
+ /**
+ * The ARNs of the resources a request names, in the request's partition, Region and account: empty when the
+ * table does not read the operation or its request names none, so it is checked on {@code *}. The operation,
+ * as {@code <namespace>:<Operation>}, is the one the request is dispatched as, never read from the request
+ * again, whose {@code X-Amz-Target} or {@code Action} may name another.
+ */
+ public static List<String> of(String operation, ContainerRequestContext ctx, String partition, String region,
+ String accountId) {
+ RequestResourceMembers.Table table = RequestResourceMembers.table();
+ List<RequestResourceMembers.Resource> resources = operation == null ? null : table.operations().get(operation);
+ if (resources == null || resources.isEmpty()) {
+ return List.of();
+ }
+ Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
+ JsonNode body = form.isEmpty() ? PassedRoles.jsonBody(ctx) : null;
+ Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, operation);
+ Set<String> arns = new LinkedHashSet<>();
+ for (RequestResourceMembers.Resource resource : resources) {
+ if (!applies(resource, form, body)) {
+ continue;
+ }
+ if (resource.arn() != null) {
+ for (String value : values(form, body, resource.arn())) {
+ String named = before(value, resource.before());
+ resource.types().stream().map(formats::get).filter(format -> format.pattern().matcher(named).matches())
+ .findFirst().ifPresent(format -> addNamed(arns, format.checked(named), partition, region,
+ accountId));
+ }
+ } else {
+ fill(arns, resource, formats.get(resource.types().getFirst()), form, body, partition, region, accountId);
+ }
+ }
+ return List.copyOf(arns);
+ }
+
+ /**
+ * The ARNs of the resources a create makes under a parent its action acts on, from the parent's ARN in the
+ * request, read as the operation's own resource reads that member, their ids open; empty when it makes none,
+ * so its tags go where the operation is checked. The operation is the one the request is dispatched as, as for
+ * {@link #of}.
+ */
+ public static List<String> created(String operation, ContainerRequestContext ctx, String partition, String region,
+ String accountId) {
+ RequestResourceMembers.Table table = RequestResourceMembers.table();
+ List<RequestResourceMembers.Created> creates = operation == null ? null : table.creates().get(operation);
+ if (creates == null) {
+ return List.of();
+ }
+ Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
+ JsonNode body = form.isEmpty() ? PassedRoles.jsonBody(ctx) : null;
+ Map<String, RequestResourceMembers.ArnFormat> formats = formats(table, operation);
+ Set<String> arns = new LinkedHashSet<>();
+ for (RequestResourceMembers.Created created : creates) {
+ String separator = table.operations().getOrDefault(operation, List.of()).stream()
+ .filter(resource -> created.arn().equals(resource.arn()) && resource.before() != null)
+ .map(RequestResourceMembers.Resource::before).findFirst().orElse(null);
+ RequestResourceMembers.ArnFormat parentFormat = formats.get(created.parent());
+ for (String value : values(form, body, created.arn())) {
+ String named = before(value, separator);
+ if (!parentFormat.pattern().matcher(named).matches()) {
+ continue;
+ }
+ AwsArnUtils.Arn parent = AwsArnUtils.parse(parentFormat.checked(named));
+ String under = parent.resource().substring(created.parentWord().length());
+ addNamed(arns, new AwsArnUtils.Arn(parent.partition(), parent.service(), parent.region(),
+ parent.accountId(), created.childWord() + under + created.separator() + "*").toString(),
+ partition, region, accountId);
+ }
+ }
+ return List.copyOf(arns);
+ }
+
+ /** The value up to {@code separator}, which its handler drops the rest after; the whole value without one. */
+ private static String before(String value, String separator) {
+ int at = separator == null ? -1 : value.indexOf(separator);
+ return at < 0 ? value : value.substring(0, at);
+ }
+
+ /** Whether each member the resource is named {@code when} has one of its values, an empty one for absent. */
+ private static boolean applies(RequestResourceMembers.Resource resource, Map<String, String> form, JsonNode body) {
+ for (Map.Entry<String, List<String>> member : resource.when().entrySet()) {
+ List<String> values = values(form, body, new RequestResourceMembers.Member(member.getKey(), false));
+ if (!member.getValue().contains(values.isEmpty() ? "" : values.getFirst())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /** The ARN formats of the operation's namespace, the part of {@code <namespace>:<Operation>} before its colon. */
+ private static Map<String, RequestResourceMembers.ArnFormat> formats(RequestResourceMembers.Table table,
+ String operation) {
+ return table.formats().getOrDefault(operation.substring(0, operation.indexOf(':')), Map.of());
+ }
+
+ /**
+ * The ARNs of a type the request names through the variables it fills: one for each value of a list member,
+ * none when it gives none of them. A value that is itself an ARN of the type names that resource. They are in
+ * the account the resource's account member gives, which its handler acts in, and none when that member holds
+ * no account id; in the request's without one, or with a JSON null for it.
+ */
+ private static void fill(Set<String> arns, RequestResourceMembers.Resource resource,
+ RequestResourceMembers.ArnFormat format, Map<String, String> form, JsonNode body,
+ String partition, String region, String accountId) {
+ String account = accountId;
+ if (resource.account() != null) {
+ List<String> given = isNull(body, resource.account()) ? List.of() : values(form, body, resource.account());
+ if (!given.isEmpty() && !ACCOUNT_ID.matcher(given.getFirst()).matches()) {
+ return;
+ }
+ account = given.isEmpty() ? accountId : given.getFirst();
+ }
+ List<Map<String, String>> fillings = new ArrayList<>(List.of(Map.of()));
+ for (Map.Entry<String, RequestResourceMembers.Member> variable : resource.fill().entrySet()) {
+ List<String> values = values(form, body, variable.getValue());
+ if (values.isEmpty()) {
+ continue;
+ }
+ if (resource.fill().size() == 1 && values.stream().allMatch(value -> format.pattern().matcher(value).matches())) {
+ values.forEach(value -> addNamed(arns, format.checked(value), partition, region, accountId));
+ return;
+ }
+ List<Map<String, String>> next = new ArrayList<>();
+ for (Map<String, String> filling : fillings) {
+ for (String value : values) {
+ Map<String, String> more = new HashMap<>(filling);
+ more.put(variable.getKey(), value);
+ next.add(more);
+ }
+ }
+ fillings = next;
+ }
+ if (!resource.fill().isEmpty() && fillings.getFirst().isEmpty()) {
+ return;
+ }
+ for (Map<String, String> filling : fillings) {
+ arns.add(render(format.format(), filling, partition, region, account));
+ }
+ }
+
+ /**
+ * Whether a body gives the member a JSON null, which a handler reading an account with {@code asText(null)} reads
+ * as none (ECR's {@code registryId}, its caller's registry then).
+ */
+ private static boolean isNull(JsonNode body, RequestResourceMembers.Member member) {
+ return body != null && body.isObject() && body.path(member.name()).isNull();
+ }
+
+ /** The format with each variable replaced once: the partition, Region and account, a value, or else {@code *}. */
+ private static String render(String format, Map<String, String> filling, String partition, String region,
+ String accountId) {
+ Matcher variable = VARIABLE.matcher(format);
+ StringBuilder arn = new StringBuilder();
+ while (variable.find()) {
+ String value = switch (variable.group(1)) {
+ case "Partition" -> partition;
+ case "Region" -> region;
+ case "Account" -> accountId;
+ default -> filling.getOrDefault(variable.group(1), "*");
+ };
+ variable.appendReplacement(arn, Matcher.quoteReplacement(value));
+ }
+ return variable.appendTail(arn).toString();
+ }
+
+ /**
+ * An ARN the request names: as given, and, when it names another partition, account or Region than the
+ * request's, as each resource of that name in the request's partition, in the ARN's account or the caller's and
+ * the ARN's Region or the request's, whichever its handler acts on. An ARN with no account or Region keeps none.
+ */
+ private static void addNamed(Set<String> arns, String arn, String partition, String region, String accountId) {
+ arns.add(arn);
+ if (!AwsArnUtils.isArn(arn)) {
+ return;
+ }
+ AwsArnUtils.Arn named = AwsArnUtils.parse(arn);
+ List<String> accounts = named.accountId().isEmpty() ? List.of("") : List.of(named.accountId(), accountId);
+ List<String> regions = named.region().isEmpty() ? List.of("") : List.of(named.region(), region);
+ for (String account : accounts) {
+ for (String inRegion : regions) {
+ arns.add(new AwsArnUtils.Arn(partition, named.service(), inRegion, account, named.resource()).toString());
+ }
+ }
+ }
+
+ /**
+ * The non-empty strings a request gives a member, read as its handler reads them: a form's parameter, or its
+ * list numbered under {@code member} from 1 to the first missing, or a body's value, as text whether a string,
+ * a number, a boolean or a null, and a list member's only from a list, a single value giving none.
+ */
+ private static List<String> values(Map<String, String> form, JsonNode body, RequestResourceMembers.Member member) {
+ List<String> values = new ArrayList<>();
+ if (!form.isEmpty()) {
+ if (!member.list()) {
+ add(values, form.get(member.name()));
+ return values;
+ }
+ for (int i = 1; form.containsKey(member.name() + ".member." + i); i++) {
+ add(values, form.get(member.name() + ".member." + i));
+ }
+ return values;
+ }
+ JsonNode value = body == null || !body.isObject() ? null : body.get(member.name());
+ if (value == null) {
+ return values;
+ }
+ if (!member.list()) {
+ addValue(values, value);
+ } else if (value.isArray()) {
+ for (JsonNode element : value) {
+ addValue(values, element);
+ }
+ }
+ return values;
+ }
+
+ /**
+ * A body's value as text, as a handler's {@code asText()} reads it, a null as {@code null}, and nothing for a
+ * structure, which a handler reads as blank.
+ */
+ private static void addValue(List<String> values, JsonNode value) {
+ if (value.isValueNode()) {
+ add(values, value.asText());
+ }
+ }
+
+ private static void add(List<String> values, String value) {
+ if (value != null && !value.isBlank()) {
+ values.add(value);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.java
index ba78163821..577ce745cc 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandler.java
@@ -232,10 +232,10 @@ public class EcrJsonHandler {
// MANUAL), with empty appliedScanFilters. Note: real AWS reports unknown repos
// in the `failures` array; here describeRepositories throws
// RepositoryNotFoundException, failing the whole batch instead.
+ // AWS's request has no registryId, so the repositories are the caller's.
List<String> names = parseStringList(request.path("repositoryNames"));
- String registryId = request.path("registryId").asText(null);
- List<Repository> repos = service.describeRepositories(names, registryId, region);
+ List<Repository> repos = service.describeRepositories(names, null, region);
ObjectNode response = objectMapper.createObjectNode();
ArrayNode configs = objectMapper.createArrayNode();
diff --git a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
index 29003826eb..cac1b3c940 100644
--- a/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/elbv2/ElbV2Service.java
@@ -45,6 +45,8 @@ import java.util.stream.Collectors;
public class ElbV2Service implements ResourceProvider, ServerCertificateReferenceProvider, VpcDependencyProvider {
private static final Logger LOG = Logger.getLogger(ElbV2Service.class);
+ /** {@code LoadBalancerTypeEnum}, in the model's order. */
+ private static final List<String> LOAD_BALANCER_TYPES = List.of("application", "network", "gateway");
@Inject
ElbV2DataPlane dataPlane;
@@ -226,12 +228,16 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
/**
* Resolving the subnets and publishing the balancer happen under EC2's subnet lock, so a
* DeleteSubnet cannot pass its dependency check in between and leave the balancer on a subnet
- * that is gone.
+ * that is gone. A {@code Type} outside the model's enum is refused, as AWS refuses it, rather
+ * than read as an application load balancer, which is not the one IAM checks the request for.
*/
public LoadBalancer createLoadBalancer(String region, String name, String scheme,
String type, String ipAddressType,
List<String> subnets, List<String> securityGroups,
Map<String, String> initialTags) {
+ if (type != null && !LOAD_BALANCER_TYPES.contains(type)) {
+ throw SmithyValidationErrors.validationError(SmithyValidationErrors.notInEnum(type, "type", LOAD_BALANCER_TYPES));
+ }
return ec2Service.supplyWithSubnetReferencesHeld(region, () -> createLoadBalancerWithSubnetsHeld(
region, name, scheme, type, ipAddressType, subnets, securityGroups, initialTags));
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
index e214cf5691..991ee6428d 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilder.java
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsQueryServiceResolver;
import io.github.hectorvent.floci.core.common.AwsRegions;
+import io.github.hectorvent.floci.core.common.RequestResources;
import io.github.hectorvent.floci.core.common.ServicePrincipals;
import io.github.hectorvent.floci.core.common.SigV4CredentialScope;
import io.github.hectorvent.floci.services.cloudwatch.logs.LogGroupTagTarget;
@@ -124,6 +125,16 @@ public class ResourceArnBuilder {
*/
public List<String> buildResources(String credentialScope, ContainerRequestContext ctx,
String region, String accountId, String partition) {
+ return buildResources(credentialScope, null, ctx, region, accountId, partition);
+ }
+
+ /**
+ * The resources a request is checked against, {@code operation} the one it is dispatched as, as
+ * {@code <namespace>:<Operation>}: a namespace with no branch here is checked on the resources its request
+ * names for that operation (see {@link RequestResources}), and on {@code *} without one.
+ */
+ public List<String> buildResources(String credentialScope, String operation, ContainerRequestContext ctx,
+ String region, String accountId, String partition) {
if (credentialScope == null) {
return List.of("*");
}
@@ -143,10 +154,22 @@ public class ResourceArnBuilder {
case "pipes" -> List.of(buildPipesArn(path, ctx, region, accountId, partition));
case "dsql" -> List.of(buildDsqlArn(path, ctx, region, accountId, partition));
case "eks" -> List.of(buildEksArn(path, ctx, region, accountId));
- default -> List.of("*");
+ default -> namedResources(credentialScope, operation, ctx, region, accountId, partition);
};
}
+ /**
+ * The resources a request of a namespace this builder has no branch for names, from the vendored table of
+ * request resources (see {@link RequestResources}); {@code *} when it names none, or the operation is not one
+ * of the namespace.
+ */
+ private static List<String> namedResources(String credentialScope, String operation, ContainerRequestContext ctx,
+ String region, String accountId, String partition) {
+ List<String> named = operation == null || !operation.startsWith(credentialScope + ":") ? List.of()
+ : RequestResources.of(operation, ctx, partition, region, accountId);
+ return named.isEmpty() ? List.of("*") : named;
+ }
+
private String buildResourceGroupArn(ContainerRequestContext ctx, String region, String accountId) {
JsonNode body = readJsonBody(ctx);
if (body == null) {
diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json
new file mode 100644
index 0000000000..94d30d3998
--- /dev/null
+++ b/src/main/resources/aws/iam-request-resources.json
@@ -0,0 +1,309 @@
+{
+ "_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.113 (installed package)", "retrieved": "2026-10-25", "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": {"cognito-idp": ["cognito-idp"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "states": ["stepfunctions"]},
+ "handBuilt": ["dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts"],
+ "notCovered": {"access-analyzer": "REST: its requests name their resources in the path, which RequestResources does not read yet", "account": "REST: its requests name their resources in the path, which RequestResources does not read yet", "acm": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "airflow": "REST: its requests name their resources in the path, which RequestResources does not read yet", "apigateway": "REST: its requests name their resources in the path, which RequestResources does not read yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources does not read yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources does not read yet", "application-autoscaling": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "appsync": "REST: its requests name their resources in the path, which RequestResources does not read yet", "aps": "REST: its requests name their resources in the path, which RequestResources does not read yet", "athena": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "autoscaling": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "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 does not read yet", "batch": "REST: its requests name their resources in the path, which RequestResources does not read yet", "bcm-data-exports": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "bcm-pricing-calculator": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "bedrock": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources does not read yet", "budgets": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ce": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources does not read yet", "cloudhsm": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudtrail": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "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 does not read yet", "codebuild": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codedeploy": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources does not read yet", "codepipeline": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cognito-identity": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "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 does not read yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources does not read yet", "controltower": "REST: its requests name their resources in the path, which RequestResources does not read yet", "cur": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "datasync": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "detective": "REST: its requests name their resources in the path, which RequestResources does not read yet", "dlm": "REST: its requests name their resources in the path, which RequestResources does not read yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ecs": "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: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticfilesystem": "REST: its requests name their resources in the path, which RequestResources does not read yet", "elasticmapreduce": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "emr-serverless": "REST: its requests name their resources in the path, which RequestResources does not read yet", "es": "REST: its requests name their resources in the path, which RequestResources does not read yet", "events": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "execute-api": "REST: its requests name their resources in the path, which RequestResources does not read yet", "firehose": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "fis": "REST: its requests name their resources in the path, which RequestResources does not read yet", "globalaccelerator": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "glue": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "guardduty": "REST: its requests name their resources in the path, which RequestResources does not read yet", "identitystore": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "inspector2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "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 does not read yet", "kinesisanalytics": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "lightsail": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "macie2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "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 does not read yet", "network-firewall": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "oam": "REST: its requests name their resources in the path, which RequestResources does not read yet", "organizations": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ram": "REST: its requests name their resources in the path, which RequestResources does not read yet", "rds": "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 does not read yet", "redshift": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "redshift-data": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "redshift-serverless": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rekognition": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "resource-explorer-2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "route53": "REST: its requests name their resources in the path, which RequestResources does not read 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 does not read yet", "s3tables": "REST: its requests name their resources in the path, which RequestResources does not read yet", "s3vectors": "REST: its requests name their resources in the path, which RequestResources does not read yet", "sagemaker": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "securityhub": "REST: its requests name their resources in the path, which RequestResources does not read yet", "servicecatalog": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "servicediscovery": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "servicequotas": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "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 does not read yet", "sso": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "sso-oauth": "REST: its requests name their resources in the path, which RequestResources does not read yet", "swf": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "textract": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "timestream-influxdb": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "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", "translate": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "verifiedpermissions": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "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", "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", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar", "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", "ec2-instance-connect", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "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", "outposts", "panorama", "partnercentral", "payment-cryptography", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "quicksight", "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", "signer", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "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", "xray"],
+ "arnFormats": {"cognito-idp": {"userpool": "arn:${Partition}:cognito-idp:${Region}:${Account}:userpool/${UserPoolId}", "webacl": "arn:${Partition}:wafv2:${Region}:${Account}:${Scope}/webacl/${Name}/${Id}"}, "ecr": {"repository": "arn:${Partition}:ecr:${Region}:${Account}:repository/${RepositoryName}"}, "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}"}, "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}"}},
+ "unqualified": {"states": ["statemachine"]},
+ "operations": {
+ "cognito-idp:AddCustomAttributes": {"action": "cognito-idp:AddCustomAttributes", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AddUserPoolClientSecret": {"action": "cognito-idp:AddUserPoolClientSecret", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminAddUserToGroup": {"action": "cognito-idp:AdminAddUserToGroup", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminConfirmSignUp": {"action": "cognito-idp:AdminConfirmSignUp", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminCreateUser": {"action": "cognito-idp:AdminCreateUser", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminDeleteSoftwareToken": {"action": "cognito-idp:AdminDeleteSoftwareToken", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminDeleteUser": {"action": "cognito-idp:AdminDeleteUser", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminDeleteUserAttributes": {"action": "cognito-idp:AdminDeleteUserAttributes", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminDisableProviderForUser": {"action": "cognito-idp:AdminDisableProviderForUser", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminDisableUser": {"action": "cognito-idp:AdminDisableUser", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminEnableUser": {"action": "cognito-idp:AdminEnableUser", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminForgetDevice": {"action": "cognito-idp:AdminForgetDevice", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminGetDevice": {"action": "cognito-idp:AdminGetDevice", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminGetUser": {"action": "cognito-idp:AdminGetUser", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminGetUserAuthFactors": {"action": "cognito-idp:AdminGetUserAuthFactors", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminInitiateAuth": {"action": "cognito-idp:AdminInitiateAuth", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminLinkProviderForUser": {"action": "cognito-idp:AdminLinkProviderForUser", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminListDevices": {"action": "cognito-idp:AdminListDevices", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminListGroupsForUser": {"action": "cognito-idp:AdminListGroupsForUser", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminListUserAuthEvents": {"action": "cognito-idp:AdminListUserAuthEvents", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminRemoveUserFromGroup": {"action": "cognito-idp:AdminRemoveUserFromGroup", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminResetUserPassword": {"action": "cognito-idp:AdminResetUserPassword", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminRespondToAuthChallenge": {"action": "cognito-idp:AdminRespondToAuthChallenge", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminSetUserMFAPreference": {"action": "cognito-idp:AdminSetUserMFAPreference", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminSetUserPassword": {"action": "cognito-idp:AdminSetUserPassword", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminSetUserSettings": {"action": "cognito-idp:AdminSetUserSettings", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminUpdateAuthEventFeedback": {"action": "cognito-idp:AdminUpdateAuthEventFeedback", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminUpdateDeviceStatus": {"action": "cognito-idp:AdminUpdateDeviceStatus", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminUpdateUserAttributes": {"action": "cognito-idp:AdminUpdateUserAttributes", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AdminUserGlobalSignOut": {"action": "cognito-idp:AdminUserGlobalSignOut", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:AssociateSoftwareToken": {"action": "cognito-idp:AssociateSoftwareToken", "types": [], "resources": []},
+ "cognito-idp:ChangePassword": {"action": "cognito-idp:ChangePassword", "types": [], "resources": []},
+ "cognito-idp:CompleteWebAuthnRegistration": {"action": "cognito-idp:CompleteWebAuthnRegistration", "types": [], "resources": []},
+ "cognito-idp:ConfirmDevice": {"action": "cognito-idp:ConfirmDevice", "types": [], "resources": []},
+ "cognito-idp:ConfirmForgotPassword": {"action": "cognito-idp:ConfirmForgotPassword", "types": [], "resources": []},
+ "cognito-idp:ConfirmSignUp": {"action": "cognito-idp:ConfirmSignUp", "types": [], "resources": []},
+ "cognito-idp:CreateGroup": {"action": "cognito-idp:CreateGroup", "types": ["userpool"], "resources": [{"types": ["userpool"], "arn": "RoleArn"}, {"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:CreateIdentityProvider": {"action": "cognito-idp:CreateIdentityProvider", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:CreateManagedLoginBranding": {"action": "cognito-idp:CreateManagedLoginBranding", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:CreateResourceServer": {"action": "cognito-idp:CreateResourceServer", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:CreateTerms": {"action": "cognito-idp:CreateTerms", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:CreateUserImportJob": {"action": "cognito-idp:CreateUserImportJob", "types": ["userpool"], "resources": [{"types": ["userpool"], "arn": "CloudWatchLogsRoleArn"}, {"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:CreateUserPool": {"action": "cognito-idp:CreateUserPool", "types": [], "resources": []},
+ "cognito-idp:CreateUserPoolClient": {"action": "cognito-idp:CreateUserPoolClient", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:CreateUserPoolDomain": {"action": "cognito-idp:CreateUserPoolDomain", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:CreateUserPoolReplica": {"action": "cognito-idp:CreateUserPoolReplica", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteGroup": {"action": "cognito-idp:DeleteGroup", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteIdentityProvider": {"action": "cognito-idp:DeleteIdentityProvider", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteManagedLoginBranding": {"action": "cognito-idp:DeleteManagedLoginBranding", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteResourceServer": {"action": "cognito-idp:DeleteResourceServer", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteTerms": {"action": "cognito-idp:DeleteTerms", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteUser": {"action": "cognito-idp:DeleteUser", "types": [], "resources": []},
+ "cognito-idp:DeleteUserAttributes": {"action": "cognito-idp:DeleteUserAttributes", "types": [], "resources": []},
+ "cognito-idp:DeleteUserPool": {"action": "cognito-idp:DeleteUserPool", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteUserPoolClient": {"action": "cognito-idp:DeleteUserPoolClient", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteUserPoolClientSecret": {"action": "cognito-idp:DeleteUserPoolClientSecret", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteUserPoolDomain": {"action": "cognito-idp:DeleteUserPoolDomain", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteUserPoolReplica": {"action": "cognito-idp:DeleteUserPoolReplica", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DeleteWebAuthnCredential": {"action": "cognito-idp:DeleteWebAuthnCredential", "types": [], "resources": []},
+ "cognito-idp:DescribeIdentityProvider": {"action": "cognito-idp:DescribeIdentityProvider", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeManagedLoginBranding": {"action": "cognito-idp:DescribeManagedLoginBranding", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeManagedLoginBrandingByClient": {"action": "cognito-idp:DescribeManagedLoginBrandingByClient", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeResourceServer": {"action": "cognito-idp:DescribeResourceServer", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeRiskConfiguration": {"action": "cognito-idp:DescribeRiskConfiguration", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeTerms": {"action": "cognito-idp:DescribeTerms", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeTermsByClient": {"action": "cognito-idp:DescribeTerms", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeUserImportJob": {"action": "cognito-idp:DescribeUserImportJob", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeUserPool": {"action": "cognito-idp:DescribeUserPool", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeUserPoolClient": {"action": "cognito-idp:DescribeUserPoolClient", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:DescribeUserPoolDomain": {"action": "cognito-idp:DescribeUserPoolDomain", "types": [], "resources": []},
+ "cognito-idp:ForgetDevice": {"action": "cognito-idp:ForgetDevice", "types": [], "resources": []},
+ "cognito-idp:ForgotPassword": {"action": "cognito-idp:ForgotPassword", "types": [], "resources": []},
+ "cognito-idp:GetCSVHeader": {"action": "cognito-idp:GetCSVHeader", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:GetClientToken": {"action": "cognito-idp:GetClientToken", "types": [], "resources": []},
+ "cognito-idp:GetDevice": {"action": "cognito-idp:GetDevice", "types": [], "resources": []},
+ "cognito-idp:GetGroup": {"action": "cognito-idp:GetGroup", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:GetIdentityProviderByIdentifier": {"action": "cognito-idp:GetIdentityProviderByIdentifier", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:GetLogDeliveryConfiguration": {"action": "cognito-idp:GetLogDeliveryConfiguration", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:GetProvisionedLimit": {"action": "cognito-idp:GetProvisionedLimit", "types": [], "resources": []},
+ "cognito-idp:GetSigningCertificate": {"action": "cognito-idp:GetSigningCertificate", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:GetTokensFromRefreshToken": {"action": "cognito-idp:GetTokensFromRefreshToken", "types": [], "resources": []},
+ "cognito-idp:GetUICustomization": {"action": "cognito-idp:GetUICustomization", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:GetUser": {"action": "cognito-idp:GetUser", "types": [], "resources": []},
+ "cognito-idp:GetUserAttributeVerificationCode": {"action": "cognito-idp:GetUserAttributeVerificationCode", "types": [], "resources": []},
+ "cognito-idp:GetUserAuthFactors": {"action": "cognito-idp:GetUserAuthFactors", "types": [], "resources": []},
+ "cognito-idp:GetUserPoolMfaConfig": {"action": "cognito-idp:GetUserPoolMfaConfig", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:GlobalSignOut": {"action": "cognito-idp:GlobalSignOut", "types": [], "resources": []},
+ "cognito-idp:InitiateAuth": {"action": "cognito-idp:InitiateAuth", "types": [], "resources": []},
+ "cognito-idp:ListDevices": {"action": "cognito-idp:ListDevices", "types": [], "resources": []},
+ "cognito-idp:ListGroups": {"action": "cognito-idp:ListGroups", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListIdentityProviders": {"action": "cognito-idp:ListIdentityProviders", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListResourceServers": {"action": "cognito-idp:ListResourceServers", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListTagsForResource": {"action": "cognito-idp:ListTagsForResource", "types": ["userpool"], "resources": [{"types": ["userpool"], "arn": "ResourceArn"}]},
+ "cognito-idp:ListTerms": {"action": "cognito-idp:ListTerms", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListUserImportJobs": {"action": "cognito-idp:ListUserImportJobs", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListUserPoolClientSecrets": {"action": "cognito-idp:ListUserPoolClientSecrets", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListUserPoolClients": {"action": "cognito-idp:ListUserPoolClients", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListUserPoolReplicas": {"action": "cognito-idp:ListUserPoolReplicas", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListUserPools": {"action": "cognito-idp:ListUserPools", "types": [], "resources": []},
+ "cognito-idp:ListUsers": {"action": "cognito-idp:ListUsers", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListUsersInGroup": {"action": "cognito-idp:ListUsersInGroup", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:ListWebAuthnCredentials": {"action": "cognito-idp:ListWebAuthnCredentials", "types": [], "resources": []},
+ "cognito-idp:ResendConfirmationCode": {"action": "cognito-idp:ResendConfirmationCode", "types": [], "resources": []},
+ "cognito-idp:RespondToAuthChallenge": {"action": "cognito-idp:RespondToAuthChallenge", "types": [], "resources": []},
+ "cognito-idp:RevokeToken": {"action": "cognito-idp:RevokeToken", "types": [], "resources": []},
+ "cognito-idp:SetLogDeliveryConfiguration": {"action": "cognito-idp:SetLogDeliveryConfiguration", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:SetRiskConfiguration": {"action": "cognito-idp:SetRiskConfiguration", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:SetUICustomization": {"action": "cognito-idp:SetUICustomization", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:SetUserMFAPreference": {"action": "cognito-idp:SetUserMFAPreference", "types": [], "resources": []},
+ "cognito-idp:SetUserPoolMfaConfig": {"action": "cognito-idp:SetUserPoolMfaConfig", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:SetUserSettings": {"action": "cognito-idp:SetUserSettings", "types": [], "resources": []},
+ "cognito-idp:SignUp": {"action": "cognito-idp:SignUp", "types": [], "resources": []},
+ "cognito-idp:StartUserImportJob": {"action": "cognito-idp:StartUserImportJob", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:StartWebAuthnRegistration": {"action": "cognito-idp:StartWebAuthnRegistration", "types": [], "resources": []},
+ "cognito-idp:StopUserImportJob": {"action": "cognito-idp:StopUserImportJob", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:TagResource": {"action": "cognito-idp:TagResource", "types": ["userpool"], "resources": [{"types": ["userpool"], "arn": "ResourceArn"}]},
+ "cognito-idp:UntagResource": {"action": "cognito-idp:UntagResource", "types": ["userpool"], "resources": [{"types": ["userpool"], "arn": "ResourceArn"}]},
+ "cognito-idp:UpdateAuthEventFeedback": {"action": "cognito-idp:UpdateAuthEventFeedback", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateDeviceStatus": {"action": "cognito-idp:UpdateDeviceStatus", "types": [], "resources": []},
+ "cognito-idp:UpdateGroup": {"action": "cognito-idp:UpdateGroup", "types": ["userpool"], "resources": [{"types": ["userpool"], "arn": "RoleArn"}, {"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateIdentityProvider": {"action": "cognito-idp:UpdateIdentityProvider", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateManagedLoginBranding": {"action": "cognito-idp:UpdateManagedLoginBranding", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateProvisionedLimit": {"action": "cognito-idp:UpdateProvisionedLimit", "types": [], "resources": []},
+ "cognito-idp:UpdateResourceServer": {"action": "cognito-idp:UpdateResourceServer", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateTerms": {"action": "cognito-idp:UpdateTerms", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateUserAttributes": {"action": "cognito-idp:UpdateUserAttributes", "types": [], "resources": []},
+ "cognito-idp:UpdateUserPool": {"action": "cognito-idp:UpdateUserPool", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateUserPoolClient": {"action": "cognito-idp:UpdateUserPoolClient", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateUserPoolDomain": {"action": "cognito-idp:UpdateUserPoolDomain", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:UpdateUserPoolReplica": {"action": "cognito-idp:UpdateUserPoolReplica", "types": ["userpool"], "resources": [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]},
+ "cognito-idp:VerifySoftwareToken": {"action": "cognito-idp:VerifySoftwareToken", "types": [], "resources": []},
+ "cognito-idp:VerifyUserAttribute": {"action": "cognito-idp:VerifyUserAttribute", "types": [], "resources": []},
+ "ecr:BatchCheckLayerAvailability": {"action": "ecr:BatchCheckLayerAvailability", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:BatchDeleteImage": {"action": "ecr:BatchDeleteImage", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:BatchGetImage": {"action": "ecr:BatchGetImage", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:BatchGetRepositoryScanningConfiguration": {"action": "ecr:BatchGetRepositoryScanningConfiguration", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryNames[]"}}]},
+ "ecr:CompleteLayerUpload": {"action": "ecr:CompleteLayerUpload", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:CreatePullThroughCacheRule": {"action": "ecr:CreatePullThroughCacheRule", "types": [], "resources": []},
+ "ecr:CreateRepository": {"action": "ecr:CreateRepository", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:CreateRepositoryCreationTemplate": {"action": "ecr:CreateRepositoryCreationTemplate", "types": [], "resources": []},
+ "ecr:DeleteLifecyclePolicy": {"action": "ecr:DeleteLifecyclePolicy", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:DeletePullThroughCacheRule": {"action": "ecr:DeletePullThroughCacheRule", "types": [], "resources": []},
+ "ecr:DeleteRegistryPolicy": {"action": "ecr:DeleteRegistryPolicy", "types": [], "resources": []},
+ "ecr:DeleteRepository": {"action": "ecr:DeleteRepository", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:DeleteRepositoryCreationTemplate": {"action": "ecr:DeleteRepositoryCreationTemplate", "types": [], "resources": []},
+ "ecr:DeleteRepositoryPolicy": {"action": "ecr:DeleteRepositoryPolicy", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:DeleteSigningConfiguration": {"action": "ecr:DeleteSigningConfiguration", "types": [], "resources": []},
+ "ecr:DeregisterPullTimeUpdateExclusion": {"action": "ecr:DeregisterPullTimeUpdateExclusion", "types": [], "resources": []},
+ "ecr:DescribeImageReplicationStatus": {"action": "ecr:DescribeImageReplicationStatus", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:DescribeImageScanFindings": {"action": "ecr:DescribeImageScanFindings", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:DescribeImageSigningStatus": {"action": "ecr:DescribeImageSigningStatus", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:DescribeImages": {"action": "ecr:DescribeImages", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:DescribePullThroughCacheRules": {"action": "ecr:DescribePullThroughCacheRules", "types": [], "resources": []},
+ "ecr:DescribeRegistry": {"action": "ecr:DescribeRegistry", "types": [], "resources": []},
+ "ecr:DescribeRepositories": {"action": "ecr:DescribeRepositories", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryNames[]"}, "account": "registryId"}]},
+ "ecr:DescribeRepositoryCreationTemplates": {"action": "ecr:DescribeRepositoryCreationTemplates", "types": [], "resources": []},
+ "ecr:GetAccountSetting": {"action": "ecr:GetAccountSetting", "types": [], "resources": []},
+ "ecr:GetAuthorizationToken": {"action": "ecr:GetAuthorizationToken", "types": [], "resources": []},
+ "ecr:GetDownloadUrlForLayer": {"action": "ecr:GetDownloadUrlForLayer", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:GetLifecyclePolicy": {"action": "ecr:GetLifecyclePolicy", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:GetLifecyclePolicyPreview": {"action": "ecr:GetLifecyclePolicyPreview", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:GetRegistryPolicy": {"action": "ecr:GetRegistryPolicy", "types": [], "resources": []},
+ "ecr:GetRegistryScanningConfiguration": {"action": "ecr:GetRegistryScanningConfiguration", "types": [], "resources": []},
+ "ecr:GetRepositoryPolicy": {"action": "ecr:GetRepositoryPolicy", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:GetSigningConfiguration": {"action": "ecr:GetSigningConfiguration", "types": [], "resources": []},
+ "ecr:InitiateLayerUpload": {"action": "ecr:InitiateLayerUpload", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:ListImageReferrers": {"action": "ecr:ListImageReferrers", "types": [], "resources": []},
+ "ecr:ListImages": {"action": "ecr:ListImages", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:ListPullTimeUpdateExclusions": {"action": "ecr:ListPullTimeUpdateExclusions", "types": [], "resources": []},
+ "ecr:ListTagsForResource": {"action": "ecr:ListTagsForResource", "types": ["repository"], "resources": [{"types": ["repository"], "arn": "resourceArn"}]},
+ "ecr:PutAccountSetting": {"action": "ecr:PutAccountSetting", "types": [], "resources": []},
+ "ecr:PutImage": {"action": "ecr:PutImage", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:PutImageScanningConfiguration": {"action": "ecr:PutImageScanningConfiguration", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:PutImageTagMutability": {"action": "ecr:PutImageTagMutability", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:PutLifecyclePolicy": {"action": "ecr:PutLifecyclePolicy", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:PutRegistryPolicy": {"action": "ecr:PutRegistryPolicy", "types": [], "resources": []},
+ "ecr:PutRegistryScanningConfiguration": {"action": "ecr:PutRegistryScanningConfiguration", "types": [], "resources": []},
+ "ecr:PutReplicationConfiguration": {"action": "ecr:PutReplicationConfiguration", "types": [], "resources": []},
+ "ecr:PutSigningConfiguration": {"action": "ecr:PutSigningConfiguration", "types": [], "resources": []},
+ "ecr:RegisterPullTimeUpdateExclusion": {"action": "ecr:RegisterPullTimeUpdateExclusion", "types": [], "resources": []},
+ "ecr:SetRepositoryPolicy": {"action": "ecr:SetRepositoryPolicy", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:StartImageScan": {"action": "ecr:StartImageScan", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:StartLifecyclePolicyPreview": {"action": "ecr:StartLifecyclePolicyPreview", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:TagResource": {"action": "ecr:TagResource", "types": ["repository"], "resources": [{"types": ["repository"], "arn": "resourceArn"}]},
+ "ecr:UntagResource": {"action": "ecr:UntagResource", "types": ["repository"], "resources": [{"types": ["repository"], "arn": "resourceArn"}]},
+ "ecr:UpdateImageStorageClass": {"action": "ecr:UpdateImageStorageClass", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:UpdatePullThroughCacheRule": {"action": "ecr:UpdatePullThroughCacheRule", "types": [], "resources": []},
+ "ecr:UpdateRepositoryCreationTemplate": {"action": "ecr:UpdateRepositoryCreationTemplate", "types": [], "resources": []},
+ "ecr:UploadLayerPart": {"action": "ecr:UploadLayerPart", "types": ["repository"], "resources": [{"type": "repository", "fill": {"RepositoryName": "repositoryName"}, "account": "registryId"}]},
+ "ecr:ValidatePullThroughCacheRule": {"action": "ecr:ValidatePullThroughCacheRule", "types": [], "resources": []},
+ "elasticloadbalancing:AddListenerCertificates": {"action": "elasticloadbalancing:AddListenerCertificates", "types": ["listener/app", "listener/net"], "resources": [{"types": ["listener/app", "listener/net"], "arn": "ListenerArn"}]},
+ "elasticloadbalancing:AddTags": {"action": "elasticloadbalancing:AddTags", "types": ["listener-rule/app", "listener-rule/net", "listener/app", "listener/gwy", "listener/net", "loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/", "targetgroup", "truststore"], "resources": [{"types": ["listener-rule/app", "listener-rule/net", "listener/app", "listener/gwy", "listener/net", "loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/", "targetgroup", "truststore"], "arn": "ResourceArns[]"}, {"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerNames[]"}}]},
+ "elasticloadbalancing:AddTrustStoreRevocations": {"action": "elasticloadbalancing:AddTrustStoreRevocations", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "TrustStoreArn"}]},
+ "elasticloadbalancing:ApplySecurityGroupsToLoadBalancer": {"action": "elasticloadbalancing:ApplySecurityGroupsToLoadBalancer", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:AttachLoadBalancerToSubnets": {"action": "elasticloadbalancing:AttachLoadBalancerToSubnets", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:ConfigureHealthCheck": {"action": "elasticloadbalancing:ConfigureHealthCheck", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:CreateAppCookieStickinessPolicy": {"action": "elasticloadbalancing:CreateAppCookieStickinessPolicy", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:CreateLBCookieStickinessPolicy": {"action": "elasticloadbalancing:CreateLBCookieStickinessPolicy", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:CreateListener": {"action": "elasticloadbalancing:CreateListener", "types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "resources": [{"types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "arn": "LoadBalancerArn"}], "creates": [{"type": "listener/app", "parent": "loadbalancer/app/", "arn": "LoadBalancerArn"}, {"type": "listener/gwy", "parent": "loadbalancer/gwy/", "arn": "LoadBalancerArn"}, {"type": "listener/net", "parent": "loadbalancer/net/", "arn": "LoadBalancerArn"}]},
+ "elasticloadbalancing:CreateLoadBalancer": {"action": "elasticloadbalancing:CreateLoadBalancer", "types": ["loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}, {"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", null]}}, {"type": "loadbalancer/gwy/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["gateway"]}}, {"type": "loadbalancer/net/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["network"]}}]},
+ "elasticloadbalancing:CreateLoadBalancerListeners": {"action": "elasticloadbalancing:CreateLoadBalancerListeners", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:CreateLoadBalancerPolicy": {"action": "elasticloadbalancing:CreateLoadBalancerPolicy", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:CreateRule": {"action": "elasticloadbalancing:CreateRule", "types": ["listener/app", "listener/net"], "resources": [{"types": ["listener/app", "listener/net"], "arn": "ListenerArn"}], "creates": [{"type": "listener-rule/app", "parent": "listener/app", "arn": "ListenerArn"}, {"type": "listener-rule/net", "parent": "listener/net", "arn": "ListenerArn"}]},
+ "elasticloadbalancing:CreateTargetGroup": {"action": "elasticloadbalancing:CreateTargetGroup", "types": ["targetgroup"], "resources": [{"type": "targetgroup", "fill": {"TargetGroupName": "Name"}}]},
+ "elasticloadbalancing:CreateTrustStore": {"action": "elasticloadbalancing:CreateTrustStore", "types": ["truststore"], "resources": [{"type": "truststore", "fill": {"TrustStoreName": "Name"}}]},
+ "elasticloadbalancing:DeleteListener": {"action": "elasticloadbalancing:DeleteListener", "types": ["listener/app", "listener/gwy", "listener/net"], "resources": [{"types": ["listener/app", "listener/gwy", "listener/net"], "arn": "ListenerArn"}]},
+ "elasticloadbalancing:DeleteLoadBalancer": {"action": "elasticloadbalancing:DeleteLoadBalancer", "types": ["loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "resources": [{"types": ["loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "arn": "LoadBalancerArn"}, {"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:DeleteLoadBalancerListeners": {"action": "elasticloadbalancing:DeleteLoadBalancerListeners", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:DeleteLoadBalancerPolicy": {"action": "elasticloadbalancing:DeleteLoadBalancerPolicy", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:DeleteRule": {"action": "elasticloadbalancing:DeleteRule", "types": ["listener-rule/app", "listener-rule/net"], "resources": [{"types": ["listener-rule/app", "listener-rule/net"], "arn": "RuleArn"}]},
+ "elasticloadbalancing:DeleteSharedTrustStoreAssociation": {"action": "elasticloadbalancing:DeleteSharedTrustStoreAssociation", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "ResourceArn"}, {"types": ["truststore"], "arn": "TrustStoreArn"}]},
+ "elasticloadbalancing:DeleteTargetGroup": {"action": "elasticloadbalancing:DeleteTargetGroup", "types": ["targetgroup"], "resources": [{"types": ["targetgroup"], "arn": "TargetGroupArn"}]},
+ "elasticloadbalancing:DeleteTrustStore": {"action": "elasticloadbalancing:DeleteTrustStore", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "TrustStoreArn"}]},
+ "elasticloadbalancing:DeregisterInstancesFromLoadBalancer": {"action": "elasticloadbalancing:DeregisterInstancesFromLoadBalancer", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:DeregisterTargets": {"action": "elasticloadbalancing:DeregisterTargets", "types": ["targetgroup"], "resources": [{"types": ["targetgroup"], "arn": "TargetGroupArn"}]},
+ "elasticloadbalancing:DescribeAccountLimits": {"action": "elasticloadbalancing:DescribeAccountLimits", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeCapacityReservation": {"action": "elasticloadbalancing:DescribeCapacityReservation", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeInstanceHealth": {"action": "elasticloadbalancing:DescribeInstanceHealth", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeListenerAttributes": {"action": "elasticloadbalancing:DescribeListenerAttributes", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeListenerCertificates": {"action": "elasticloadbalancing:DescribeListenerCertificates", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeListeners": {"action": "elasticloadbalancing:DescribeListeners", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeLoadBalancerAttributes": {"action": "elasticloadbalancing:DescribeLoadBalancerAttributes", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeLoadBalancerPolicies": {"action": "elasticloadbalancing:DescribeLoadBalancerPolicies", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeLoadBalancerPolicyTypes": {"action": "elasticloadbalancing:DescribeLoadBalancerPolicyTypes", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeLoadBalancers": {"action": "elasticloadbalancing:DescribeLoadBalancers", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeRules": {"action": "elasticloadbalancing:DescribeRules", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeSSLPolicies": {"action": "elasticloadbalancing:DescribeSSLPolicies", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeTags": {"action": "elasticloadbalancing:DescribeTags", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeTargetGroupAttributes": {"action": "elasticloadbalancing:DescribeTargetGroupAttributes", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeTargetGroups": {"action": "elasticloadbalancing:DescribeTargetGroups", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeTargetHealth": {"action": "elasticloadbalancing:DescribeTargetHealth", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeTrustStoreAssociations": {"action": "elasticloadbalancing:DescribeTrustStoreAssociations", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeTrustStoreRevocations": {"action": "elasticloadbalancing:DescribeTrustStoreRevocations", "types": [], "resources": []},
+ "elasticloadbalancing:DescribeTrustStores": {"action": "elasticloadbalancing:DescribeTrustStores", "types": [], "resources": []},
+ "elasticloadbalancing:DetachLoadBalancerFromSubnets": {"action": "elasticloadbalancing:DetachLoadBalancerFromSubnets", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:DisableAvailabilityZonesForLoadBalancer": {"action": "elasticloadbalancing:DisableAvailabilityZonesForLoadBalancer", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:EnableAvailabilityZonesForLoadBalancer": {"action": "elasticloadbalancing:EnableAvailabilityZonesForLoadBalancer", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:GetResourcePolicy": {"action": "elasticloadbalancing:GetResourcePolicy", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "ResourceArn"}]},
+ "elasticloadbalancing:GetTrustStoreCaCertificatesBundle": {"action": "elasticloadbalancing:GetTrustStoreCaCertificatesBundle", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "TrustStoreArn"}]},
+ "elasticloadbalancing:GetTrustStoreRevocationContent": {"action": "elasticloadbalancing:GetTrustStoreRevocationContent", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "TrustStoreArn"}]},
+ "elasticloadbalancing:ModifyCapacityReservation": {"action": "elasticloadbalancing:ModifyCapacityReservation", "types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "resources": [{"types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "arn": "LoadBalancerArn"}]},
+ "elasticloadbalancing:ModifyIpPools": {"action": "elasticloadbalancing:ModifyIpPools", "types": ["loadbalancer/app/"], "resources": [{"types": ["loadbalancer/app/"], "arn": "LoadBalancerArn"}]},
+ "elasticloadbalancing:ModifyListener": {"action": "elasticloadbalancing:ModifyListener", "types": ["listener/app", "listener/gwy", "listener/net"], "resources": [{"types": ["listener/app", "listener/gwy", "listener/net"], "arn": "ListenerArn"}]},
+ "elasticloadbalancing:ModifyListenerAttributes": {"action": "elasticloadbalancing:ModifyListenerAttributes", "types": ["listener/app", "listener/gwy", "listener/net"], "resources": [{"types": ["listener/app", "listener/gwy", "listener/net"], "arn": "ListenerArn"}]},
+ "elasticloadbalancing:ModifyLoadBalancerAttributes": {"action": "elasticloadbalancing:ModifyLoadBalancerAttributes", "types": ["loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "resources": [{"types": ["loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "arn": "LoadBalancerArn"}, {"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:ModifyRule": {"action": "elasticloadbalancing:ModifyRule", "types": ["listener-rule/app", "listener-rule/net"], "resources": [{"types": ["listener-rule/app", "listener-rule/net"], "arn": "RuleArn"}]},
+ "elasticloadbalancing:ModifyTargetGroup": {"action": "elasticloadbalancing:ModifyTargetGroup", "types": ["targetgroup"], "resources": [{"types": ["targetgroup"], "arn": "TargetGroupArn"}]},
+ "elasticloadbalancing:ModifyTargetGroupAttributes": {"action": "elasticloadbalancing:ModifyTargetGroupAttributes", "types": ["targetgroup"], "resources": [{"types": ["targetgroup"], "arn": "TargetGroupArn"}]},
+ "elasticloadbalancing:ModifyTrustStore": {"action": "elasticloadbalancing:ModifyTrustStore", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "TrustStoreArn"}]},
+ "elasticloadbalancing:RegisterInstancesWithLoadBalancer": {"action": "elasticloadbalancing:RegisterInstancesWithLoadBalancer", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:RegisterTargets": {"action": "elasticloadbalancing:RegisterTargets", "types": ["targetgroup"], "resources": [{"types": ["targetgroup"], "arn": "TargetGroupArn"}]},
+ "elasticloadbalancing:RemoveListenerCertificates": {"action": "elasticloadbalancing:RemoveListenerCertificates", "types": ["listener/app", "listener/net"], "resources": [{"types": ["listener/app", "listener/net"], "arn": "ListenerArn"}]},
+ "elasticloadbalancing:RemoveTags": {"action": "elasticloadbalancing:RemoveTags", "types": ["listener-rule/app", "listener-rule/net", "listener/app", "listener/gwy", "listener/net", "loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/", "targetgroup", "truststore"], "resources": [{"types": ["listener-rule/app", "listener-rule/net", "listener/app", "listener/gwy", "listener/net", "loadbalancer", "loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/", "targetgroup", "truststore"], "arn": "ResourceArns[]"}, {"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerNames[]"}}]},
+ "elasticloadbalancing:RemoveTrustStoreRevocations": {"action": "elasticloadbalancing:RemoveTrustStoreRevocations", "types": ["truststore"], "resources": [{"types": ["truststore"], "arn": "TrustStoreArn"}]},
+ "elasticloadbalancing:SetIpAddressType": {"action": "elasticloadbalancing:SetIpAddressType", "types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "resources": [{"types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "arn": "LoadBalancerArn"}]},
+ "elasticloadbalancing:SetLoadBalancerListenerSSLCertificate": {"action": "elasticloadbalancing:SetLoadBalancerListenerSSLCertificate", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:SetLoadBalancerPoliciesForBackendServer": {"action": "elasticloadbalancing:SetLoadBalancerPoliciesForBackendServer", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:SetLoadBalancerPoliciesOfListener": {"action": "elasticloadbalancing:SetLoadBalancerPoliciesOfListener", "types": ["loadbalancer"], "resources": [{"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}]},
+ "elasticloadbalancing:SetRulePriorities": {"action": "elasticloadbalancing:SetRulePriorities", "types": ["listener-rule/app", "listener-rule/net"], "resources": []},
+ "elasticloadbalancing:SetSecurityGroups": {"action": "elasticloadbalancing:SetSecurityGroups", "types": ["loadbalancer/app/", "loadbalancer/net/"], "resources": [{"types": ["loadbalancer/app/", "loadbalancer/net/"], "arn": "LoadBalancerArn"}]},
+ "elasticloadbalancing:SetSubnets": {"action": "elasticloadbalancing:SetSubnets", "types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "resources": [{"types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "arn": "LoadBalancerArn"}]},
+ "states:CreateActivity": {"action": "states:CreateActivity", "types": ["activity"], "resources": [{"type": "activity", "fill": {"ActivityName": "name"}}]},
+ "states:CreateStateMachine": {"action": "states:CreateStateMachine", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "roleArn"}, {"type": "statemachine", "fill": {"StateMachineName": "name"}}]},
+ "states:CreateStateMachineAlias": {"action": "states:CreateStateMachineAlias", "types": ["statemachine"], "resources": []},
+ "states:DeleteActivity": {"action": "states:DeleteActivity", "types": ["activity"], "resources": [{"types": ["activity"], "arn": "activityArn"}]},
+ "states:DeleteStateMachine": {"action": "states:DeleteStateMachine", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn"}]},
+ "states:DeleteStateMachineAlias": {"action": "states:DeleteStateMachineAlias", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineAliasArn"}]},
+ "states:DeleteStateMachineVersion": {"action": "states:DeleteStateMachineVersion", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineVersionArn"}]},
+ "states:DescribeActivity": {"action": "states:DescribeActivity", "types": ["activity"], "resources": [{"types": ["activity"], "arn": "activityArn"}]},
+ "states:DescribeExecution": {"action": "states:DescribeExecution", "types": ["execution", "express"], "resources": [{"types": ["execution", "express"], "arn": "executionArn"}]},
+ "states:DescribeMapRun": {"action": "states:DescribeMapRun", "types": ["maprun"], "resources": [{"types": ["maprun"], "arn": "mapRunArn"}]},
+ "states:DescribeStateMachine": {"action": "states:DescribeStateMachine", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn"}]},
+ "states:DescribeStateMachineAlias": {"action": "states:DescribeStateMachineAlias", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineAliasArn"}]},
+ "states:DescribeStateMachineForExecution": {"action": "states:DescribeStateMachineForExecution", "types": ["execution"], "resources": [{"types": ["execution"], "arn": "executionArn"}]},
+ "states:GetActivityTask": {"action": "states:GetActivityTask", "types": ["activity"], "resources": [{"types": ["activity"], "arn": "activityArn"}]},
+ "states:GetExecutionHistory": {"action": "states:GetExecutionHistory", "types": ["execution"], "resources": [{"types": ["execution"], "arn": "executionArn"}]},
+ "states:ListActivities": {"action": "states:ListActivities", "types": [], "resources": []},
+ "states:ListExecutions": {"action": "states:ListExecutions", "types": ["maprun", "statemachine"], "resources": [{"types": ["maprun", "statemachine"], "arn": "mapRunArn"}, {"types": ["maprun", "statemachine"], "arn": "stateMachineArn"}]},
+ "states:ListMapRuns": {"action": "states:ListMapRuns", "types": ["execution"], "resources": [{"types": ["execution"], "arn": "executionArn"}]},
+ "states:ListStateMachineAliases": {"action": "states:ListStateMachineAliases", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn"}]},
+ "states:ListStateMachineVersions": {"action": "states:ListStateMachineVersions", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn"}]},
+ "states:ListStateMachines": {"action": "states:ListStateMachines", "types": [], "resources": []},
+ "states:ListTagsForResource": {"action": "states:ListTagsForResource", "types": ["activity", "statemachine"], "resources": [{"types": ["activity", "statemachine"], "arn": "resourceArn"}]},
+ "states:PublishStateMachineVersion": {"action": "states:PublishStateMachineVersion", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn"}]},
+ "states:RedriveExecution": {"action": "states:RedriveExecution", "types": ["execution"], "resources": [{"types": ["execution"], "arn": "executionArn"}]},
+ "states:SendTaskFailure": {"action": "states:SendTaskFailure", "types": [], "resources": []},
+ "states:SendTaskHeartbeat": {"action": "states:SendTaskHeartbeat", "types": [], "resources": []},
+ "states:SendTaskSuccess": {"action": "states:SendTaskSuccess", "types": [], "resources": []},
+ "states:StartExecution": {"action": "states:StartExecution", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}], "creates": [{"type": "execution", "parent": "statemachine", "arn": "stateMachineArn"}]},
+ "states:StartSyncExecution": {"action": "states:StartSyncExecution", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}], "creates": [{"type": "execution", "parent": "statemachine", "arn": "stateMachineArn"}]},
+ "states:StopExecution": {"action": "states:StopExecution", "types": ["execution"], "resources": [{"types": ["execution"], "arn": "executionArn"}]},
+ "states:TagResource": {"action": "states:TagResource", "types": ["activity", "statemachine"], "resources": [{"types": ["activity", "statemachine"], "arn": "resourceArn"}]},
+ "states:TestState": {"action": "states:TestState", "types": [], "resources": []},
+ "states:UntagResource": {"action": "states:UntagResource", "types": ["activity", "statemachine"], "resources": [{"types": ["activity", "statemachine"], "arn": "resourceArn"}]},
+ "states:UpdateMapRun": {"action": "states:UpdateMapRun", "types": ["maprun"], "resources": [{"types": ["maprun"], "arn": "mapRunArn"}]},
+ "states:UpdateStateMachine": {"action": "states:UpdateStateMachine", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "roleArn"}, {"types": ["statemachine"], "arn": "stateMachineArn"}]},
+ "states:UpdateStateMachineAlias": {"action": "states:UpdateStateMachineAlias", "types": ["statemachine"], "resources": [{"types": ["statemachine"], "arn": "stateMachineAliasArn"}]},
+ "states:ValidateStateMachineDefinition": {"action": "states:ValidateStateMachineDefinition", "types": [], "resources": []}
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
index e3ec1a336a..cb07caa59f 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java
@@ -104,7 +104,7 @@ class IamEnforcementFilterTest {
when(services.iam()).thenReturn(iamConfig);
when(iamConfig.enforcementEnabled()).thenReturn(true);
when(config.defaultRegion()).thenReturn("us-east-1");
- when(arnBuilder.buildResources(any(), any(), any(), any())).thenReturn(List.of("*"));
+ when(arnBuilder.buildResources(any(), any(), any(), any(), any(), any())).thenReturn(List.of("*"));
when(arnBuilder.build(any(), any(), any(), any())).thenReturn("*");
// Default: scopes are already canonical. Alias handling is asserted explicitly below.
when(catalog.canonicalCredentialScope(anyString())).thenAnswer(inv -> inv.getArgument(0));
@@ -168,7 +168,7 @@ class IamEnforcementFilterTest {
{"Effect":"Allow","Action":"lambda:InvokeFunction",
"Resource":"arn:aws:lambda:us-east-1:222233334444:function:fn"}
]}""")));
- when(arnBuilder.buildResources("lambda", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("lambda"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:lambda:us-east-1:222233334444:function:fn"));
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -185,7 +185,7 @@ class IamEnforcementFilterTest {
filter.filter(containerRequest);
- verify(arnBuilder).buildResources("lambda", containerRequest, "us-east-1", "222233334444");
+ verify(arnBuilder).buildResources(eq("lambda"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws"));
}
@Test
@@ -207,7 +207,7 @@ class IamEnforcementFilterTest {
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::mybucket/obj"}
]}""")));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::mybucket/obj"));
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -252,7 +252,7 @@ class IamEnforcementFilterTest {
{"Effect":"Allow","Action":"s3:GetObject",
"Resource":"arn:aws:s3:::mybucket/obj"}
]}""")));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::mybucket/obj"));
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -287,7 +287,7 @@ class IamEnforcementFilterTest {
// Resolve for the serving service only. Left unstubbed the filter would leave through its
// permissive unknown-action branch and the deny below would never be reached.
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:PutItem");
- when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
+ when(arnBuilder.buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws")))
.thenReturn(List.of("*"));
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq("dynamodb:PutItem"), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
@@ -417,8 +417,7 @@ class IamEnforcementFilterTest {
verify(actionRegistry).resolveRoute("apigateway", containerRequest);
verify(actionRegistry, never()).resolveRoute("iam", containerRequest);
- verify(arnBuilder).buildResources("apigateway", containerRequest,
- "us-east-1", "000000000000");
+ verify(arnBuilder).buildResources(eq("apigateway"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws"));
verify(conditionContextResolver).resolve("apigateway", "apigateway:POST", containerRequest);
}
@@ -494,8 +493,7 @@ class IamEnforcementFilterTest {
verify(actionRegistry).queryAction(containerRequest);
verify(actionRegistry, never()).resolve("lambda", containerRequest);
- verify(arnBuilder).buildResources("iam", containerRequest,
- "us-east-1", "000000000000");
+ verify(arnBuilder).buildResources(eq("iam"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws"));
verify(conditionContextResolver).resolve("iam", "iam:CreateUser", containerRequest);
}
@@ -520,8 +518,7 @@ class IamEnforcementFilterTest {
verify(actionRegistry).queryAction(containerRequest);
verify(actionRegistry, never()).resolve("lambda", containerRequest);
- verify(arnBuilder).buildResources("iam", containerRequest,
- "us-east-1", "000000000000");
+ verify(arnBuilder).buildResources(eq("iam"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws"));
verify(conditionContextResolver).resolve("iam", "iam:CreateUser", containerRequest);
}
@@ -1159,7 +1156,7 @@ class IamEnforcementFilterTest {
{"Effect":"Allow","Action":"dynamodb:GetItem",
"Resource":"arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable"}
]}""")));
- when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
+ when(arnBuilder.buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws")))
.thenReturn(List.of("arn:aws:dynamodb:us-east-1:000000000000:table/FgacTable"));
when(evaluator.evaluateResolvedResourcePolicy(
any(),
@@ -1176,7 +1173,7 @@ class IamEnforcementFilterTest {
filter.filter(containerRequest);
- verify(arnBuilder).buildResources("dynamodb", containerRequest, "us-east-1", "000000000000");
+ verify(arnBuilder).buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws"));
verify(containerRequest, never()).abortWith(any());
}
@@ -1194,7 +1191,7 @@ class IamEnforcementFilterTest {
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:BatchGetItem");
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
.thenReturn(CallerContext.of(List.of("{}")));
- when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
+ when(arnBuilder.buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws")))
.thenReturn(List.of(
"arn:aws:dynamodb:us-east-1:000000000000:table/TableA",
"arn:aws:dynamodb:us-east-1:000000000000:table/TableB"
@@ -1252,7 +1249,7 @@ class IamEnforcementFilterTest {
when(actionRegistry.resolve("dynamodb", containerRequest)).thenReturn("dynamodb:BatchGetItem");
when(iamService.resolveCallerContext(eq("ASIASESSION"), any()))
.thenReturn(CallerContext.of(List.of("{}")));
- when(arnBuilder.buildResources("dynamodb", containerRequest, "us-east-1", "000000000000"))
+ when(arnBuilder.buildResources(eq("dynamodb"), any(), eq(containerRequest), eq("us-east-1"), eq("000000000000"), eq("aws")))
.thenReturn(List.of(
"arn:aws:dynamodb:us-east-1:000000000000:table/TableA",
"arn:aws:dynamodb:us-east-1:000000000000:table/TableB"
@@ -1481,7 +1478,7 @@ class IamEnforcementFilterTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
]}""")));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::bucket"));
when(conditionContextResolver.resolve("s3", "s3:ListBucket", containerRequest))
.thenReturn(conditions);
@@ -1528,7 +1525,7 @@ class IamEnforcementFilterTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
]}""")));
- when(arnBuilder.buildResources(eq("s3"), eq(containerRequest), anyString(), anyString()))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), anyString(), anyString(), anyString()))
.thenReturn(List.of("arn:aws:s3:::bucket/key"));
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
@@ -1537,7 +1534,7 @@ class IamEnforcementFilterTest {
// Everything keyed by scope must see the canonical name, not the alias.
verify(actionRegistry).resolve("s3", containerRequest);
- verify(arnBuilder).buildResources(eq("s3"), eq(containerRequest), anyString(), anyString());
+ verify(arnBuilder).buildResources(eq("s3"), any(), eq(containerRequest), anyString(), anyString(), anyString());
verify(conditionContextResolver).resolve("s3", "s3:GetObject", containerRequest);
// The policy above grants only s3:PutObject, so a GetObject signed as s3express is denied.
verify(containerRequest).abortWith(any(Response.class));
@@ -1624,7 +1621,7 @@ class IamEnforcementFilterTest {
when(actionRegistry.resolve("organizations", containerRequest))
.thenReturn("organizations:DescribeOrganization");
when(iamService.resolveCallerContext(eq(account), any())).thenReturn(null);
- when(arnBuilder.buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
+ when(arnBuilder.buildResources(eq("organizations"), any(), eq(containerRequest), eq("us-east-1"), eq(account), eq("aws")))
.thenReturn(List.of("*"));
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
.thenReturn(null);
@@ -1642,7 +1639,7 @@ class IamEnforcementFilterTest {
// arnBuilder.buildResources sits after the caller-resolution branch, so it only fires for a request
// that was actually evaluated. Without this, the never()-abort assertion would also pass on
// a bypass, making it no stronger than the pre-fix behavior.
- verify(arnBuilder).buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account));
+ verify(arnBuilder).buildResources(eq("organizations"), any(), eq(containerRequest), eq("us-east-1"), eq(account), eq("aws"));
}
// The realistic baseline guardrail from .temp/org-functional-test.sh: DenyLeaveOrg plus a
@@ -1825,7 +1822,7 @@ class IamEnforcementFilterTest {
.thenReturn(CallerContext.of(List.of(ALLOW_IF_IAM_USER_PRINCIPAL)));
String userArn = "arn:aws:iam::" + account + ":user/bob";
when(iamService.resolveCallerArns(akid)).thenReturn(Optional.of(new CallerArns(userArn, userArn)));
- when(arnBuilder.buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account)))
+ when(arnBuilder.buildResources(eq("organizations"), any(), eq(containerRequest), eq("us-east-1"), eq(account), eq("aws")))
.thenReturn(List.of("*"));
when(conditionContextResolver.resolve(eq("organizations"), anyString(), eq(containerRequest)))
.thenReturn(null);
@@ -1838,7 +1835,7 @@ class IamEnforcementFilterTest {
// aws:PrincipalArn matches arn:aws:iam::*:user/* → the conditional Allow grants access.
verify(containerRequest, never()).abortWith(any());
- verify(arnBuilder).buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account));
+ verify(arnBuilder).buildResources(eq("organizations"), any(), eq(containerRequest), eq("us-east-1"), eq(account), eq("aws"));
}
@Test
@@ -1889,7 +1886,7 @@ class IamEnforcementFilterTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
]}""")));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
.thenReturn(null);
@@ -1925,7 +1922,7 @@ class IamEnforcementFilterTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
]}""")));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
.thenReturn(null);
@@ -1960,7 +1957,7 @@ class IamEnforcementFilterTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
]}""")));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
.thenReturn(null);
@@ -2183,7 +2180,7 @@ class IamEnforcementFilterTest {
when(containerRequest.getHeaderString("x-amz-bypass-governance-retention")).thenReturn("true");
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:DeleteObjectVersion");
when(iamService.resolveCallerContext(eq("AKIABYPASS"), any())).thenReturn(CallerContext.of(List.of()));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::bucket/object"));
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
@@ -2216,7 +2213,7 @@ class IamEnforcementFilterTest {
when(containerRequest.getHeaderString(header)).thenReturn(headerValue);
when(actionRegistry.resolve("s3", containerRequest)).thenReturn(allowedAction);
when(iamService.resolveCallerContext(eq("AKIAEXTRA"), any())).thenReturn(CallerContext.of(List.of()));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::bucket/object"));
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(allowedAction), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
@@ -2258,7 +2255,7 @@ class IamEnforcementFilterTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:ListBucket","Resource":"*"}
]}""")));
- when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
+ when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), eq("us-east-1"), eq("222233334444"), eq("aws")))
.thenReturn(List.of("arn:aws:s3:::partner-bucket"));
when(conditionContextResolver.resolve("s3", "s3:ListBucket", containerRequest))
.thenReturn(conditions);
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java
new file mode 100644
index 0000000000..ec81a143ca
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java
@@ -0,0 +1,241 @@
+package io.github.hectorvent.floci.core.common;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.github.hectorvent.floci.core.common.RequestResourceMembers.ArnFormat;
+import io.github.hectorvent.floci.core.common.RequestResourceMembers.Member;
+import io.github.hectorvent.floci.core.common.RequestResourceMembers.Resource;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.core.MediaType;
+import org.junit.jupiter.api.DynamicTest;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestFactory;
+
+import java.io.ByteArrayInputStream;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The vendored table of the resources each operation's request names, and that {@link RequestResources} reads every
+ * resource it gives, from a JSON body and from Query form parameters.
+ */
+class RequestResourceMembersTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ @Test
+ void theTableReadsItsNamespacesAndGivesEachTypeItNamesAnArnFormat() {
+ RequestResourceMembers.Table table = RequestResourceMembers.table();
+ assertTrue(table.namespaces().containsAll(List.of("cognito-idp", "ecr", "elasticloadbalancing", "states")));
+ assertTrue(table.handBuilt().contains("lambda"));
+ assertTrue(table.namespaces().stream().noneMatch(table.handBuilt()::contains));
+ assertTrue(table.namespaces().stream().noneMatch(table.notCovered()::contains));
+ assertTrue(table.otherNamespaces().stream().noneMatch(table.notCovered()::contains));
+ table.operations().forEach((operation, resources) -> {
+ Map<String, ArnFormat> formats = table.formats().get(operation.substring(0, operation.indexOf(':')));
+ resources.forEach(resource -> assertTrue(formats.keySet().containsAll(resource.types()), operation));
+ });
+ }
+
+ @Test
+ void anArnFormatMatchesAnArnOfItsTypeAndNoOther() {
+ ArnFormat group = format("arn:${Partition}:elasticloadbalancing:${Region}:${Account}:targetgroup/${TargetGroupName}/${TargetGroupId}");
+ assertTrue(group.pattern().matcher("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web/abc").matches());
+ assertTrue(group.pattern().matcher("arn:aws-cn:elasticloadbalancing:cn-north-1:000000000000:targetgroup/a/b").matches());
+ assertFalse(group.pattern().matcher("arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/a/b").matches());
+ assertFalse(group.pattern().matcher("arn:aws:iam::000000000000:role/targetgroup/a/b").matches());
+ assertFalse(group.pattern().matcher("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup//b").matches());
+ }
+
+ @Test
+ void anUnqualifiedTypesArnIsCheckedWithoutItsQualifier() {
+ String machine = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
+ String format = "arn:${Partition}:states:${Region}:${Account}:stateMachine:${StateMachineName}";
+ ArnFormat unqualified = new ArnFormat(format, RequestResourceMembers.pattern(format), true);
+ assertEquals(machine, unqualified.checked(machine + ":PROD"));
+ assertEquals(machine, unqualified.checked(machine));
+ assertEquals(machine + ":PROD", format(unqualified.format()).checked(machine + ":PROD"));
+ assertTrue(RequestResourceMembers.table().formats().get("states").get("statemachine").unqualified());
+ assertFalse(RequestResourceMembers.table().formats().get("states").get("execution").unqualified());
+ }
+
+ @Test
+ void aMalformedTableFailsToLoad() {
+ assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{}}"));
+ // An operation of a namespace the file does not read.
+ assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]},\"arnFormats\":{},"
+ + "\"operations\":{\"b:Op\":{\"resources\":[]}}}"));
+ // A type with no format, a variable the format does not have, a member that is no member.
+ String formats = "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${ThingName}\"}}";
+ assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"types\":[\"other\"],\"arn\":\"Arn\"}")));
+ assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"type\":\"thing\",\"fill\":{\"Other\":\"Name\"}}")));
+ assertThrows(IllegalStateException.class, () -> parse(document(formats, "{\"types\":[\"thing\"],\"arn\":\"a.b\"}")));
+ assertThrows(IllegalStateException.class, () -> parse(
+ "{\"namespaces\":{\"a\":[]},\"arnFormats\":{\"a\":{\"thing\":\"*\"}},\"operations\":{\"a:Op\":{\"resources\":[]}}}"));
+ // A type made under a parent whose format it does not extend by one id.
+ for (String part : List.of("part/${PartName}", "part/${ThingName}/${A}/${B}", "thing/${ThingName}/${PartId}")) {
+ assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]},\"arnFormats\":{\"a\":{"
+ + "\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${ThingName}\","
+ + "\"part\":\"arn:${Partition}:a:${Region}:${Account}:" + part + "\"}},\"operations\":{\"a:Op\":"
+ + "{\"resources\":[],\"creates\":[{\"type\":\"part\",\"parent\":\"thing\",\"arn\":\"ThingArn\"}]}}}"),
+ part);
+ }
+ // An ARN read before more than one character.
+ assertThrows(IllegalStateException.class, () -> parse(document(formats,
+ "{\"types\":[\"thing\"],\"arn\":\"ThingArn\",\"before\":\"##\"}")));
+ // An account from a list, or for a type whose format has no account.
+ assertThrows(IllegalStateException.class, () -> parse(document(formats,
+ "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"account\":\"Ids[]\"}")));
+ assertThrows(IllegalStateException.class, () -> parse(document(
+ "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:::thing/${ThingName}\"}}",
+ "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"account\":\"registryId\"}")));
+ // A type checked without a qualifier that has no format, or not given as a list.
+ assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]}," + formats
+ + ",\"unqualified\":{\"a\":[\"other\"]},\"operations\":{\"a:Op\":{\"resources\":[]}}}"));
+ assertThrows(IllegalStateException.class, () -> parse("{\"namespaces\":{\"a\":[]}," + formats
+ + ",\"unqualified\":{\"a\":\"thing\"},\"operations\":{\"a:Op\":{\"resources\":[]}}}"));
+ assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Names", true)), Map.of(),
+ new Member("registryId", false), null)),
+ parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Names[]\"},"
+ + "\"account\":\"registryId\"}")).operations().get("a:Op"));
+ }
+
+ /**
+ * Each resource alone, from a request naming it and nothing else, gives exactly its ARN, in the account its
+ * account member names when it has one.
+ */
+ @TestFactory
+ Stream<DynamicTest> everyResourceOfTheTableIsReadFromAJsonBodyAndAForm() {
+ RequestResourceMembers.Table table = RequestResourceMembers.table();
+ return table.operations().entrySet().stream().flatMap(operation -> operation.getValue().stream()
+ .map(resource -> DynamicTest.dynamicTest(operation.getKey() + " " + resource, () -> {
+ String namespace = operation.getKey().substring(0, operation.getKey().indexOf(':'));
+ String name = operation.getKey().substring(namespace.length() + 1);
+ ArnFormat format = table.formats().get(namespace).get(resource.types().getFirst());
+ String arn = example(format.format());
+ String account = resource.account() != null ? "111122223333" : "000000000000";
+ String expected = resource.arn() != null ? arn : expected(format.format(), resource, account);
+ ObjectNode body = MAPPER.createObjectNode();
+ StringBuilder form = new StringBuilder("Action=" + name);
+ Map<Member, String> values = resource.arn() != null ? Map.of(resource.arn(), arn)
+ : resource.fill().values().stream().distinct().collect(Collectors.toMap(m -> m, m -> "x"));
+ Map<Member, String> given = new LinkedHashMap<>(values);
+ if (resource.account() != null) {
+ given.put(resource.account(), account);
+ }
+ resource.when().forEach((member, allowed) -> {
+ if (!allowed.getFirst().isEmpty()) {
+ given.put(new Member(member, false), allowed.getFirst());
+ }
+ });
+ given.forEach((member, value) -> {
+ if (member.list()) {
+ body.putArray(member.name()).add(value);
+ form.append('&').append(member.name()).append(".member.1=").append(encoded(value));
+ } else {
+ body.put(member.name(), value);
+ form.append('&').append(member.name()).append('=').append(encoded(value));
+ }
+ });
+ assertEquals(List.of(expected), RequestResources.of(operation.getKey(), json(body.toString()),
+ "aws", "us-east-1", "000000000000"), body.toString());
+ assertEquals(List.of(expected), RequestResources.of(operation.getKey(), form(form.toString()),
+ "aws", "us-east-1", "000000000000"), form.toString());
+ })));
+ }
+
+ /** Each resource a create makes under a parent, from a request naming the parent's ARN, is the parent's own. */
+ @TestFactory
+ Stream<DynamicTest> everyResourceACreateMakesIsNamedFromItsParentsArn() {
+ RequestResourceMembers.Table table = RequestResourceMembers.table();
+ return table.creates().entrySet().stream().flatMap(operation -> operation.getValue().stream()
+ .map(created -> DynamicTest.dynamicTest(operation.getKey() + " " + created.type(), () -> {
+ String namespace = operation.getKey().substring(0, operation.getKey().indexOf(':'));
+ String name = operation.getKey().substring(namespace.length() + 1);
+ String parent = example(table.formats().get(namespace).get(created.parent()).format());
+ String child = example(table.formats().get(namespace).get(created.type()).format());
+ String expected = child.substring(0, child.length() - 1) + "*";
+ ObjectNode body = MAPPER.createObjectNode();
+ if (created.arn().list()) {
+ body.putArray(created.arn().name()).add(parent);
+ } else {
+ body.put(created.arn().name(), parent);
+ }
+ String form = "Action=" + name + "&" + created.arn().name() + (created.arn().list() ? ".member.1=" : "=")
+ + encoded(parent);
+ assertTrue(RequestResources.created(operation.getKey(), json(body.toString()), "aws",
+ "us-east-1", "000000000000").contains(expected), body.toString());
+ assertTrue(RequestResources.created(operation.getKey(), form(form), "aws", "us-east-1",
+ "000000000000").contains(expected), form);
+ })));
+ }
+
+ /** An ARN of the format in the test's partition, Region and account, each other variable {@code x}. */
+ private static String example(String format) {
+ return format.replace("${Partition}", "aws").replace("${Region}", "us-east-1")
+ .replace("${Account}", "000000000000").replaceAll("\\$\\{\\w+}", "x");
+ }
+
+ /** The format in the account with each variable the resource fills {@code x}, and each other open. */
+ private static String expected(String format, Resource resource, String account) {
+ String arn = format.replace("${Partition}", "aws").replace("${Region}", "us-east-1")
+ .replace("${Account}", account);
+ for (String variable : resource.fill().keySet()) {
+ arn = arn.replace("${" + variable + "}", "x");
+ }
+ return arn.replaceAll("\\$\\{\\w+}", "*");
+ }
+
+ private static ArnFormat format(String format) {
+ return new ArnFormat(format, RequestResourceMembers.pattern(format), false);
+ }
+
+ private static String document(String formats, String resource) {
+ return "{\"namespaces\":{\"a\":[]}," + formats + ",\"operations\":{\"a:Op\":{\"resources\":[" + resource + "]}}}";
+ }
+
+ private static RequestResourceMembers.Table parse(String document) throws Exception {
+ return RequestResourceMembers.parse(new ByteArrayInputStream(document.getBytes(StandardCharsets.UTF_8)));
+ }
+
+ private static RequestResourceMembers.Table parseUnchecked(String document) {
+ try {
+ return parse(document);
+ } catch (Exception e) {
+ throw new AssertionError(e);
+ }
+ }
+
+ private static String encoded(String value) {
+ return URLEncoder.encode(value, StandardCharsets.UTF_8);
+ }
+
+ private static ContainerRequestContext json(String body) {
+ return request("application/x-amz-json-1.1", body);
+ }
+
+ private static ContainerRequestContext form(String body) {
+ return request("application/x-www-form-urlencoded", body);
+ }
+
+ private static ContainerRequestContext request(String mediaType, String body) {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ ContainerRequestContext request = mock(ContainerRequestContext.class);
+ when(request.getMethod()).thenReturn("POST");
+ when(request.getMediaType()).thenReturn(MediaType.valueOf(mediaType));
+ when(request.getEntityStream()).thenAnswer(invocation -> new ByteArrayInputStream(bytes));
+ return request;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceNamespacesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceNamespacesIntegrationTest.java
new file mode 100644
index 0000000000..9715b99aeb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceNamespacesIntegrationTest.java
@@ -0,0 +1,35 @@
+package io.github.hectorvent.floci.core.common;
+
+import io.quarkus.test.junit.QuarkusTest;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.Test;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Every IAM namespace Floci serves whose actions the Service Reference gives resource types is one the vendored
+ * table of request resources reads, one whose resources {@code ResourceArnBuilder} builds by hand, or one the table
+ * names as not read yet, so a service Floci adds is not left checking its resources on {@code *} unnoticed.
+ */
+@QuarkusTest
+class RequestResourceNamespacesIntegrationTest {
+
+ @Inject
+ ResolvedServiceCatalog catalog;
+
+ @Test
+ void everyNamespaceFlociServesWithResourceTypesIsReadBuiltByHandOrNamedAsNotReadYet() {
+ Set<String> served = new TreeSet<>();
+ for (ServiceDescriptor descriptor : catalog.all()) {
+ for (String scope : descriptor.credentialScopes()) {
+ served.add(catalog.canonicalCredentialScope(scope));
+ }
+ }
+ Set<String> unread = new TreeSet<>(served);
+ unread.retainAll(RequestResourceMembers.table().otherNamespaces());
+ assertEquals(Set.of(), unread, "add these to NAMESPACES or NOT_COVERED in tools/aws/regen_iam_request_resources.py");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourcesTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourcesTest.java
new file mode 100644
index 0000000000..eacbb963bb
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourcesTest.java
@@ -0,0 +1,259 @@
+package io.github.hectorvent.floci.core.common;
+
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.core.MediaType;
+import org.junit.jupiter.api.Test;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/** How {@link RequestResources} builds the ARNs of the resources a request names. */
+class RequestResourcesTest {
+
+ private static final String MACHINE = "arn:aws:states:us-east-1:000000000000:stateMachine:orders";
+
+ @Test
+ void aMemberHoldingAnArnOfATypeTheActionActsOnNamesThatResource() {
+ assertEquals(List.of(MACHINE), of("states:DescribeStateMachine",
+ json("{\"stateMachineArn\":\"" + MACHINE + "\"}")));
+ }
+
+ /** {@code CreateStateMachine}'s {@code roleArn} is an IAM role, no resource of Step Functions. */
+ @Test
+ void anArnOfAnotherTypeIsNotChecked() {
+ assertEquals(List.of(MACHINE), of("states:CreateStateMachine", json(
+ "{\"name\":\"orders\",\"roleArn\":\"arn:aws:iam::000000000000:role/sfn\",\"definition\":\"{}\"}")));
+ }
+
+ /**
+ * A handler may act on the resource the ARN names or on one of that name in the caller's account or the
+ * request's Region, or both (ECR's tag handlers keep the ARN's account in the request's Region), so each is
+ * checked.
+ */
+ @Test
+ void anArnOfAnotherAccountOrRegionIsCheckedAsGivenAndAsTheCallersOwn() {
+ String other = "arn:aws:states:eu-west-1:111122223333:stateMachine:orders";
+ assertEquals(List.of(other, "arn:aws:states:us-east-1:111122223333:stateMachine:orders",
+ "arn:aws:states:eu-west-1:000000000000:stateMachine:orders", MACHINE), of("states:DescribeStateMachine",
+ json("{\"stateMachineArn\":\"" + other + "\"}")));
+ assertEquals(List.of("arn:aws:ecr:eu-west-1:111122223333:repository/web",
+ "arn:aws:ecr:us-east-1:111122223333:repository/web", "arn:aws:ecr:eu-west-1:000000000000:repository/web",
+ "arn:aws:ecr:us-east-1:000000000000:repository/web"), of("ecr:TagResource",
+ json("{\"resourceArn\":\"arn:aws:ecr:eu-west-1:111122223333:repository/web\",\"tags\":[]}")));
+ }
+
+ @Test
+ void aTypesVariablesAreFilledFromTheRequestAndAListGivesAResourceForEachValue() {
+ assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web",
+ "arn:aws:ecr:us-east-1:000000000000:repository/api"), of("ecr:DescribeRepositories", json(
+ "{\"repositoryNames\":[\"web\",\"api\"]}")));
+ assertEquals(List.of("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_abc"),
+ of("cognito-idp:DescribeUserPool", json("{\"UserPoolId\":\"us-east-1_abc\"}")));
+ }
+
+ /** A value that is itself an ARN of the type names that resource. */
+ @Test
+ void aValueThatIsAnArnOfTheTypeNamesItsResource() {
+ assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web"), of("ecr:DescribeRepositories", json(
+ "{\"repositoryNames\":[\"arn:aws:ecr:us-east-1:000000000000:repository/web\"]}")));
+ }
+
+ /** The service mints a new target group's id, so it is open. */
+ @Test
+ void aVariableTheRequestDoesNotFillIsOpen() {
+ assertEquals(List.of("arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web/*"),
+ of("elasticloadbalancing:CreateTargetGroup",
+ form("Action=CreateTargetGroup&Name=web&Protocol=HTTP&Port=80")));
+ }
+
+ /** A v2 load balancer's type, application when none is given, picks the ARN it is created under. */
+ @Test
+ void aLoadBalancerIsCreatedUnderTheArnOfItsType() {
+ String prefix = "arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/";
+ assertEquals(List.of(prefix + "app/web/*"), of("elasticloadbalancing:CreateLoadBalancer",
+ form("Action=CreateLoadBalancer&Name=web")));
+ assertEquals(List.of(prefix + "net/web/*"), of("elasticloadbalancing:CreateLoadBalancer",
+ form("Action=CreateLoadBalancer&Name=web&Type=network")));
+ assertEquals(List.of(prefix + "gwy/web/*"), of("elasticloadbalancing:CreateLoadBalancer",
+ form("Action=CreateLoadBalancer&Name=web&Type=gateway")));
+ assertEquals(List.of(), of("elasticloadbalancing:CreateLoadBalancer",
+ form("Action=CreateLoadBalancer&Name=web&Type=other")));
+ // The classic API names it by LoadBalancerName.
+ assertEquals(List.of(prefix + "classic"), of("elasticloadbalancing:CreateLoadBalancer",
+ form("Action=CreateLoadBalancer&LoadBalancerName=classic&Listeners.member.1.Protocol=HTTP")));
+ }
+
+ /**
+ * A listener is made under a load balancer, and a rule under a listener: their ARNs are the parent's with its
+ * type word replaced and their own id open, of the parent's type.
+ */
+ @Test
+ void aResourceCreatedUnderAParentIsNamedFromTheParentsArn() {
+ String prefix = "arn:aws:elasticloadbalancing:us-east-1:000000000000:";
+ assertEquals(List.of(prefix + "listener/app/web/abc/*"), created("elasticloadbalancing:CreateListener", form(
+ "Action=CreateListener&LoadBalancerArn=" + prefix + "loadbalancer/app/web/abc&Protocol=HTTP&Port=80")));
+ assertEquals(List.of(prefix + "listener/net/web/abc/*"), created("elasticloadbalancing:CreateListener", form(
+ "Action=CreateListener&LoadBalancerArn=" + prefix + "loadbalancer/net/web/abc&Protocol=TCP&Port=80")));
+ assertEquals(List.of(prefix + "listener-rule/app/web/abc/def/*"), created("elasticloadbalancing:CreateRule",
+ form("Action=CreateRule&ListenerArn=" + prefix + "listener/app/web/abc/def&Priority=1")));
+ // A parent of another account is named as given and as the caller's own.
+ assertEquals(List.of("arn:aws:elasticloadbalancing:us-east-1:111122223333:listener/app/web/abc/*",
+ prefix + "listener/app/web/abc/*"), created("elasticloadbalancing:CreateListener", form(
+ "Action=CreateListener&LoadBalancerArn=arn:aws:elasticloadbalancing:us-east-1:111122223333:"
+ + "loadbalancer/app/web/abc")));
+ // An ARN of no parent, a create of a type its action acts on, and no create name nothing.
+ assertEquals(List.of(), created("elasticloadbalancing:CreateListener",
+ form("Action=CreateListener&LoadBalancerArn=" + prefix + "targetgroup/web/abc")));
+ assertEquals(List.of(), created("elasticloadbalancing:CreateTargetGroup",
+ form("Action=CreateTargetGroup&Name=web")));
+ assertEquals(List.of(), created("elasticloadbalancing:DeleteListener",
+ form("Action=DeleteListener&ListenerArn=" + prefix + "listener/app/web/abc/def")));
+ }
+
+ /**
+ * The operation is the one the request is dispatched as: an {@code X-Amz-Target} or {@code Action} naming
+ * another, whose members name an allowed resource, does not change what it is checked on.
+ */
+ @Test
+ void theOperationIsTheOneTheRequestIsDispatchedAsNotOneTheRequestNames() {
+ ContainerRequestContext request = json("{\"name\":\"allowed\",\"stateMachineArn\":\"" + MACHINE + "\"}");
+ when(request.getHeaderString("X-Amz-Target")).thenReturn("AWSStepFunctions.CreateStateMachine");
+ assertEquals(List.of(MACHINE), of("states:DescribeStateMachine", request));
+ String group = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/web/1";
+ assertEquals(List.of(group), of("elasticloadbalancing:DeleteTargetGroup",
+ form("Action=CreateTargetGroup&Name=allowed&TargetGroupArn=" + group)));
+ assertEquals(List.of(), created("elasticloadbalancing:DeleteLoadBalancer", form("Action=CreateListener"
+ + "&LoadBalancerArn=arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/web/abc")));
+ }
+
+ @Test
+ void aFormsListIsReadFromOneToTheFirstMissingNumber() {
+ String first = "arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/a/1";
+ String second = "arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/app/b/2";
+ assertEquals(List.of(first, second), of("elasticloadbalancing:AddTags", form("Action=AddTags"
+ + "&ResourceArns.member.1=" + first + "&ResourceArns.member.2=" + second
+ + "&ResourceArns.member.4=arn:aws:elasticloadbalancing:us-east-1:000000000000:targetgroup/c/3"
+ + "&Tags.member.1.Key=team")));
+ // A classic load balancer goes by its name.
+ assertEquals(List.of("arn:aws:elasticloadbalancing:us-east-1:000000000000:loadbalancer/classic"),
+ of("elasticloadbalancing:DeleteLoadBalancer",
+ form("Action=DeleteLoadBalancer&LoadBalancerName=classic")));
+ }
+
+ /**
+ * A member is read as its handler reads it: a list only from a list, so a single name for one gives none, as
+ * ECR's handler then lists every repository, a number, boolean or null as its text, and a structure as none.
+ */
+ @Test
+ void aMemberIsReadAsItsHandlerReadsIt() {
+ assertEquals(List.of(), of("ecr:DescribeRepositories", json("{\"repositoryNames\":\"allowed\"}")));
+ assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/123",
+ "arn:aws:ecr:us-east-1:000000000000:repository/null"),
+ of("ecr:DescribeRepositories", json("{\"repositoryNames\":[123,{\"a\":1},null]}")));
+ assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/7"),
+ of("ecr:DeleteRepository", json("{\"repositoryName\":7}")));
+ assertEquals(List.of(), of("ecr:DeleteRepository", json("{\"repositoryName\":[\"web\"]}")));
+ }
+
+ /**
+ * ECR's {@code registryId} selects the registry its handler acts in, so the repositories are that account's;
+ * one that is no account id names none.
+ */
+ @Test
+ void aRepositoryIsInTheRegistryTheRequestNames() {
+ assertEquals(List.of("arn:aws:ecr:us-east-1:111122223333:repository/web"), of("ecr:DescribeRepositories",
+ json("{\"registryId\":\"111122223333\",\"repositoryNames\":[\"web\"]}")));
+ assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web"), of("ecr:DescribeRepositories",
+ json("{\"repositoryNames\":[\"web\"]}")));
+ assertEquals(List.of(), of("ecr:DescribeRepositories",
+ json("{\"registryId\":\"1:2\",\"repositoryNames\":[\"web\"]}")));
+ // A JSON null is no registry, as ECR reads it: the caller's.
+ assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web"), of("ecr:DescribeRepositories",
+ json("{\"registryId\":null,\"repositoryNames\":[\"web\"]}")));
+ // The scanning configuration's request has no registryId: its repositories are the caller's.
+ assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/web"),
+ of("ecr:BatchGetRepositoryScanningConfiguration",
+ json("{\"registryId\":\"111122223333\",\"repositoryNames\":[\"web\"]}")));
+ }
+
+ /**
+ * {@code StartExecution} takes Step Functions Local's {@code <stateMachineArn>#<test case>} and runs the
+ * machine the part before the {@code #} names, so that machine is checked; other operations read it whole.
+ */
+ @Test
+ void aStateMachinesTestCaseIsCheckedOnTheMachineItRuns() {
+ assertEquals(List.of(MACHINE), of("states:StartExecution",
+ json("{\"stateMachineArn\":\"" + MACHINE + "#HappyPath\"}")));
+ assertEquals(List.of(MACHINE), of("states:StartSyncExecution", json("{\"stateMachineArn\":\"" + MACHINE + "#\"}")));
+ assertEquals(List.of(MACHINE + "#x"), of("states:DescribeStateMachine",
+ json("{\"stateMachineArn\":\"" + MACHINE + "#x\"}")));
+ assertEquals(List.of("arn:aws:states:us-east-1:000000000000:execution:orders:*"), created("states:StartExecution",
+ json("{\"stateMachineArn\":\"" + MACHINE + "#HappyPath\"}")));
+ }
+
+ /**
+ * Step Functions checks a version or an alias on its state machine's ARN, so a request naming one is checked on
+ * the state machine, and an execution it starts is the state machine's; other types keep their ARN whole.
+ */
+ @Test
+ void aVersionOrAnAliasIsCheckedOnItsStateMachine() {
+ assertEquals(List.of(MACHINE), of("states:DescribeStateMachineAlias",
+ json("{\"stateMachineAliasArn\":\"" + MACHINE + ":PROD\"}")));
+ assertEquals(List.of(MACHINE), of("states:DeleteStateMachineVersion",
+ json("{\"stateMachineVersionArn\":\"" + MACHINE + ":3\"}")));
+ assertEquals(List.of(MACHINE), of("states:DescribeStateMachine", json("{\"stateMachineArn\":\"" + MACHINE + ":1\"}")));
+ assertEquals(List.of(MACHINE), of("states:StartExecution",
+ json("{\"stateMachineArn\":\"" + MACHINE + ":PROD#HappyPath\"}")));
+ assertEquals(List.of("arn:aws:states:us-east-1:000000000000:execution:orders:*"), created("states:StartExecution",
+ json("{\"stateMachineArn\":\"" + MACHINE + ":PROD\"}")));
+ String execution = "arn:aws:states:us-east-1:000000000000:execution:orders:run-1";
+ assertEquals(List.of(execution), of("states:DescribeExecution", json("{\"executionArn\":\"" + execution + "\"}")));
+ }
+
+ /** A request value is a name, so a {@code ${...}} in it is kept, not read as a variable of the format. */
+ @Test
+ void aValueIsTakenLiterally() {
+ assertEquals(List.of("arn:aws:ecr:us-east-1:000000000000:repository/${Account}"),
+ of("ecr:DescribeRepositories", json(
+ "{\"repositoryNames\":[\"${Account}\"]}")));
+ }
+
+ @Test
+ void aRequestNamingNoResourceOrOfANamespaceTheTableDoesNotReadIsCheckedOnStar() {
+ assertEquals(List.of(), of("ecr:DescribeRepositories", json("{}")));
+ assertEquals(List.of(), of("ecr:GetAuthorizationToken", json("{}")));
+ assertEquals(List.of(), of("ecr:NoSuchOperation", json("{\"repositoryName\":\"web\"}")));
+ assertEquals(List.of(), of(null, json("{\"repositoryName\":\"web\"}")));
+ assertEquals(List.of(), of("lambda:GetFunction", json("{\"FunctionName\":\"f\"}")));
+ }
+
+ private static List<String> created(String operation, ContainerRequestContext request) {
+ return RequestResources.created(operation, request, "aws", "us-east-1", "000000000000");
+ }
+
+ private static List<String> of(String operation, ContainerRequestContext request) {
+ return RequestResources.of(operation, request, "aws", "us-east-1", "000000000000");
+ }
+
+ private static ContainerRequestContext json(String body) {
+ return request("application/x-amz-json-1.1", body);
+ }
+
+ private static ContainerRequestContext form(String body) {
+ return request("application/x-www-form-urlencoded", body);
+ }
+
+ private static ContainerRequestContext request(String mediaType, String body) {
+ byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
+ ContainerRequestContext request = mock(ContainerRequestContext.class);
+ when(request.getMethod()).thenReturn("POST");
+ when(request.getMediaType()).thenReturn(MediaType.valueOf(mediaType));
+ when(request.getEntityStream()).thenAnswer(invocation -> new ByteArrayInputStream(bytes));
+ return request;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandlerTest.java b/src/test/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandlerTest.java
new file mode 100644
index 0000000000..6085d280e2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ecr/EcrJsonHandlerTest.java
@@ -0,0 +1,33 @@
+package io.github.hectorvent.floci.services.ecr;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** How {@link EcrJsonHandler} reads the requests it hands to {@link EcrService}. */
+class EcrJsonHandlerTest {
+
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ /**
+ * AWS's {@code BatchGetRepositoryScanningConfiguration} request has no {@code registryId}, so the repositories
+ * are the caller's whatever one the request carries, as IAM checks them.
+ */
+ @Test
+ void theScanningConfigurationIsOfTheCallersRepositories() throws Exception {
+ EcrService service = mock(EcrService.class);
+ when(service.describeRepositories(List.of("web"), null, "us-east-1")).thenReturn(List.of());
+ EcrJsonHandler handler = new EcrJsonHandler(service, MAPPER);
+
+ assertEquals(200, handler.handle("BatchGetRepositoryScanningConfiguration",
+ MAPPER.readTree("{\"registryId\":\"111122223333\",\"repositoryNames\":[\"web\"]}"), "us-east-1")
+ .getStatus());
+ verify(service).describeRepositories(List.of("web"), null, "us-east-1");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java
index 84c1265250..4e346267e6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/elbv2/ElbV2ServiceTest.java
@@ -149,6 +149,23 @@ class ElbV2ServiceTest {
verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());
}
+ /**
+ * A {@code Type} outside the model's enum is refused, as AWS refuses it, before anything is looked up or
+ * stored, rather than read as an Application Load Balancer.
+ */
+ @ParameterizedTest
+ @ValueSource(strings = {"other", "Application", ""})
+ void aLoadBalancerOfATypeOutsideTheEnumIsRefused(String type) {
+ AwsException refusal = assertThrows(AwsException.class, () -> service.createLoadBalancer(REGION,
+ "unknown-type", null, type, null, List.of("subnet-a", "subnet-b"), List.of(), Map.of()));
+ assertEquals("ValidationError", refusal.getErrorCode());
+ assertEquals("1 validation error detected: Value '" + type + "' at 'type' failed to satisfy constraint: "
+ + "Member must satisfy enum value set: [application, network, gateway]", refusal.getMessage());
+ assertEquals(400, refusal.getHttpStatus());
+ assertTrue(service.describeLoadBalancers(REGION, null, null, null, null).isEmpty());
+ verify(ec2Service, never()).describeSubnets(anyString(), anyList(), any());
+ }
+
/** A Network or Gateway Load Balancer can be in a single Availability Zone. */
@ParameterizedTest
@ValueSource(strings = {"network", "gateway"})
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestResourceEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..61a1a9b473
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestResourceEnforcementIntegrationTest.java
@@ -0,0 +1,456 @@
+package io.github.hectorvent.floci.services.iam;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import io.github.hectorvent.floci.testing.EnforcementFixtures;
+import io.github.hectorvent.floci.testing.IamEnforcementProfile;
+import io.github.hectorvent.floci.testing.PartitionCleanup;
+import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
+import io.quarkus.test.common.http.TestHTTPResource;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.Map;
+
+import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A request of a service whose ARNs the vendored table of request resources gives is checked on the resource it
+ * names, the ARN its handler mints, so a grant scoped to the resource allows it, and the same grant refuses a
+ * request naming another; a deny scoped to the resource holds. Without the table these were checked on {@code *}.
+ */
+@QuarkusTest
+@TestProfile(IamEnforcementProfile.class)
+class IamRequestResourceEnforcementIntegrationTest {
+
+ private static final String ADMIN = "test";
+ private static final String ACCOUNT = "000000000000";
+ private static final String REGION = "us-east-1";
+ private static final String ELB = "arn:aws:elasticloadbalancing:" + REGION + ":" + ACCOUNT + ":";
+ /** The AWS Load Balancer Controller's create, tag-on-create and listener statements (its policy v2.14.0). */
+ private static final String CONTROLLER_CREATE = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:CreateLoadBalancer\","
+ + "\"elasticloadbalancing:CreateTargetGroup\"],\"Resource\":\"*\","
+ + "\"Condition\":{\"Null\":{\"aws:RequestTag/elbv2.k8s.aws/cluster\":\"false\"}}}";
+ private static final String CONTROLLER_LISTENERS = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:CreateListener\","
+ + "\"elasticloadbalancing:DeleteListener\",\"elasticloadbalancing:CreateRule\",\"elasticloadbalancing:DeleteRule\"],"
+ + "\"Resource\":\"*\"}";
+ private static final String CONTROLLER_TAG_LISTENERS = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:AddTags\","
+ + "\"elasticloadbalancing:RemoveTags\"],\"Resource\":[\"arn:aws:elasticloadbalancing:*:*:listener/net/*/*/*\","
+ + "\"arn:aws:elasticloadbalancing:*:*:listener/app/*/*/*\",\"arn:aws:elasticloadbalancing:*:*:listener-rule/net/*/*/*\","
+ + "\"arn:aws:elasticloadbalancing:*:*:listener-rule/app/*/*/*\"]}";
+ private static final String CONTROLLER_TAG_ON_CREATE = "{\"Effect\":\"Allow\",\"Action\":[\"elasticloadbalancing:AddTags\"],"
+ + "\"Resource\":[\"arn:aws:elasticloadbalancing:*:*:targetgroup/*/*\",\"arn:aws:elasticloadbalancing:*:*:loadbalancer/net/*/*\","
+ + "\"arn:aws:elasticloadbalancing:*:*:loadbalancer/app/*/*\"],\"Condition\":{\"StringEquals\":"
+ + "{\"elasticloadbalancing:CreateAction\":[\"CreateTargetGroup\",\"CreateLoadBalancer\"]},"
+ + "\"Null\":{\"aws:RequestTag/elbv2.k8s.aws/cluster\":\"false\"}}}";
+ private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory());
+ private static final String PASS = "{\\\"StartAt\\\":\\\"P\\\",\\\"States\\\":{\\\"P\\\":{\\\"Type\\\":\\\"Pass\\\",\\\"End\\\":true}}}";
+
+ @TestHTTPResource("/")
+ static URI baseUri;
+
+ @RegisterExtension
+ final PartitionCleanup cleanup = new PartitionCleanup();
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void aTargetGroupIsCheckedOnItsArnAndANewOneOnItsName() {
+ String name = "res-tg-" + suffix();
+ String arn = admin("elasticloadbalancing").formParam("Action", "CreateTargetGroup").formParam("Version", "2015-12-01")
+ .formParam("Name", name).formParam("Protocol", "HTTP").formParam("Port", "80").formParam("TargetType", "ip")
+ .post("/").then().statusCode(200).extract()
+ .path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
+ cleanup.register(() -> admin("elasticloadbalancing").formParam("Action", "DeleteTargetGroup")
+ .formParam("Version", "2015-12-01").formParam("TargetGroupArn", arn).post("/"));
+ assertEquals(arn.substring(0, arn.lastIndexOf('/')), "arn:aws:elasticloadbalancing:" + REGION + ":" + ACCOUNT
+ + ":targetgroup/" + name);
+
+ User user = user("res-tg");
+ user.policy(allowOn("elasticloadbalancing:ModifyTargetGroupAttributes", arn));
+ modifyAttributes(user, arn).statusCode(200);
+ refused(modifyAttributes(user, arn + "0"), "elasticloadbalancing:ModifyTargetGroupAttributes");
+
+ // A new target group's id is the service's to mint, so a grant on its name covers it.
+ String created = "res-new-" + suffix();
+ user.policy(allowOn("elasticloadbalancing:CreateTargetGroup", "arn:aws:elasticloadbalancing:" + REGION + ":"
+ + ACCOUNT + ":targetgroup/" + created + "/*"));
+ refused(createTargetGroup(user, created + "-other"), "elasticloadbalancing:CreateTargetGroup");
+ String createdArn = createTargetGroup(user, created).statusCode(200).extract()
+ .path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
+ cleanup.register(() -> admin("elasticloadbalancing").formParam("Action", "DeleteTargetGroup")
+ .formParam("Version", "2015-12-01").formParam("TargetGroupArn", createdArn).post("/"));
+ }
+
+ /**
+ * The AWS Load Balancer Controller's policy creates on {@code *} with its cluster tag, and tags at creation only
+ * a target group or an application or network load balancer, as {@code elasticloadbalancing:CreateAction}
+ * says; these statements are the published policy's.
+ */
+ @Test
+ void theLoadBalancerControllersPolicyCreatesTaggedTargetGroupsAndLoadBalancers() {
+ User user = user("res-alb-controller");
+ user.policy(CONTROLLER_CREATE + "," + CONTROLLER_TAG_ON_CREATE);
+ String group = "res-ctl-" + suffix();
+ String arn = tagged(user.query("elasticloadbalancing", "CreateTargetGroup").formParam("Version", "2015-12-01")
+ .formParam("Name", group).formParam("Protocol", "HTTP").formParam("Port", "80").formParam("TargetType", "ip"))
+ .post("/").then().statusCode(200).extract()
+ .path("CreateTargetGroupResponse.CreateTargetGroupResult.TargetGroups.member.TargetGroupArn");
+ cleanup.register(() -> admin("elasticloadbalancing").formParam("Action", "DeleteTargetGroup")
+ .formParam("Version", "2015-12-01").formParam("TargetGroupArn", arn).post("/"));
+ refused(createTargetGroup(user, group + "-untagged"), "elasticloadbalancing:CreateTargetGroup");
+
+ // Authorized, a load balancer with no subnets is refused by Elastic Load Balancing, not by IAM.
+ tagged(user.query("elasticloadbalancing", "CreateLoadBalancer").formParam("Version", "2015-12-01")
+ .formParam("Name", "res-ctl-alb")).post("/").then().statusCode(400).body(containsString("ValidationError"));
+ tagged(user.query("elasticloadbalancing", "CreateLoadBalancer").formParam("Version", "2015-12-01")
+ .formParam("Name", "res-ctl-nlb").formParam("Type", "network")).post("/").then().statusCode(400)
+ .body(containsString("ValidationError"));
+ refused(user.query("elasticloadbalancing", "CreateLoadBalancer").formParam("Version", "2015-12-01")
+ .formParam("Name", "res-ctl-untagged").post("/").then(), "elasticloadbalancing:CreateLoadBalancer");
+ }
+
+ /**
+ * A listener's and a rule's tags go to the new listener and rule, so the controller's grant of {@code AddTags} on
+ * listeners and rules covers a tagged {@code CreateListener} and {@code CreateRule}, which act on a load balancer
+ * and a listener.
+ */
+ @Test
+ void theLoadBalancerControllersPolicyCreatesTaggedListenersAndRules() {
+ User user = user("res-alb-listener");
+ user.policy(CONTROLLER_LISTENERS);
+ refused(createListener(user), "elasticloadbalancing:AddTags");
+ refused(createRule(user), "elasticloadbalancing:AddTags");
+
+ // Authorized, a listener of no load balancer and a rule of no listener are refused by Elastic Load Balancing.
+ user.policy(CONTROLLER_LISTENERS + "," + CONTROLLER_TAG_LISTENERS);
+ createListener(user).statusCode(400).body(containsString("LoadBalancerNotFound"));
+ createRule(user).statusCode(400).body(containsString("ListenerNotFound"));
+ }
+
+ /**
+ * A v2 {@code CreateLoadBalancer} of a {@code Type} outside the enum names no v2 load balancer for IAM to check,
+ * and Elastic Load Balancing refuses it, as AWS does, so a grant on a classic load balancer's name does not
+ * create a v2 one under another.
+ */
+ @Test
+ void aLoadBalancerOfATypeOutsideTheEnumIsNotCreatedUnderAnotherName() {
+ String name = "res-protected-" + suffix();
+ User user = user("res-lb-type");
+ user.policy(allowOn("elasticloadbalancing:CreateLoadBalancer", ELB + "loadbalancer/res-allowed"));
+ user.query("elasticloadbalancing", "CreateLoadBalancer").formParam("Version", "2015-12-01")
+ .formParam("Name", name).formParam("Type", "other").formParam("LoadBalancerName", "res-allowed")
+ .formParam("Subnets.member.1", "subnet-a").formParam("Subnets.member.2", "subnet-b").post("/").then()
+ .statusCode(400).body(containsString("ValidationError"))
+ .body(containsString("Member must satisfy enum value set: [application, network, gateway]"));
+ admin("elasticloadbalancing").formParam("Action", "DescribeLoadBalancers").formParam("Version", "2015-12-01")
+ .post("/").then().statusCode(200).body(not(containsString(name)));
+ }
+
+ @Test
+ void aStateMachineIsCheckedOnItsArnAndADenyOnItHolds() {
+ String name = "res-sm-" + suffix();
+ String arn = createStateMachine(name);
+ assertEquals("arn:aws:states:" + REGION + ":" + ACCOUNT + ":stateMachine:" + name, arn);
+
+ User user = user("res-sm");
+ user.policy(allowOn("states:DescribeStateMachine", arn));
+ describeStateMachine(user, arn).statusCode(200);
+ refusedJson(describeStateMachine(user, arn + "-other"), "states:DescribeStateMachine");
+
+ user.policy(allowOn("states:DescribeStateMachine", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"states:*\","
+ + "\"Resource\":\"" + arn + "\"}");
+ refusedJson(describeStateMachine(user, arn), "states:DescribeStateMachine");
+ }
+
+ /**
+ * Over the Smithy RPC v2 route a request is checked for the operation its path dispatches, not one an
+ * {@code X-Amz-Target} it carries names: a grant on one state machine allows describing it there, and a
+ * request whose header names a create of that machine does not describe another.
+ */
+ @Test
+ void aStateMachineIsCheckedForTheOperationTheRpcV2RouteDispatches() throws IOException {
+ String allowedName = "res-rpc-" + suffix();
+ String allowed = createStateMachine(allowedName);
+ String other = createStateMachine("res-rpc-other-" + suffix());
+ User user = user("res-rpc");
+ user.policy(allowOn("states:DescribeStateMachine", allowed));
+ user.cbor("states").body(CBOR_MAPPER.writeValueAsBytes(Map.of("stateMachineArn", allowed)))
+ .post("/service/SFN/operation/DescribeStateMachine").then().statusCode(200);
+
+ byte[] body = CBOR_MAPPER.writeValueAsBytes(Map.of("name", allowedName, "stateMachineArn", other));
+ JsonNode error = CBOR_MAPPER.readTree(user.cbor("states")
+ .header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine").body(body)
+ .post("/service/SFN/operation/DescribeStateMachine").then().statusCode(403).extract().asByteArray());
+ assertEquals("AccessDeniedException", error.path("__type").asText());
+ assertTrue(error.path("message").asText().contains("states:DescribeStateMachine"), error.toString());
+ }
+
+ /**
+ * {@code StartExecution} runs the machine before a Step Functions Local test case's {@code #}, so a grant on
+ * that machine allows a start that names a test case, and a deny on it holds.
+ */
+ @Test
+ void aStateMachinesTestCaseIsCheckedOnTheMachineItRuns() {
+ String arn = createStateMachine("res-tc-" + suffix());
+ User user = user("res-tc");
+ user.policy(allowOn("states:StartExecution", arn));
+ startExecution(user, arn + "#").statusCode(200);
+
+ user.policy(allowOn("states:StartExecution", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"states:StartExecution\","
+ + "\"Resource\":\"" + arn + "\"}");
+ refusedJson(startExecution(user, arn + "#"), "states:StartExecution");
+ }
+
+ /**
+ * Step Functions checks a version or an alias on its state machine's ARN, so a grant on the state machine
+ * allows describing its alias and starting it through either, and a deny on it holds for both.
+ */
+ @Test
+ void aVersionOrAnAliasIsCheckedOnItsStateMachine() {
+ String arn = createStateMachine("res-alias-" + suffix());
+ String version = admin("states").header("X-Amz-Target", "AWSStepFunctions.PublishStateMachineVersion")
+ .contentType("application/x-amz-json-1.0").body("{\"stateMachineArn\":\"" + arn + "\"}")
+ .post("/").then().statusCode(200).extract().path("stateMachineVersionArn");
+ String alias = admin("states").header("X-Amz-Target", "AWSStepFunctions.CreateStateMachineAlias")
+ .contentType("application/x-amz-json-1.0").body("{\"name\":\"PROD\",\"routingConfiguration\":"
+ + "[{\"stateMachineVersionArn\":\"" + version + "\",\"weight\":100}]}")
+ .post("/").then().statusCode(200).extract().path("stateMachineAliasArn");
+ assertEquals(arn + ":PROD", alias);
+
+ User user = user("res-alias");
+ user.policy(allowOn("states:DescribeStateMachineAlias", arn) + "," + allowOn("states:StartExecution", arn));
+ user.json("states", "AWSStepFunctions.DescribeStateMachineAlias", "1.0")
+ .body("{\"stateMachineAliasArn\":\"" + alias + "\"}").post("/").then().statusCode(200);
+ startExecution(user, alias).statusCode(200);
+ startExecution(user, version).statusCode(200);
+
+ user.policy(allowOn("states:StartExecution", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"states:StartExecution\","
+ + "\"Resource\":\"" + arn + "\"}");
+ refusedJson(startExecution(user, alias), "states:StartExecution");
+ refusedJson(startExecution(user, version), "states:StartExecution");
+ }
+
+ @Test
+ void aUserPoolIsCheckedOnTheArnItsIdNames() {
+ String id = admin("cognito-idp").header("X-Amz-Target", "AWSCognitoIdentityProviderService.CreateUserPool")
+ .contentType("application/x-amz-json-1.1").body("{\"PoolName\":\"res-pool-" + suffix() + "\"}")
+ .post("/").then().statusCode(200).extract().path("UserPool.Id");
+ String arn = admin("cognito-idp").header("X-Amz-Target", "AWSCognitoIdentityProviderService.DescribeUserPool")
+ .contentType("application/x-amz-json-1.1").body("{\"UserPoolId\":\"" + id + "\"}")
+ .post("/").then().statusCode(200).extract().path("UserPool.Arn");
+ cleanup.register(() -> admin("cognito-idp").header("X-Amz-Target", "AWSCognitoIdentityProviderService.DeleteUserPool")
+ .contentType("application/x-amz-json-1.1").body("{\"UserPoolId\":\"" + id + "\"}").post("/"));
+ assertEquals("arn:aws:cognito-idp:" + REGION + ":" + ACCOUNT + ":userpool/" + id, arn);
+
+ User user = user("res-pool");
+ user.policy(allowOn("cognito-idp:DescribeUserPool", arn));
+ describeUserPool(user, id).statusCode(200);
+ refusedJson(describeUserPool(user, id + "x"), "cognito-idp:DescribeUserPool");
+ }
+
+ /** A repository is checked on the ARN its name gives, whether or not it exists. */
+ @Test
+ void aRepositoryIsCheckedOnTheArnItsNameGives() {
+ String name = "res-repo-" + suffix();
+ User user = user("res-repo");
+ user.policy(allowOn("ecr:DescribeRepositories", "arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + name));
+ describeRepositories(user, name).statusCode(400).body(containsString("RepositoryNotFoundException"));
+ refusedJson(describeRepositories(user, name + "-other"), "ecr:DescribeRepositories");
+ }
+
+ /**
+ * A list given as one name names no repository, as ECR's handler then lists every one, so a grant on that
+ * repository alone does not allow it.
+ */
+ @Test
+ void aRepositoryListGivenAsOneNameNamesNone() {
+ String name = "res-repo-" + suffix();
+ User user = user("res-repo-list");
+ user.policy(allowOn("ecr:DescribeRepositories", "arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + name));
+ refusedJson(describeRepositoriesWith(user, "{\"repositoryNames\":\"" + name + "\"}"), "ecr:DescribeRepositories");
+ }
+
+ /** A repository is checked in the registry the request's {@code registryId} selects, the one ECR acts in. */
+ @Test
+ void aRepositoryIsCheckedInTheRegistryItsRequestNames() {
+ String name = "res-repo-" + suffix();
+ String other = "111122223333";
+ User user = user("res-repo-registry");
+ user.policy(allowOn("ecr:DescribeRepositories", "arn:aws:ecr:" + REGION + ":" + other + ":repository/" + name));
+ describeRepositoriesWith(user, "{\"registryId\":\"" + other + "\",\"repositoryNames\":[\"" + name + "\"]}")
+ .statusCode(400).body(containsString("RepositoryNotFoundException"));
+ refusedJson(describeRepositories(user, name), "ecr:DescribeRepositories");
+
+ user.policy(allowOn("ecr:DescribeRepositories", "arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + name));
+ refusedJson(describeRepositoriesWith(user, "{\"registryId\":\"" + other + "\",\"repositoryNames\":[\"" + name
+ + "\"]}"), "ecr:DescribeRepositories");
+ }
+
+ /** A {@code registryId} of JSON null is no registry, as ECR reads it, so a deny on the caller's repository holds. */
+ @Test
+ void aNullRegistryIsTheCallersOwn() {
+ String name = "res-protected-" + suffix();
+ User user = user("res-repo-null");
+ user.policy(allowOn("ecr:DescribeRepositories", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"ecr:DescribeRepositories\","
+ + "\"Resource\":\"arn:aws:ecr:" + REGION + ":" + ACCOUNT + ":repository/" + name + "\"}");
+ refusedJson(describeRepositoriesWith(user, "{\"registryId\":null,\"repositoryNames\":[\"" + name + "\"]}"),
+ "ecr:DescribeRepositories");
+ describeRepositoriesWith(user, "{\"registryId\":null,\"repositoryNames\":[\"" + name + "-other\"]}")
+ .statusCode(400).body(containsString("RepositoryNotFoundException"));
+ }
+
+ /**
+ * ECR's tag handlers keep the ARN's account and use the request's Region, so a deny on that repository holds
+ * for an ARN naming it in another Region.
+ */
+ @Test
+ void aDenyHoldsOnTheRepositoryTheTagHandlersActOn() {
+ String protectedArn = "arn:aws:ecr:" + REGION + ":111122223333:repository/res-protected-" + suffix();
+ User user = user("res-repo-tag");
+ user.policy(allowOn("ecr:TagResource", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"ecr:TagResource\","
+ + "\"Resource\":\"" + protectedArn + "\"}");
+ refusedJson(user.json("ecr", "AmazonEC2ContainerRegistry_V20150921.TagResource", "1.1")
+ .body("{\"resourceArn\":\"" + protectedArn.replace(REGION, "eu-west-1")
+ + "\",\"tags\":[{\"Key\":\"a\",\"Value\":\"b\"}]}").post("/").then(), "ecr:TagResource");
+ }
+
+ private static RequestSpecification tagged(RequestSpecification request) {
+ return request.formParam("Tags.member.1.Key", "elbv2.k8s.aws/cluster").formParam("Tags.member.1.Value", "c");
+ }
+
+ private static ValidatableResponse modifyAttributes(User user, String arn) {
+ return user.query("elasticloadbalancing", "ModifyTargetGroupAttributes").formParam("Version", "2015-12-01")
+ .formParam("TargetGroupArn", arn).formParam("Attributes.member.1.Key", "deregistration_delay.timeout_seconds")
+ .formParam("Attributes.member.1.Value", "30").post("/").then();
+ }
+
+ private static ValidatableResponse createTargetGroup(User user, String name) {
+ return user.query("elasticloadbalancing", "CreateTargetGroup").formParam("Version", "2015-12-01")
+ .formParam("Name", name).formParam("Protocol", "HTTP").formParam("Port", "80")
+ .formParam("TargetType", "ip").post("/").then();
+ }
+
+ private static ValidatableResponse createListener(User user) {
+ return tagged(user.query("elasticloadbalancing", "CreateListener").formParam("Version", "2015-12-01")
+ .formParam("LoadBalancerArn", ELB + "loadbalancer/app/res-none/0123456789abcdef")
+ .formParam("Protocol", "HTTP").formParam("Port", "80")
+ .formParam("DefaultActions.member.1.Type", "fixed-response")
+ .formParam("DefaultActions.member.1.FixedResponseConfig.StatusCode", "200")).post("/").then();
+ }
+
+ private static ValidatableResponse createRule(User user) {
+ return tagged(user.query("elasticloadbalancing", "CreateRule").formParam("Version", "2015-12-01")
+ .formParam("ListenerArn", ELB + "listener/app/res-none/0123456789abcdef/0123456789abcdef")
+ .formParam("Priority", "1").formParam("Conditions.member.1.Field", "path-pattern")
+ .formParam("Conditions.member.1.Values.member.1", "/x")
+ .formParam("Actions.member.1.Type", "fixed-response")
+ .formParam("Actions.member.1.FixedResponseConfig.StatusCode", "200")).post("/").then();
+ }
+
+ private String createStateMachine(String name) {
+ String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", name + "-role",
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"lambda:*\",\"Resource\":\"*\"}]}");
+ String arn = admin("states").header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
+ .contentType("application/x-amz-json-1.0")
+ .body("{\"name\":\"" + name + "\",\"roleArn\":\"" + role + "\",\"definition\":\"" + PASS + "\"}")
+ .post("/").then().statusCode(200).extract().path("stateMachineArn");
+ cleanup.register(() -> admin("states").header("X-Amz-Target", "AWSStepFunctions.DeleteStateMachine")
+ .contentType("application/x-amz-json-1.0").body("{\"stateMachineArn\":\"" + arn + "\"}").post("/"));
+ return arn;
+ }
+
+ private static ValidatableResponse describeStateMachine(User user, String arn) {
+ return user.json("states", "AWSStepFunctions.DescribeStateMachine", "1.0")
+ .body("{\"stateMachineArn\":\"" + arn + "\"}").post("/").then();
+ }
+
+ private static ValidatableResponse startExecution(User user, String arn) {
+ return user.json("states", "AWSStepFunctions.StartExecution", "1.0")
+ .body("{\"stateMachineArn\":\"" + arn + "\"}").post("/").then();
+ }
+
+ private static ValidatableResponse describeUserPool(User user, String id) {
+ return user.json("cognito-idp", "AWSCognitoIdentityProviderService.DescribeUserPool", "1.1")
+ .body("{\"UserPoolId\":\"" + id + "\"}").post("/").then();
+ }
+
+ private static ValidatableResponse describeRepositories(User user, String name) {
+ return describeRepositoriesWith(user, "{\"repositoryNames\":[\"" + name + "\"]}");
+ }
+
+ private static ValidatableResponse describeRepositoriesWith(User user, String body) {
+ return user.json("ecr", "AmazonEC2ContainerRegistry_V20150921.DescribeRepositories", "1.1")
+ .body(body).post("/").then();
+ }
+
+ /** A Query service refuses with {@code AccessDenied}, a 403, naming the permission that is missing. */
+ private static void refused(ValidatableResponse response, String action) {
+ response.statusCode(403).body(containsString("not authorized to perform: " + action));
+ }
+
+ /** A JSON-protocol service refuses with {@code AccessDeniedException}, which those protocols send as a 400. */
+ private static void refusedJson(ValidatableResponse response, String action) {
+ response.statusCode(400).body(containsString("AccessDeniedException"))
+ .body(containsString("not authorized to perform: " + action)).body(not(containsString("NotFound")));
+ }
+
+ private static String allowOn(String action, String resource) {
+ return "{\"Effect\":\"Allow\",\"Action\":\"" + action + "\",\"Resource\":\"" + resource + "\"}";
+ }
+
+ private User user(String name) {
+ String userName = name + "-" + suffix();
+ return new User(userName, EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ADMIN, "iam"),
+ userName).accessKeyId());
+ }
+
+ private static RequestSpecification admin(String service) {
+ return given().header("Authorization", auth(ADMIN, service));
+ }
+
+ private static String suffix() {
+ return Long.toString(System.nanoTime(), 36);
+ }
+
+ /** An IAM user whose one inline policy each test replaces. */
+ private record User(String name, String accessKeyId) {
+
+ void policy(String statements) {
+ admin("iam").formParam("Action", "PutUserPolicy").formParam("UserName", name)
+ .formParam("PolicyName", "p")
+ .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statements + "]}")
+ .post("/").then().statusCode(200);
+ }
+
+ RequestSpecification query(String service, String action) {
+ return given().header("Authorization", auth(accessKeyId, service)).formParam("Action", action);
+ }
+
+ RequestSpecification json(String service, String target, String version) {
+ return given().header("Authorization", auth(accessKeyId, service)).header("X-Amz-Target", target)
+ .contentType("application/x-amz-json-" + version);
+ }
+
+ RequestSpecification cbor(String service) {
+ return given().header("Authorization", auth(accessKeyId, service)).header("smithy-protocol", "rpc-v2-cbor")
+ .contentType("application/cbor").accept("application/cbor");
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
index a17de0bbc4..981040b597 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/ResourceArnBuilderTest.java
@@ -1228,6 +1228,26 @@ class ResourceArnBuilderTest {
assertEquals("arn:aws:s3:::my-bucket/folder/", arn);
}
+ // ── The vendored table of request resources ─────────────────────────────────
+
+ /**
+ * A namespace with no branch here is checked on the resources the vendored table finds in its request for the
+ * operation it is dispatched as, and on {@code *} without one or for an operation of another namespace.
+ */
+ @Test
+ void aNamespaceWithNoBranchIsCheckedOnTheResourcesItsRequestNames() {
+ when(ctx.getMethod()).thenReturn("POST");
+ setJsonBody("{\"UserPoolId\":\"us-east-1_abc\"}");
+ assertEquals(List.of("arn:aws:cognito-idp:us-east-1:000000000000:userpool/us-east-1_abc"), builder.buildResources(
+ "cognito-idp", "cognito-idp:DescribeUserPool", ctx, "us-east-1", "000000000000", "aws"));
+ assertEquals(List.of("*"), builder.buildResources("cognito-idp", ctx, "us-east-1", "000000000000"));
+ assertEquals(List.of("*"), builder.buildResources("glue", "cognito-idp:DescribeUserPool", ctx, "us-east-1",
+ "000000000000", "aws"));
+ setJsonBody("{}");
+ assertEquals(List.of("*"), builder.buildResources("cognito-idp", "cognito-idp:DescribeUserPool", ctx,
+ "us-east-1", "000000000000", "aws"));
+ }
+
// ── Lambda ──────────────────────────────────────────────────────────────────
@Test
diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py
new file mode 100644
index 0000000000..cd959fc3b6
--- /dev/null
+++ b/tools/aws/regen_iam_request_resources.py
@@ -0,0 +1,780 @@
+#!/usr/bin/env python3
+"""Regenerate src/main/resources/aws/iam-request-resources.json from AWS's Service Reference and botocore.
+
+Under IAM enforcement every request is checked against the resources it acts on. For the services
+`ResourceArnBuilder` builds them for by hand that is their ARN; for every other service it is `*`,
+so a grant scoped to a resource is refused and a deny scoped to one never applies. This file gives,
+for each operation of the namespaces it reads, the resources its request names, and `RequestResources`
+builds their ARNs from the request. It comes from two sources, each answering what the other cannot:
+
+- AWS's Service Reference, which lists the resource types each action acts on and the ARN formats
+ of each type, but not which request member names a resource:
+
+ https://servicereference.us-east-1.amazonaws.com/ (the index of services)
+ https://servicereference.us-east-1.amazonaws.com/v1/<svc>/<svc>.json
+
+- botocore's model of each SDK client the reference lists the operation for (Apache-2.0,
+ https://github.com/boto/botocore, the pinned release), which gives the request's members.
+
+An operation is checked as its own action, or as the action of another name the reference gives it
+(`regen_iam_authorized_actions.py` vendors that mapping). For each resource type that action acts
+on, the request names a resource when one of its top-level members holds a string or a list of
+strings and:
+
+- holds the resource's ARN: its name ends in `Arn` or `Arns`. Any of the action's types may be the
+ one it holds (`ResourceArn` holds whatever the action acts on, `RuleArn` a `listener-rule/app`),
+ and a value names a resource of a type when it matches the type's ARN format, so an ARN of
+ something the action does not act on is not checked.
+- fills one of the variables of the type's ARN format: its stem (the name lowercased, `Arn`, `Name`,
+ `Id`, `Identifier` and a plural dropped) is the variable's, ends with it or is the end of it, four
+ letters at least (`AutoScalingGroupName` fills `${GroupFriendlyName}`, `GroupId` fills
+ `${SecurityGroupId}`), and it is a name for a name and an id for an id (an `Identifier` either),
+ or the member is a bare `Name`, `Id` or `Identifier`, the variable is named after the type and the
+ operation is about the type, its name past the verb the type's (`DescribeTargetGroups`, but not
+ `StartExecution` for a state machine, whose `name` is the execution's), and no member holds its ARN.
+ The variables nothing fills are left open as `*`: a resource the request creates has the id its
+ service mints, so `CreateTargetGroup` names `targetgroup/<Name>/*`.
+- names neither, but the type is the one the operation is named after (`CreateCapacityReservation`
+ and `capacity-reservation`): the request creates one, every variable open.
+
+A member whose botocore shape is an account id (a string of pattern `[0-9]{12}`) gives the account of
+the types the request names by their variables: ECR's `registryId` selects the registry its handler
+acts in, so `repository/<name>` is that account's.
+
+An operation that creates a type its action does not act on names the new resource from the ARN of the
+parent it acts on, when the child's ARN format is the parent's with its resource type word replaced and
+one id appended (`CreateListener` acts on a load balancer and makes `listener/app/<lb>/<id>/*`); the
+tagging action a create's tags need is checked on it, as AWS checks it on the resource being tagged.
+
+A type nothing names is not checked: an action lists the optional resources its requests may use
+(`RunInstances` lists `elastic-gpu`), and checking one a request does not name would refuse a grant
+that covers what it does name. An operation whose action acts on no resource type, or whose request
+names none, is checked on `*`, as AWS checks it.
+
+Only the namespaces in `NAMESPACES` are read, and in them every operation, whether Floci serves it
+or not. `HAND_BUILT` are the namespaces `ResourceArnBuilder` builds resources for itself, and
+`NOT_COVERED` the ones Floci serves that are not read yet, each with its reason;
+`RequestResourceNamespacesIntegrationTest` fails for a served namespace in none of the three.
+`CORRECTIONS` gives an operation's resources where the rule gets them wrong, each with its reason; a
+resource there may apply only `when` a member has one of some values (`Type` picks the load balancer
+v2 `CreateLoadBalancer` creates), and an ARN member's value may be read only up to a character
+`before` which its handler drops the rest (`StartExecution`'s `<stateMachineArn>#<test case>`).
+`UNQUALIFIED` are the resource types whose ARN a request may give with a qualifier, one more `:<name>`
+past its format, and whose service checks it without one: Step Functions checks a version or an alias
+on its state machine's ARN.
+
+The Service Reference is live rather than a pinned dependency, so a fresh generation is not
+byte-identical. The two gates split along the sources:
+
+- `--check` is offline and needs the pinned botocore. The file must be well-formed, and every
+ operation's resources must be exactly what the rule and the corrections give from botocore for the
+ resource types and ARN formats the file records, so a hand-edited entry fails.
+- `--verify` is online and stdlib-only. Every operation must still be checked as the action, on the
+ resource types, the file records, and every type must still have its ARN format. An operation AWS
+ has added is reported without failing: until the next sync it is checked on `*`, where it was
+ before this file existed.
+
+Run from anywhere in the repo:
+ python3 tools/aws/regen_iam_request_resources.py # rewrite the vendored file in place
+ python3 tools/aws/regen_iam_request_resources.py --check # offline: resources match botocore
+ python3 tools/aws/regen_iam_request_resources.py --verify # online: actions and types match AWS
+ python3 tools/aws/regen_iam_request_resources.py --source-dir <dir> # read saved <svc>.json files
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+from regen_iam_authorized_actions import authorized_actions_from, fetch_references
+from regen_iam_passed_roles import NAMESPACE_RE, OPERATION_RE, _shown, load_models, namespace_of
+from regen_partitions import resolve_botocore_data
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-request-resources.json"
+
+# The namespaces read, in batches: each moves here from NOT_COVERED with the tests that show its ARNs
+# are the ones its handlers mint.
+NAMESPACES = ("cognito-idp", "ecr", "elasticloadbalancing", "states")
+
+# The namespaces whose resources ResourceArnBuilder builds itself.
+HAND_BUILT = ("dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups",
+ "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts")
+
+_LATER = "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint"
+_REST = "REST: its requests name their resources in the path, which RequestResources does not read yet"
+
+# Namespaces Floci serves whose resources are not read yet, and why.
+NOT_COVERED: dict[str, str] = {
+ "access-analyzer": _REST,
+ "account": _REST,
+ "acm": _LATER,
+ "airflow": _REST,
+ "apigateway": _REST,
+ "app-integrations": _REST,
+ "appconfig": _REST,
+ "application-autoscaling": _LATER,
+ "appsync": _REST,
+ "aps": _REST,
+ "athena": _LATER,
+ "autoscaling": _LATER,
+ "aws-marketplace": _LATER,
+ "backup": _REST,
+ "batch": _REST,
+ "bcm-data-exports": _LATER,
+ "bcm-pricing-calculator": _LATER,
+ "bedrock": _LATER,
+ "bedrock-agentcore": _REST,
+ "budgets": _LATER,
+ "ce": _LATER,
+ "cloudformation": _LATER,
+ "cloudfront": _REST,
+ "cloudhsm": _LATER,
+ "cloudtrail": _LATER,
+ "cloudwatch": _LATER,
+ "codeartifact": _REST,
+ "codebuild": _LATER,
+ "codedeploy": _LATER,
+ "codeguru-reviewer": _REST,
+ "codepipeline": _LATER,
+ "cognito-identity": _LATER,
+ "comprehend": _LATER,
+ "config": _LATER,
+ "connect": _REST,
+ "controlcatalog": _REST,
+ "controltower": _REST,
+ "cur": _LATER,
+ "datasync": _LATER,
+ "detective": _REST,
+ "dlm": _REST,
+ "dms": _LATER,
+ "ec2": _LATER,
+ "ecs": _LATER,
+ "elasticache": _LATER,
+ "elasticbeanstalk": _LATER,
+ "elasticfilesystem": _REST,
+ "elasticmapreduce": _LATER,
+ "emr-serverless": _REST,
+ "es": _REST,
+ "events": _LATER,
+ "execute-api": _REST,
+ "firehose": _LATER,
+ "fis": _REST,
+ "globalaccelerator": _LATER,
+ "glue": _LATER,
+ "guardduty": _REST,
+ "identitystore": _LATER,
+ "inspector2": _REST,
+ "iot": _LATER,
+ "kafka": _REST,
+ "kinesisanalytics": _LATER,
+ "lightsail": _LATER,
+ "macie2": _REST,
+ "memorydb": _LATER,
+ "mq": _REST,
+ "network-firewall": _LATER,
+ "oam": _REST,
+ "organizations": _LATER,
+ "ram": _REST,
+ "rds": _LATER,
+ "rds-data": _REST,
+ "redshift": _LATER,
+ "redshift-data": _LATER,
+ "redshift-serverless": _LATER,
+ "rekognition": _LATER,
+ "resource-explorer-2": _REST,
+ "route53": _REST,
+ "route53resolver": _LATER,
+ "rum": _REST,
+ "s3tables": _REST,
+ "s3vectors": _REST,
+ "sagemaker": _LATER,
+ "securityhub": _REST,
+ "servicecatalog": _LATER,
+ "servicediscovery": _LATER,
+ "servicequotas": _LATER,
+ "ses": _LATER,
+ "signin": _REST,
+ "sso": _LATER,
+ "sso-oauth": _REST,
+ "swf": _LATER,
+ "textract": _LATER,
+ "timestream-influxdb": _LATER,
+ "transcribe": _LATER,
+ "transfer": _LATER,
+ "translate": _LATER,
+ "verifiedpermissions": _LATER,
+ "wafv2": _LATER,
+}
+
+# An operation's resources where the rule gets them wrong: the resources, and why. A resource's `when` names the
+# values of a member it applies for, null for the member absent.
+CORRECTIONS: dict[str, tuple[list[dict], str]] = {
+ "elasticloadbalancing:CreateLoadBalancer": ([
+ {"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}},
+ {"type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}},
+ {"type": "loadbalancer/gwy/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["gateway"]}},
+ {"type": "loadbalancer/net/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["network"]}},
+ ], "the classic API names its load balancer by LoadBalancerName; the v2 API by Name, its type by Type, "
+ "an application load balancer when it gives none, which the rule cannot tell apart"),
+ **{f"states:{operation}": ([{"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}],
+ "Floci takes Step Functions Local's <stateMachineArn>#<test case> and runs the machine "
+ "the part before the # names, so that part is the one checked")
+ for operation in ("StartExecution", "StartSyncExecution")},
+}
+
+# Resource types whose ARN a request may give with a qualifier, one more `:<name>` past its format, which their
+# service drops to check it, and why.
+UNQUALIFIED: dict[str, str] = {
+ "states:statemachine": "Step Functions authorizes a version or an alias on its state machine's ARN, not on the "
+ "version's or the alias's ('To authorize a version or an alias to invoke an API action, "
+ "Step Functions uses the state machine's ARN instead of using the version ARN or alias ARN')",
+}
+
+# The variables of an ARN format the account, partition and Region fill.
+KNOWN_VARIABLES = {"Partition", "Region", "Account"}
+VARIABLE_RE = re.compile(r"\$\{(\w+)}")
+STEM_SUFFIX_RE = re.compile(r"(arns|arn|names|name|identifiers|identifier|ids|id|s)$")
+# A bare member that names the resource of the type its operation acts on.
+BARE = {"name", "names", "id", "ids", "identifier", "identifiers"}
+# The patterns botocore gives a string shape that holds an account id.
+ACCOUNT_ID_PATTERNS = {"[0-9]{12}", "^[0-9]{12}$", r"\d{12}", r"^\d{12}$"}
+# The verbs an operation that creates the resource it is named after starts with.
+CREATING_RE = re.compile(r"^(Create|Run|Allocate|Register|Put|Import|Copy|Request|Start|Add)")
+# An operation's verb: what follows is what it acts on.
+SUBJECT_RE = re.compile(r"^[A-Z][a-z]+")
+# The protocols whose requests RequestResources reads: form parameters or a JSON or CBOR body.
+READ_PROTOCOLS = {"json", "query", "ec2", "smithy-rpc-v2-cbor"}
+BODY_LOCATIONS = (None, "")
+
+
+def stem(name: str) -> str:
+ """The name lowercased, without what is not a letter or digit, and without a trailing `Arn`,
+ `Name`, `Id`, `Identifier` or plural, twice over (`TargetGroupArns` is `targetgroup`)."""
+ value = re.sub(r"[^a-z0-9]", "", name.lower())
+ for _ in range(2):
+ value = STEM_SUFFIX_RE.sub("", value)
+ return value
+
+
+def related(a: str, b: str) -> bool:
+ """Whether two stems name the same thing: equal, or one ends with the other, four letters at least."""
+ return a == b or (min(len(a), len(b)) >= 4 and (a.endswith(b) or b.endswith(a)))
+
+
+# --------------------------------------------------------------------------- #
+# The Service Reference
+# --------------------------------------------------------------------------- #
+def checked_actions(documents: list[dict]) -> dict[str, dict]:
+ """Each operation of each namespace, as `<namespace>:<Operation>`, with the action Floci checks it
+ as, that action's resource types (null when the namespace has no action of that name) and the
+ operation's SDK clients."""
+ mapped = authorized_actions_from(documents)
+ found = {}
+ for document in documents:
+ namespace = document["Name"]
+ actions = {action["Name"].lower(): action for action in document.get("Actions", [])}
+ for operation in document.get("Operations", []):
+ name = operation["Name"]
+ action_name = mapped.get(namespace, {}).get(name, f"{namespace}:{name}").split(":", 1)[1]
+ action = actions.get(action_name.lower())
+ found[f"{namespace}:{name}"] = {
+ "action": f"{namespace}:{action['Name']}" if action else f"{namespace}:{action_name}",
+ "types": None if action is None else [resource["Name"] for resource in action.get("Resources") or []],
+ "clients": sorted({sdk["Name"] for sdk in operation.get("SDK", []) if sdk.get("Package") == "Boto3"}),
+ }
+ return found
+
+
+def arn_formats(documents: list[dict], namespaces: set[str]) -> dict[str, dict[str, str]]:
+ """Each resource type of the namespaces given, as its first ARN format."""
+ formats = {}
+ for document in documents:
+ if document["Name"] in namespaces:
+ formats[document["Name"]] = dict(sorted(
+ (resource["Name"], resource["ARNFormats"][0])
+ for resource in document.get("Resources", []) if resource.get("ARNFormats")))
+ return dict(sorted(formats.items()))
+
+
+# --------------------------------------------------------------------------- #
+# botocore
+# --------------------------------------------------------------------------- #
+def _protocols(model: dict) -> set[str]:
+ metadata = model["metadata"]
+ return set(metadata.get("protocols") or [metadata.get("protocol")])
+
+
+def request_members(models: dict[str, dict], operation: str) -> dict[str, str]:
+ """The top-level members of the operation's request that hold a string (`Name`) or a list of
+ strings (`Name[]`), by name, as the vendored path reads them; empty for a request this file does
+ not read."""
+ found: dict[str, str] = {}
+ for model in models.values():
+ spec = model["operations"].get(operation)
+ if spec is None or "input" not in spec or not READ_PROTOCOLS & _protocols(model):
+ continue
+ root = model["shapes"][spec["input"]["shape"]]
+ for name, member in root.get("members", {}).items():
+ if member.get("location") not in BODY_LOCATIONS:
+ continue
+ shape = model["shapes"][member["shape"]]
+ if shape["type"] == "string":
+ found.setdefault(name, name)
+ elif shape["type"] == "list" and model["shapes"][shape["member"]["shape"]]["type"] == "string":
+ found.setdefault(name, name + "[]")
+ return found
+
+
+def account_members(models: dict[str, dict], operation: str) -> list[str]:
+ """The top-level members of the operation's request whose shape is an account id, by name."""
+ found: set[str] = set()
+ for model in models.values():
+ spec = model["operations"].get(operation)
+ if spec is None or "input" not in spec or not READ_PROTOCOLS & _protocols(model):
+ continue
+ for name, member in model["shapes"][spec["input"]["shape"]].get("members", {}).items():
+ shape = model["shapes"][member["shape"]]
+ if member.get("location") in BODY_LOCATIONS and shape["type"] == "string" \
+ and shape.get("pattern") in ACCOUNT_ID_PATTERNS:
+ found.add(name)
+ return sorted(found)
+
+
+def with_account(resources: list[dict], formats: dict[str, str], accounts: list[str]) -> list[dict]:
+ """The resources, each a type named by its variables taking its account from the request's one account id
+ member, when it has exactly one and the type's format has an account."""
+ if len(accounts) != 1:
+ return resources
+ return [dict(resource, account=accounts[0]) if "fill" in resource
+ and "${Account}" in formats.get(resource["type"], "") else resource for resource in resources]
+
+
+def kind_of(name: str) -> str:
+ """Whether a name ends as a name, an id, or an identifier (which is either), or neither."""
+ lower = name.lower()
+ if re.search(r"identifiers?$", lower):
+ return "identifier"
+ if re.search(r"names?$", lower):
+ return "name"
+ if re.search(r"ids?$", lower):
+ return "id"
+ return ""
+
+
+def compatible(member: str, variable: str) -> bool:
+ """Whether a member can fill a variable: a name fills a name, an id an id, an identifier either."""
+ member_kind, variable_kind = kind_of(member), kind_of(variable)
+ return not member_kind or not variable_kind or member_kind == variable_kind or member_kind == "identifier"
+
+
+def resources_for(operation: str, types: list[str], formats: dict[str, str], members: dict[str, str]) -> list[dict]:
+ """The resources the rule finds the operation's request naming, as vendored entries."""
+ name = operation.split(":", 1)[1]
+ created = stem(CREATING_RE.sub("", name)) if CREATING_RE.match(name) else None
+ subject = stem(SUBJECT_RE.sub("", name))
+ arns = {member: path for member, path in members.items() if re.search(r"arns?$", member, re.IGNORECASE)}
+ names = {member: path for member, path in members.items() if member not in arns}
+ by_arn: dict[str, list[str]] = {}
+ filled: dict[str, dict[str, str]] = {}
+ complete: dict[str, bool] = {}
+ for kind in types:
+ if kind not in formats:
+ continue
+ kind_stem = stem(kind)
+ for member in sorted(arns):
+ by_arn.setdefault(member, []).append(kind)
+ # An ARN member named for the type, or for whatever the action acts on, holds it, and a bare name
+ # then names something else.
+ held = [member for member in arns if stem(member) in ("", "resource")
+ or related(stem(member), kind_stem) or kind_stem.startswith(stem(member))]
+ variables = [v for v in VARIABLE_RE.findall(formats[kind]) if v not in KNOWN_VARIABLES]
+ fill: dict[str, str] = {}
+ for variable in sorted(variables, key=lambda v: (kind_of(v) == "", v)):
+ choice = _filling(variable, kind_stem, len(variables), {m: p for m, p in names.items() if m not in fill.values()},
+ bare=not held and related(subject, kind_stem))
+ if choice is not None:
+ fill[variable] = choice
+ fill = {variable: names[member] for variable, member in fill.items()}
+ if len([path for path in fill.values() if path.endswith("[]")]) > 1:
+ fill = {variable: path for variable, path in fill.items() if not path.endswith("[]")}
+ if fill or (not held and (not variables or (created is not None and related(created, kind_stem)))):
+ filled[kind] = fill
+ complete[kind] = len(fill) == len(variables)
+ # Types named only through the same members are alternatives the request picks one of: the one it names in
+ # full, or none when that is not one type, rather than checking every one.
+ by_members: dict[tuple, list[str]] = {}
+ for kind, fill in filled.items():
+ by_members.setdefault(tuple(sorted(set(fill.values()))), []).append(kind)
+ kept = []
+ for kinds in by_members.values():
+ if len(kinds) == 1 or not by_members_key_is_empty(kinds, filled):
+ full = [kind for kind in kinds if complete[kind]]
+ kept += kinds if len(kinds) == 1 else (full if len(full) == 1 else [])
+ specs = [{"types": kinds, "arn": arns[member]} for member, kinds in sorted(by_arn.items())]
+ return specs + [{"type": kind, "fill": dict(sorted(filled[kind].items()))} for kind in types if kind in kept]
+
+
+RESOURCE_PART_RE = re.compile(r"^arn:\$\{Partition}:[^:]*:[^:]*:[^:]*:([A-Za-z][A-Za-z0-9-]*)(.*)$")
+
+
+def child_id(child: str, parent: str) -> str | None:
+ """The variable a child type's ARN format adds to its parent's: the parent's with its leading resource type word
+ replaced and one id appended (`listener/app/.../${ListenerId}` for `loadbalancer/app/...`); None for any other."""
+ child_match, parent_match = RESOURCE_PART_RE.match(child), RESOURCE_PART_RE.match(parent)
+ if child_match is None or parent_match is None or child_match.group(1) == parent_match.group(1):
+ return None
+ appended = re.fullmatch(re.escape(parent_match.group(2)) + r"[/:]\$\{(\w+)}", child_match.group(2))
+ return appended.group(1) if appended else None
+
+
+def creates_for(operation: str, types: list[str], formats: dict[str, str], members: dict[str, str]) -> list[dict]:
+ """The resources a create of a type its action does not act on makes, named from the ARN of the parent it acts
+ on: `CreateListener` acts on a load balancer and makes a listener under it, its id open."""
+ name = operation.split(":", 1)[1]
+ if not CREATING_RE.match(name):
+ return []
+ created = stem(CREATING_RE.sub("", name))
+ arns = sorted(member for member in members if re.search(r"arns?$", member, re.IGNORECASE))
+ found = []
+ for child in sorted(formats):
+ if child in types:
+ continue
+ for parent in types:
+ appended = child_id(formats[child], formats.get(parent, ""))
+ if appended is None or not related(stem(appended), created):
+ continue
+ for member in arns:
+ if stem(member) in ("", "resource") or related(stem(member), stem(parent)) \
+ or stem(parent).startswith(stem(member)):
+ found.append({"type": child, "parent": parent, "arn": members[member]})
+ return found
+
+
+def by_members_key_is_empty(kinds: list[str], filled: dict[str, dict[str, str]]) -> bool:
+ """Whether the types are named by no member at all: each a create's own type, all ids minted."""
+ return all(not filled[kind] for kind in kinds)
+
+
+def _filling(variable: str, kind_stem: str, variables: int, names: dict[str, str], bare: bool) -> str | None:
+ """The member that fills the variable: one of a compatible kind whose stem relates to the variable's,
+ or, for the variable named after the type or a type's only one, a member named after the type, or,
+ when `bare`, a bare `Name` or `Id`, of a compatible kind; the closest of them, and a string before a
+ list."""
+ variable_stem = stem(variable)
+ candidates = [member for member in names
+ if stem(member) and related(stem(member), variable_stem) and compatible(member, variable)]
+ if not candidates and (related(variable_stem, kind_stem) or variables == 1):
+ candidates = [member for member in names if compatible(member, variable)
+ and ((bare and member.lower() in BARE) or (stem(member) and related(stem(member), kind_stem)))]
+ if not candidates:
+ return None
+ return min(candidates, key=lambda member: (stem(member) != variable_stem, names[member].endswith("[]"), len(member), member))
+
+
+# --------------------------------------------------------------------------- #
+# The vendored document
+# --------------------------------------------------------------------------- #
+def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: dict[str, dict]) -> dict:
+ """What the file says for one operation."""
+ types = upstream["types"] or []
+ members = request_members(models, operation.split(":", 1)[1])
+ if operation in CORRECTIONS:
+ resources = CORRECTIONS[operation][0]
+ else:
+ resources = resources_for(operation, types, formats, members)
+ resources = with_account(resources, formats, account_members(models, operation.split(":", 1)[1]))
+ entry = {"action": upstream["action"], "types": types, "resources": resources}
+ creates = creates_for(operation, types, formats, members)
+ if creates:
+ entry["creates"] = creates
+ return entry
+
+
+def build(documents: list[dict], provenance: str, data: Path, botocore: str) -> dict:
+ upstream = checked_actions(documents)
+ covered = {operation: value for operation, value in upstream.items() if namespace_of(operation) in NAMESPACES}
+ _check_overrides(covered)
+ namespaces = {namespace: sorted({client for operation, value in covered.items()
+ if namespace_of(operation) == namespace for client in value["clients"]})
+ for namespace in sorted(NAMESPACES)}
+ formats = arn_formats(documents, set(NAMESPACES))
+ unqualified = unqualified_types()
+ missing = [f"UNQUALIFIED names {namespace}:{kind}, no resource type with an ARN format of a namespace the file reads"
+ for namespace, kinds in unqualified.items() for kind in kinds if kind not in formats.get(namespace, {})]
+ if missing:
+ raise ValueError("; ".join(missing))
+ operations = {}
+ for operation, value in sorted(covered.items()):
+ models = load_models(data, set(namespaces[namespace_of(operation)]))
+ operations[operation] = entry_for(operation, value, formats.get(namespace_of(operation), {}), models)
+ return {
+ "_source": {
+ "generator": "tools/aws/regen_iam_request_resources.py",
+ "reference": provenance,
+ "botocore": botocore,
+ "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
+ "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": namespaces,
+ "handBuilt": list(HAND_BUILT),
+ "notCovered": dict(sorted(NOT_COVERED.items())),
+ "otherNamespaces": sorted(namespace for namespace in _with_resource_types(documents)
+ if namespace not in NAMESPACES and namespace not in HAND_BUILT
+ and namespace not in NOT_COVERED),
+ "arnFormats": formats,
+ "unqualified": unqualified,
+ "operations": operations,
+ }
+
+
+def unqualified_types() -> dict[str, list[str]]:
+ """`UNQUALIFIED` as the types of each namespace."""
+ found: dict[str, list[str]] = {}
+ for key in sorted(UNQUALIFIED):
+ namespace, kind = key.split(":", 1)
+ found.setdefault(namespace, []).append(kind)
+ return found
+
+
+def _with_resource_types(documents: list[dict]) -> set[str]:
+ """The namespaces with an action that acts on a resource type."""
+ return {document["Name"] for document in documents
+ if any(action.get("Resources") for action in document.get("Actions", []))}
+
+
+def _check_overrides(covered: dict[str, dict]) -> None:
+ """Every correction names an operation the file reads, and no namespace is in two places."""
+ stale = [f"CORRECTIONS names {operation}, which the file does not read" for operation in CORRECTIONS
+ if operation not in covered]
+ for left, right in (("NAMESPACES", "HAND_BUILT"), ("NAMESPACES", "NOT_COVERED"), ("HAND_BUILT", "NOT_COVERED")):
+ stale += [f"{namespace} is in both {left} and {right}"
+ for namespace in sorted(set(globals()[left]) & set(globals()[right]))]
+ if stale:
+ raise ValueError("; ".join(stale))
+
+
+def render(document: dict) -> str:
+ """The document with one operation to a line."""
+ lines = ["{"]
+ for key in ("_source", "namespaces", "handBuilt", "notCovered", "otherNamespaces", "arnFormats", "unqualified"):
+ lines.append(f' "{key}": {json.dumps(document[key])},')
+ lines.append(' "operations": {')
+ operations = list(document["operations"].items())
+ for index, (operation, entry) in enumerate(operations):
+ tail = "," if index < len(operations) - 1 else ""
+ lines.append(f" {json.dumps(operation)}: {json.dumps(entry)}{tail}")
+ lines += [" }", "}"]
+ return "\n".join(lines) + "\n"
+
+
+# --------------------------------------------------------------------------- #
+# Gates
+# --------------------------------------------------------------------------- #
+PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[])?$")
+
+
+def validate(document: dict) -> list[str]:
+ """Problems that make the vendored file unusable, rather than out of date."""
+ namespaces = document.get("namespaces")
+ operations = document.get("operations")
+ formats = document.get("arnFormats")
+ if not isinstance(namespaces, dict) or not namespaces:
+ return ["namespaces is missing or empty"]
+ if not isinstance(operations, dict) or not operations:
+ return ["operations is missing or empty"]
+ problems: list[str] = []
+ if not isinstance(formats, dict) or set(formats) - set(namespaces) or not all(
+ isinstance(types, dict) and all(isinstance(arn, str) and arn.startswith("arn:${Partition}:")
+ for arn in types.values()) for types in formats.values()):
+ return ["arnFormats is not an ARN format for each resource type of namespaces the file reads"]
+ if list(operations) != sorted(operations):
+ problems.append("operations is not sorted")
+ unqualified = document.get("unqualified")
+ if not isinstance(unqualified, dict) or not all(
+ isinstance(kinds, list) and kinds and all(isinstance(kind, str) and kind in formats.get(namespace, {})
+ for kind in kinds) for namespace, kinds in unqualified.items()):
+ problems.append("unqualified is not resource types with an ARN format of each namespace the file reads")
+ for key in ("handBuilt", "otherNamespaces"):
+ if not isinstance(document.get(key), list) or not all(isinstance(n, str) and NAMESPACE_RE.match(n)
+ for n in document[key]):
+ problems.append(f"{key} is not a list of namespaces")
+ if not isinstance(document.get("notCovered"), dict) or not all(
+ isinstance(reason, str) and reason for reason in document["notCovered"].values()):
+ problems.append("notCovered does not give each namespace a reason")
+ for operation, entry in operations.items():
+ namespace = namespace_of(operation)
+ if not OPERATION_RE.match(operation) or namespace not in namespaces:
+ problems.append(f"{operation!r} is not an operation of a namespace the file reads")
+ continue
+ if not isinstance(entry, dict) or not {"action", "types", "resources"} <= set(entry) <= {"action", "types", "resources", "creates"}:
+ problems.append(f"{operation} is not an action, its types and its resources")
+ continue
+ if not isinstance(entry["action"], str) or not OPERATION_RE.match(entry["action"]) \
+ or namespace_of(entry["action"]) != namespace:
+ problems.append(f"{operation} is checked as no action of its namespace")
+ types = entry["types"]
+ if not isinstance(types, list) or not all(isinstance(kind, str) for kind in types):
+ problems.append(f"{operation} has no list of resource types")
+ continue
+ for resource in entry["resources"] if isinstance(entry["resources"], list) else [None]:
+ problems += _resource_problems(operation, resource, set(types), formats.get(namespace, {}))
+ for created in entry.get("creates", []) if isinstance(entry.get("creates", []), list) else [None]:
+ problems += _created_problems(operation, created, set(types), formats.get(namespace, {}))
+ return problems
+
+
+def _resource_problems(operation: str, resource: object, types: set[str], formats: dict[str, str]) -> list[str]:
+ if not isinstance(resource, dict) or not ({"types", "arn"} <= set(resource) <= {"types", "arn", "before"}
+ or {"type", "fill"} <= set(resource) <= {"type", "fill", "when", "account"}):
+ return [f"{operation} names {resource!r}, which is neither an ARN member nor a type's variables"]
+ kinds = resource.get("types") or [resource.get("type")]
+ if not all(isinstance(kind, str) and kind in types and kind in formats for kind in kinds):
+ return [f"{operation} names {kinds}, not resource types its action acts on with an ARN format"]
+ if "arn" in resource:
+ if not isinstance(resource["arn"], str) or not PATH_RE.match(resource["arn"]):
+ return [f"{operation} reads an ARN at {resource['arn']!r}, which is no member"]
+ before = resource.get("before", "#")
+ return [] if isinstance(before, str) and len(before) == 1 else [
+ f"{operation} reads its ARN before {before!r}, which is no one character"]
+ fill = resource["fill"]
+ variables = set(VARIABLE_RE.findall(formats[kinds[0]])) - KNOWN_VARIABLES
+ if not isinstance(fill, dict) or set(fill) - variables or not all(
+ isinstance(path, str) and PATH_RE.match(path) for path in fill.values()):
+ return [f"{operation} fills {fill!r}, which are no variables of {kinds[0]}'s ARN by members"]
+ if sum(path.endswith("[]") for path in fill.values()) > 1:
+ return [f"{operation} fills {kinds[0]} from more than one list"]
+ when = resource.get("when", {})
+ if not isinstance(when, dict) or not all(
+ isinstance(path, str) and PATH_RE.match(path) and not path.endswith("[]") and isinstance(values, list) and values
+ and all(value is None or isinstance(value, str) for value in values) for path, values in when.items()):
+ return [f"{operation} names {kinds[0]} when {when!r}, which is no member's values"]
+ account = resource.get("account")
+ if account is not None and (not isinstance(account, str) or not PATH_RE.match(account) or account.endswith("[]")
+ or "${Account}" not in formats[kinds[0]]):
+ return [f"{operation} takes {kinds[0]}'s account from {account!r}, which is no member or no account of its ARN"]
+ return []
+
+
+def _created_problems(operation: str, created: object, types: set[str], formats: dict[str, str]) -> list[str]:
+ if not isinstance(created, dict) or set(created) != {"type", "parent", "arn"} or not isinstance(created["arn"], str) \
+ or not PATH_RE.match(created["arn"]):
+ return [f"{operation} creates {created!r}, which is no type made under a parent's ARN member"]
+ if created["parent"] not in types or created["type"] not in formats or created["parent"] not in formats \
+ or child_id(formats[created["type"]], formats[created["parent"]]) is None:
+ return [f"{operation} creates a {created['type']} under a {created['parent']}, no parent of it its action acts on"]
+ return []
+
+
+def derive(document: dict, data: Path) -> list[str]:
+ """Where the resources the file gives differ from what botocore gives for its types and formats."""
+ problems: list[str] = []
+ if document["unqualified"] != unqualified_types():
+ problems.append(f"the file checks {json.dumps(document['unqualified'])} without a qualifier, "
+ f"UNQUALIFIED gives {json.dumps(unqualified_types())}")
+ for operation, entry in document["operations"].items():
+ namespace = namespace_of(operation)
+ models = load_models(data, set(document["namespaces"][namespace]))
+ expected = entry_for(operation, {"action": entry["action"], "types": entry["types"]},
+ document["arnFormats"].get(namespace, {}), models)
+ if expected != entry:
+ problems.append(f"{operation}: the file has {json.dumps(entry)}, botocore gives {json.dumps(expected)}")
+ return problems
+
+
+def verify_against(vendored: dict, upstream: dict[str, dict], formats: dict[str, dict[str, str]]) -> tuple[list[str], list[str]]:
+ """What the file claims and AWS does not, and the operations AWS has added since."""
+ untrue: list[str] = []
+ for operation, entry in vendored["operations"].items():
+ actual = upstream.get(operation)
+ if actual is None:
+ untrue.append(f"AWS no longer lists {operation}")
+ elif actual["action"] != entry["action"]:
+ untrue.append(f"AWS checks {operation} as {actual['action']}, not {entry['action']}")
+ elif (actual["types"] or []) != entry["types"]:
+ untrue.append(f"AWS gives {entry['action']} the resource types {actual['types']}, not {entry['types']}")
+ elif not set(actual["clients"]) <= set(vendored["namespaces"][namespace_of(operation)]):
+ untrue.append(f"AWS lists {operation} for {actual['clients']}, which the file does not read")
+ for namespace, types in vendored["arnFormats"].items():
+ changed = sorted(kind for kind, arn in types.items() if formats.get(namespace, {}).get(kind) != arn)
+ if changed:
+ untrue.append(f"AWS no longer gives {namespace}'s {', '.join(changed)} the ARN format the file does")
+ added = sorted(operation for operation in upstream
+ if namespace_of(operation) in vendored["namespaces"] and operation not in vendored["operations"])
+ return untrue, added
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--check", action="store_true", help="offline: resources match the pinned botocore")
+ parser.add_argument("--verify", action="store_true", help="online: actions, types and formats match AWS")
+ parser.add_argument("--source-dir", type=Path, default=None,
+ help="read saved <service>.json reference files instead of fetching them")
+ parser.add_argument("--botocore-data", type=Path, default=None, help="botocore data directory")
+ parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
+ args = parser.parse_args(argv)
+
+ if args.check or args.verify:
+ if not args.output.exists():
+ print(f"error: {args.output} does not exist", file=sys.stderr)
+ return 1
+ document = json.loads(args.output.read_text(encoding="utf-8"))
+ problems = validate(document)
+ if not problems and args.check:
+ data, _ = resolve_botocore_data(args.botocore_data)
+ problems = derive(document, data)
+ for problem in problems:
+ print(f"error: {problem}", file=sys.stderr)
+ if problems:
+ return 1
+ entries = len(document["operations"])
+ if args.check:
+ print(f"{_shown(args.output)} matches botocore ({entries} operations over "
+ f"{len(document['namespaces'])} namespaces)")
+ return 0
+ try:
+ documents, provenance = fetch_references(args.source_dir)
+ upstream = checked_actions(documents)
+ formats = arn_formats(documents, set(document["namespaces"]))
+ except (OSError, ValueError) as e:
+ print(f"error: could not read the Service Reference ({e})", file=sys.stderr)
+ return 2
+ untrue, added = verify_against(document, upstream, formats)
+ for claim in untrue:
+ print(f"error: {claim}", file=sys.stderr)
+ if untrue:
+ print(f"error: {len(untrue)} vendored claim(s) do not hold upstream.", file=sys.stderr)
+ return 1
+ if added:
+ print(f"{_shown(args.output)}: all {entries} operations verified. AWS has since added "
+ f"{len(added)}, so the file is incomplete but not wrong (run without --verify to refresh): "
+ f"{', '.join(added[:10])}{'...' if len(added) > 10 else ''}")
+ else:
+ print(f"{_shown(args.output)}: all {entries} operations verified against {provenance}, "
+ f"nothing added upstream.")
+ return 0
+
+ data, botocore = resolve_botocore_data(args.botocore_data)
+ try:
+ documents, provenance = fetch_references(args.source_dir)
+ document = build(documents, provenance, data, botocore)
+ except (OSError, ValueError) as e:
+ print(f"error: {e}", file=sys.stderr)
+ return 2
+ problems = validate(document)
+ for problem in problems:
+ print(f"error: {problem}", file=sys.stderr)
+ if problems:
+ return 1
+ args.output.write_text(render(document), encoding="utf-8")
+ print(f"wrote {_shown(args.output)} ({len(document['operations'])} operations over "
+ f"{len(document['namespaces'])} namespaces, from {provenance})")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/aws/test_regen_iam_request_resources.py b/tools/aws/test_regen_iam_request_resources.py
new file mode 100644
index 0000000000..4d2751140a
--- /dev/null
+++ b/tools/aws/test_regen_iam_request_resources.py
@@ -0,0 +1,340 @@
+"""Tests for regen_iam_request_resources.
+
+Run with: pytest tools/aws -q (or: make iam-request-resources-test)
+"""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+import regen_iam_request_resources as r
+
+FORMATS = {
+ "thing": "arn:${Partition}:svc:${Region}:${Account}:thing/${ThingName}",
+ "group": "arn:${Partition}:svc:${Region}:${Account}:group/${GroupName}/${GroupId}",
+ "pool": "arn:${Partition}:svc:${Region}:${Account}:pool/${PoolId}",
+ "catalog": "arn:${Partition}:svc:${Region}:${Account}:catalog",
+ "lb": "arn:${Partition}:svc:${Region}:${Account}:loadbalancer/${LoadBalancerName}",
+ "lb/app/": "arn:${Partition}:svc:${Region}:${Account}:loadbalancer/app/${LoadBalancerName}/${LoadBalancerId}",
+}
+
+
+def members(*names: str) -> dict[str, str]:
+ return {name.rstrip("[]"): name for name in names}
+
+
+def test_a_member_holding_an_arn_names_any_type_the_action_acts_on():
+ assert r.resources_for("svc:DescribeThing", ["thing", "pool"], FORMATS, members("ThingArn", "ResourceArns[]")) == [
+ {"types": ["thing", "pool"], "arn": "ResourceArns[]"}, {"types": ["thing", "pool"], "arn": "ThingArn"}]
+
+
+def test_a_member_fills_a_variable_its_stem_relates_to_and_of_its_kind():
+ assert r.resources_for("svc:GetThing", ["thing"], FORMATS, members("ThingName")) == [
+ {"type": "thing", "fill": {"ThingName": "ThingName"}}]
+ # A name fills a name and leaves an id open; an identifier fills either.
+ assert r.resources_for("svc:UpdateGroup", ["group"], FORMATS, members("GroupName")) == [
+ {"type": "group", "fill": {"GroupName": "GroupName"}}]
+ assert r.resources_for("svc:UpdatePool", ["pool"], FORMATS, members("PoolIdentifier")) == [
+ {"type": "pool", "fill": {"PoolId": "PoolIdentifier"}}]
+ # A longer name ending with the variable's stem fills it.
+ assert r.resources_for("svc:GetThing", ["thing"], FORMATS, members("SpecialThingName")) == [
+ {"type": "thing", "fill": {"ThingName": "SpecialThingName"}}]
+
+
+def test_a_bare_name_fills_the_type_the_operation_is_about_and_no_other():
+ assert r.resources_for("svc:CreateThing", ["thing"], FORMATS, members("Name")) == [
+ {"type": "thing", "fill": {"ThingName": "Name"}}]
+ assert r.resources_for("svc:DescribeGroups", ["group"], FORMATS, members("Names[]")) == [
+ {"type": "group", "fill": {"GroupName": "Names[]"}}]
+ # StartRun's name is the run's, not the thing's.
+ assert r.resources_for("svc:StartRun", ["thing"], FORMATS, members("name")) == []
+ # A member holding the type's ARN leaves the bare name to something else.
+ assert r.resources_for("svc:CreateThingAlias", ["thing"], FORMATS, members("Name")) == []
+
+
+def test_a_fixed_format_and_a_creates_own_type_are_named_without_members():
+ assert r.resources_for("svc:GetCatalog", ["catalog"], FORMATS, {}) == [{"type": "catalog", "fill": {}}]
+ assert r.resources_for("svc:CreatePool", ["pool"], FORMATS, members("Description")) == [{"type": "pool", "fill": {}}]
+ # Another type the action lists, which the request does not name, is not checked.
+ assert r.resources_for("svc:CreatePool", ["pool", "thing"], FORMATS, members("Description")) == [
+ {"type": "pool", "fill": {}}]
+
+
+def test_types_named_only_through_the_same_members_are_alternatives():
+ # A classic load balancer's name fills its whole ARN, not an application one's id: the classic one is kept.
+ assert r.resources_for("svc:DeleteLoadBalancer", ["lb", "lb/app/"], FORMATS, members("LoadBalancerName")) == [
+ {"type": "lb", "fill": {"LoadBalancerName": "LoadBalancerName"}}]
+
+
+def test_a_type_is_filled_from_one_list_at_most():
+ formats = {"pair": "arn:${Partition}:svc:${Region}:${Account}:pair/${LeftName}/${RightName}"}
+ assert r.resources_for("svc:GetPair", ["pair"], formats, members("LeftNames[]", "RightNames[]")) == []
+ # Only an operation that creates its type names it with every variable open.
+ assert r.resources_for("svc:GetPair", ["pair"], formats, {}) == []
+
+
+LISTENERS = {
+ "loadbalancer/app/": FORMATS["lb/app/"],
+ "listener/app": "arn:${Partition}:svc:${Region}:${Account}:listener/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}",
+ "rule/app": "arn:${Partition}:svc:${Region}:${Account}:rule/app/${LoadBalancerName}/${LoadBalancerId}/${ListenerId}/${RuleId}",
+ "pair": "arn:${Partition}:svc:${Region}:${Account}:pair/app/${LoadBalancerName}/${LoadBalancerId}/${A}/${B}",
+}
+
+
+def test_a_child_format_is_its_parents_with_the_type_word_replaced_and_one_id_appended():
+ assert r.child_id(LISTENERS["listener/app"], LISTENERS["loadbalancer/app/"]) == "ListenerId"
+ assert r.child_id(LISTENERS["rule/app"], LISTENERS["listener/app"]) == "RuleId"
+ # Two ids appended, a grandchild, the parent itself and the same type word are no children.
+ assert r.child_id(LISTENERS["pair"], LISTENERS["loadbalancer/app/"]) is None
+ assert r.child_id(LISTENERS["rule/app"], LISTENERS["loadbalancer/app/"]) is None
+ assert r.child_id(LISTENERS["loadbalancer/app/"], LISTENERS["loadbalancer/app/"]) is None
+ assert r.child_id(FORMATS["group"], FORMATS["lb"]) is None
+
+
+def test_a_create_of_a_child_of_a_type_its_action_acts_on_names_it_from_the_parents_arn():
+ assert r.creates_for("svc:CreateListener", ["loadbalancer/app/"], LISTENERS, members("LoadBalancerArn", "RoleArn")) == [
+ {"type": "listener/app", "parent": "loadbalancer/app/", "arn": "LoadBalancerArn"}]
+ assert r.creates_for("svc:CreateRule", ["listener/app"], LISTENERS, members("ListenerArn")) == [
+ {"type": "rule/app", "parent": "listener/app", "arn": "ListenerArn"}]
+ # Only a creating verb, a child named after what it creates, and a type its action does not act on.
+ assert r.creates_for("svc:DescribeListeners", ["loadbalancer/app/"], LISTENERS, members("LoadBalancerArn")) == []
+ assert r.creates_for("svc:CreateRule", ["loadbalancer/app/"], LISTENERS, members("LoadBalancerArn")) == []
+ assert r.creates_for("svc:CreateListener", ["loadbalancer/app/", "listener/app"], LISTENERS, members("LoadBalancerArn")) == []
+ # A parent's ARN in no member, or in one of another type, names nothing.
+ assert r.creates_for("svc:CreateListener", ["loadbalancer/app/"], LISTENERS, members("Name")) == []
+ assert r.creates_for("svc:CreateListener", ["loadbalancer/app/"], LISTENERS, members("RoleArn")) == []
+
+
+def test_stems_drop_the_suffixes_names_carry():
+ assert r.stem("TargetGroupArns") == "targetgroup"
+ assert r.stem("DBInstanceIdentifier") == "dbinstance"
+ # A plural's s goes, from a type's name and a member's alike, so they still meet.
+ assert r.related(r.stem("EventBusName"), r.stem("event-bus"))
+ assert r.related("autoscalinggroup", "group") and not r.related("ab", "b")
+
+
+def reference(namespace: str, operations: dict[str, list[str]], resources: dict[str, str]) -> dict:
+ """A Service Reference document: each operation its own action, acting on the types given."""
+ return {"Name": namespace,
+ "Actions": [{"Name": name, "Resources": [{"Name": kind} for kind in types]} for name, types in operations.items()],
+ "Operations": [{"Name": name, "AuthorizedActions": [{"Service": namespace, "Name": name}],
+ "SDK": [{"Name": namespace, "Method": name, "Package": "Boto3"}]} for name in operations],
+ "Resources": [{"Name": kind, "ARNFormats": [arn]} for kind, arn in resources.items()]}
+
+
+def model(operations: dict[str, dict[str, str]], protocol: str = "json") -> dict:
+ """A botocore model whose operations take the members given, each a string or a list of strings."""
+ shapes = {"String": {"type": "string"}, "Strings": {"type": "list", "member": {"shape": "String"}},
+ "AccountId": {"type": "string", "pattern": "[0-9]{12}"}}
+ ops = {}
+ for name, fields in operations.items():
+ shapes[name + "In"] = {"type": "structure", "members": {field: {"shape": shape} for field, shape in fields.items()}}
+ ops[name] = {"input": {"shape": name + "In"}}
+ return {"metadata": {"protocol": protocol}, "operations": ops, "shapes": shapes}
+
+
+def corrections(monkeypatch):
+ monkeypatch.setattr(r, "NAMESPACES", ("svc",))
+ monkeypatch.setattr(r, "HAND_BUILT", ("hand",))
+ monkeypatch.setattr(r, "NOT_COVERED", {"later": "a later batch"})
+ monkeypatch.setattr(r, "CORRECTIONS", {})
+ monkeypatch.setattr(r, "UNQUALIFIED", {})
+ return monkeypatch
+
+
+def write_models(root, models: dict[str, dict]):
+ for name, value in models.items():
+ directory = root / name / "2020-01-01"
+ directory.mkdir(parents=True)
+ (directory / "service-2.json").write_text(json.dumps(value), encoding="utf-8")
+
+
+DOCUMENTS = [reference("svc", {"GetThing": ["thing"], "ListThings": []}, {"thing": FORMATS["thing"]}),
+ reference("other", {"Op": ["x"]}, {"x": "arn:${Partition}:other:::x"}),
+ reference("later", {"Op": ["y"]}, {"y": "arn:${Partition}:later:::y"})]
+
+
+def test_a_built_document_validates_matches_botocore_and_names_the_namespaces_it_does_not_read(corrections, tmp_path):
+ write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
+ document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
+ assert r.validate(document) == []
+ assert r.derive(document, tmp_path) == []
+ assert document["operations"]["svc:GetThing"] == {"action": "svc:GetThing", "types": ["thing"],
+ "resources": [{"type": "thing", "fill": {"ThingName": "ThingName"}}]}
+ assert document["operations"]["svc:ListThings"]["resources"] == []
+ assert document["otherNamespaces"] == ["other"]
+ assert json.loads(r.render(document)) == document
+
+
+def test_a_member_holding_an_account_id_gives_the_account_of_the_types_named_by_variables(corrections, tmp_path):
+ write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String", "registryId": "AccountId"},
+ "ListThings": {"registryId": "AccountId"}})})
+ document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
+ assert r.validate(document) == [] and r.derive(document, tmp_path) == []
+ assert document["operations"]["svc:GetThing"]["resources"] == [
+ {"type": "thing", "fill": {"ThingName": "ThingName"}, "account": "registryId"}]
+ # An ARN carries its own account, and a format without one takes none.
+ assert r.with_account([{"types": ["thing"], "arn": "ThingArn"}], FORMATS, ["registryId"]) == [
+ {"types": ["thing"], "arn": "ThingArn"}]
+ assert r.with_account([{"type": "catalog", "fill": {}}], {"catalog": "arn:${Partition}:svc:::catalog"},
+ ["registryId"]) == [{"type": "catalog", "fill": {}}]
+ # Two account members, either of which it could be, give none.
+ assert r.with_account([{"type": "thing", "fill": {}}], FORMATS, ["a", "b"]) == [{"type": "thing", "fill": {}}]
+
+
+def test_a_hand_edited_entry_does_not_match_botocore(corrections, tmp_path):
+ write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
+ document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
+ document["operations"]["svc:GetThing"]["resources"] = []
+ assert r.validate(document) == []
+ assert len(r.derive(document, tmp_path)) == 1
+
+
+def test_a_type_checked_without_a_qualifier_is_recorded_and_must_be_one_the_file_reads(corrections, tmp_path):
+ write_models(tmp_path, {"svc": model({"GetThing": {"ThingName": "String"}, "ListThings": {}})})
+ corrections.setattr(r, "UNQUALIFIED", {"svc:thing": "its service checks a qualified ARN without the qualifier"})
+ document = r.build(DOCUMENTS, "test", tmp_path, "botocore test")
+ assert document["unqualified"] == {"svc": ["thing"]}
+ assert r.validate(document) == [] and r.derive(document, tmp_path) == []
+ # A hand edit no longer matches, and a type the file has no format for fails the build.
+ document["unqualified"] = {}
+ assert r.validate(document) == [] and len(r.derive(document, tmp_path)) == 1
+ corrections.setattr(r, "UNQUALIFIED", {"svc:gone": "no longer there"})
+ with pytest.raises(ValueError, match="svc:gone"):
+ r.build(DOCUMENTS, "test", tmp_path, "botocore test")
+
+
+def test_a_correction_for_an_operation_the_file_does_not_read_fails(corrections, tmp_path):
+ corrections.setattr(r, "CORRECTIONS", {"svc:Gone": ([], "no longer there")})
+ with pytest.raises(ValueError, match="svc:Gone"):
+ r.build(DOCUMENTS, "test", tmp_path, "botocore test")
+
+
+def good_document() -> dict:
+ return {"namespaces": {"svc": ["svc"]}, "handBuilt": ["hand"], "notCovered": {"later": "a later batch"},
+ "otherNamespaces": ["other"], "arnFormats": {"svc": {"thing": FORMATS["thing"], "group": FORMATS["group"]}},
+ "unqualified": {"svc": ["thing"]},
+ "operations": {
+ "svc:A": {"action": "svc:A", "types": ["thing"], "resources": [{"types": ["thing"], "arn": "ThingArn"}]},
+ "svc:B": {"action": "svc:B", "types": ["group"], "resources": [{"type": "group", "fill": {"GroupName": "Names[]"}}]},
+ "svc:C": {"action": "svc:C", "types": [], "resources": []}}}
+
+
+def test_a_well_formed_document_validates():
+ assert r.validate(good_document()) == []
+ document = good_document()
+ document["operations"]["svc:B"]["resources"][0]["when"] = {"Type": ["application", None]}
+ document["operations"]["svc:B"]["resources"][0]["account"] = "registryId"
+ document["operations"]["svc:A"]["resources"][0]["before"] = "#"
+ assert r.validate(document) == []
+ assert r.validate(with_a_create()) == []
+
+
+def with_a_create() -> dict:
+ document = good_document()
+ document["arnFormats"]["svc"]["part"] = "arn:${Partition}:svc:${Region}:${Account}:part/${ThingName}/${PartId}"
+ document["operations"]["svc:A"]["creates"] = [{"type": "part", "parent": "thing", "arn": "ThingArn"}]
+ return document
+
+
[email protected]("change, problem", [
+ (lambda d: d["operations"]["svc:A"]["resources"][0].update(types=["pool"]), "not resource types"),
+ (lambda d: d["operations"]["svc:A"]["resources"][0].update(arn="a.b"), "no member"),
+ (lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(Other="Name"), "no variables"),
+ (lambda d: d["operations"]["svc:B"]["resources"][0]["fill"].update(GroupId="Ids[]"), "more than one list"),
+ (lambda d: d["operations"]["svc:A"].update(action="other:A"), "no action of its namespace"),
+ (lambda d: d["operations"]["svc:A"].pop("types"), "an action, its types"),
+ (lambda d: d["arnFormats"]["svc"].update(thing="*"), "arnFormats"),
+ (lambda d: d["operations"].update({"other:X": {"action": "other:X", "types": [], "resources": []}}),
+ "namespace the file reads"),
+ (lambda d: d["notCovered"].update(later=""), "reason"),
+ (lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Type": []}), "no member's values"),
+ (lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Types[]": ["a"]}), "no member's values"),
+ (lambda d: d["operations"]["svc:B"]["resources"][0].update(when={"Type": [1]}), "no member's values"),
+ (lambda d: d["operations"]["svc:A"]["resources"][0].update(before="##"), "no one character"),
+ (lambda d: d["operations"]["svc:B"]["resources"][0].update(before="#"), "neither an ARN member"),
+ (lambda d: d["operations"]["svc:B"]["resources"][0].update(account="Ids[]"), "no account of its ARN"),
+ (lambda d: d["operations"]["svc:B"]["resources"][0].update(account="a.b"), "no account of its ARN"),
+ (lambda d: d["arnFormats"]["svc"].update(group="arn:${Partition}:svc:::group/${GroupName}")
+ or d["operations"]["svc:B"]["resources"][0].update(account="registryId"), "no account of its ARN"),
+ (lambda d: d.update(unqualified={"svc": ["pool"]}), "unqualified"),
+ (lambda d: d.update(unqualified={"other": ["thing"]}), "unqualified"),
+ (lambda d: d.update(unqualified={"svc": []}), "unqualified"),
+ (lambda d: d.pop("unqualified"), "unqualified"),
+])
+def test_a_malformed_document_is_rejected(change, problem):
+ document = good_document()
+ change(document)
+ assert any(problem in p for p in r.validate(document)), r.validate(document)
+
+
[email protected]("change, problem", [
+ (lambda d: d["operations"]["svc:A"]["creates"][0].update(parent="group"), "no parent of it"),
+ (lambda d: d["operations"]["svc:A"]["creates"][0].update(type="group"), "no parent of it"),
+ (lambda d: d["operations"]["svc:A"]["creates"][0].update(arn="a.b"), "no type made under"),
+ (lambda d: d["operations"]["svc:A"]["creates"][0].pop("parent"), "no type made under"),
+ (lambda d: d["arnFormats"]["svc"].update(part="arn:${Partition}:svc:${Region}:${Account}:part/${PartId}"),
+ "no parent of it"),
+])
+def test_a_malformed_create_is_rejected(change, problem):
+ document = with_a_create()
+ change(document)
+ assert any(problem in p for p in r.validate(document)), r.validate(document)
+
+
+def test_verify_fails_on_an_action_type_or_format_aws_does_not_give_and_reports_an_added_operation():
+ document = good_document()
+ upstream = {"svc:A": {"action": "svc:A", "types": ["thing"], "clients": ["svc"]},
+ "svc:B": {"action": "svc:Other", "types": ["group"], "clients": ["svc"]},
+ "svc:C": {"action": "svc:C", "types": ["thing"], "clients": ["svc"]},
+ "svc:D": {"action": "svc:D", "types": [], "clients": ["svc"]}}
+ untrue, added = r.verify_against(document, upstream, {"svc": {"thing": FORMATS["thing"], "group": "arn:${Partition}:svc:::g"}})
+ assert any("svc:B" in u for u in untrue) and any("svc:C" in u for u in untrue)
+ assert any("group" in u and "ARN format" in u for u in untrue)
+ assert added == ["svc:D"]
+
+
+def test_every_correction_is_the_vendored_entry_of_an_operation_the_file_reads():
+ operations = json.loads(r.OUTPUT.read_text(encoding="utf-8"))["operations"]
+ assert r.CORRECTIONS
+ for operation, (resources, reason) in r.CORRECTIONS.items():
+ assert operation in operations and reason, operation
+ assert operations[operation]["resources"] == resources, operation
+
+
+def test_a_correction_gives_the_operation_its_resources(corrections):
+ corrections.setattr(r, "CORRECTIONS", {"svc:GetThing": ([{"type": "thing", "fill": {}}], "a reason")})
+ entry = r.entry_for("svc:GetThing", {"action": "svc:GetThing", "types": ["thing"]}, FORMATS, {})
+ assert entry["resources"] == [{"type": "thing", "fill": {}}]
+
+
+def test_the_vendored_file_is_well_formed():
+ document = json.loads(r.OUTPUT.read_text(encoding="utf-8"))
+ assert r.validate(document) == []
+ operations = document["operations"]
+ assert operations["elasticloadbalancing:CreateTargetGroup"]["resources"] == [
+ {"type": "targetgroup", "fill": {"TargetGroupName": "Name"}}]
+ assert operations["states:DescribeStateMachine"]["resources"] == [{"types": ["statemachine"], "arn": "stateMachineArn"}]
+ assert operations["ecr:DescribeRepositories"]["resources"] == [
+ {"type": "repository", "fill": {"RepositoryName": "repositoryNames[]"}, "account": "registryId"}]
+ # Its request has no registryId, so the repositories are the caller's.
+ assert operations["ecr:BatchGetRepositoryScanningConfiguration"]["resources"] == [
+ {"type": "repository", "fill": {"RepositoryName": "repositoryNames[]"}}]
+ assert operations["cognito-idp:DescribeUserPool"]["resources"] == [{"type": "userpool", "fill": {"UserPoolId": "UserPoolId"}}]
+ # StartExecution's name is the execution's, so only its state machine ARN is read, up to a test case's #.
+ assert operations["states:StartExecution"]["resources"] == [
+ {"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}]
+ # A state machine's version or alias is checked on the state machine.
+ assert document["unqualified"] == {"states": ["statemachine"]}
+ # A listener is made under a load balancer, and a rule under a listener.
+ assert operations["elasticloadbalancing:CreateListener"]["creates"] == [
+ {"type": f"listener/{kind}", "parent": f"loadbalancer/{kind}/", "arn": "LoadBalancerArn"}
+ for kind in ("app", "gwy", "net")]
+ assert operations["elasticloadbalancing:CreateRule"]["creates"] == [
+ {"type": f"listener-rule/{kind}", "parent": f"listener/{kind}", "arn": "ListenerArn"} for kind in ("app", "net")]
+ assert set(document["handBuilt"]) >= {"lambda", "s3", "sqs"}
+ # The v2 API's Type picks the load balancer it creates, application when it gives none.
+ assert operations["elasticloadbalancing:CreateLoadBalancer"]["resources"][1] == {
+ "type": "loadbalancer/app/", "fill": {"LoadBalancerName": "Name"}, "when": {"Type": ["application", None]}}