diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 5cd2ac733b..0ffd2b551a 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -92,6 +92,9 @@ on: - 'tools/aws/sources/ec2-id-examples.json' - 'tools/aws/fetch_ec2_id_examples.py' - 'tools/aws/test_fetch_ec2_id_examples.py' + - 'tools/aws/sources/ec2-request-samples.json' + - 'tools/aws/fetch_ec2_request_samples.py' + - 'tools/aws/test_fetch_ec2_request_samples.py' - 'tools/aws/fetch_ssm_session_permissions.py' - 'tools/aws/sources/ssm-session-permissions.json' - 'tools/aws/test_fetch_ssm_session_permissions.py' diff --git a/Makefile b/Makefile index 2ed048e32e..4dbb3503d9 100644 --- a/Makefile +++ b/Makefile @@ -711,6 +711,8 @@ IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json tools/aws/fetch_dynamodb_permissions.py tools/aws/test_fetch_dynamodb_permissions.py \ tools/aws/sources/iam-identifiers.json tools/aws/fetch_iam_identifiers.py tools/aws/test_fetch_iam_identifiers.py \ tools/aws/sources/ec2-id-examples.json tools/aws/fetch_ec2_id_examples.py tools/aws/test_fetch_ec2_id_examples.py \ + tools/aws/sources/ec2-request-samples.json tools/aws/fetch_ec2_request_samples.py \ + tools/aws/test_fetch_ec2_request_samples.py \ tools/aws/sources/ssm-session-permissions.json tools/aws/fetch_ssm_session_permissions.py \ tools/aws/test_fetch_ssm_session_permissions.py \ tools/aws/sources/sqs-redrive-permissions.json tools/aws/fetch_sqs_redrive_permissions.py \ @@ -966,7 +968,7 @@ iam-request-resources-verify: ## CI gate (online): every vendored operation must 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 tools/aws/test_fetch_ec2_id_examples.py tools/aws/test_fetch_ssm_session_permissions.py -q + $(PYTHON) -m pytest tools/aws/test_regen_iam_request_resources.py tools/aws/test_fetch_ec2_id_examples.py tools/aws/test_fetch_ec2_request_samples.py tools/aws/test_fetch_ssm_session_permissions.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/ec2.md b/docs/services/ec2.md index d0a529b526..dfe2dd14a5 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -11,6 +11,15 @@ its botocore shape each comes from, are generated from the Service Reference and every interface is checked against its own keys and tags before any tag changes; another interface's VPC or tags cannot authorize it. Authorization reads do not create default resources. +A request acting on a VPC peering connection carries its `ec2:AccepterVpc` and +`ec2:RequesterVpc` as the ARNs of the two VPCs it joins, each in its own Region and account, +so a cross-account or cross-Region peering can be scoped by either side. +`CreateVpcPeeringConnection` takes them for the connection from its request: `PeerVpcId`, +`PeerOwnerId` and `PeerRegion` for the accepter, `VpcId` for the requester, the caller's +account and the request's Region where the request leaves the peer's out. An accepter VPC +Floci holds is in the account holding it, as the connection records it, whatever +`PeerOwnerId` claims. + With IAM enforcement enabled, `CreateTags` and `DeleteTags` check every VPC endpoint ID against its endpoint ARN before changing any batch member. botocore gives no `vpce-` example, so the generated request resource table takes the prefix from the response examples of the diff --git a/docs/services/iam.md b/docs/services/iam.md index 46cb15bb3b..890a8f489a 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -4180,9 +4180,21 @@ floci populates: `ec2:NetworkInterfaceID`: for every action on a resource EC2 holds, the members of the resource the key names, an ARN for a key the Service Reference types as one. `resourceKeys` in `iam-request-resources.json` gives each type's keys and members, generated from the Service Reference - and botocore by `tools/aws/regen_iam_request_resources.py`; network interfaces are read so far, and a - key of a type EC2 does not yet answer for stays absent. A batch is evaluated once per resource, each - with its own keys. + and botocore by `tools/aws/regen_iam_request_resources.py`; network interfaces and VPC peering + connections are read so far, and a key of a type EC2 does not yet answer for stays absent. A batch is + evaluated once per resource, each with its own keys. +- A VPC peering connection's `ec2:AccepterVpc` and `ec2:RequesterVpc`: the ARN of each VPC it joins, in + that VPC's own Region and account, from the `AccepterVpcInfo` and `RequesterVpcInfo` it holds, for + `AcceptVpcPeeringConnection`, `RejectVpcPeeringConnection`, `DeleteVpcPeeringConnection` and + `ModifyVpcPeeringConnectionOptions`. On `CreateVpcPeeringConnection` the connection's + `vpc-peering-connection/*` takes them from the request (`madeResourceKeys`): the accepter VPC from + `PeerVpcId`, `PeerOwnerId` and `PeerRegion`, the requester VPC from `VpcId`; a `PeerOwnerId` or + `PeerRegion` left out is the caller's account or the request's Region, as botocore documents, and an + accepter VPC Floci holds is in the account holding it, as the connection records it, whatever + `PeerOwnerId` claims. The + request's `vpc` resource does not take them, as the Service Reference lists neither key on it. Which + parameter fills which part of the ARN comes from AWS's sample request and response on the EC2 API + reference's `CreateVpcPeeringConnection` page, which `tools/aws/fetch_ec2_request_samples.py` copies. - `s3:ExistingObjectTag/`: the tags already on the target object version, for `s3:GetObject`, `s3:GetObjectTagging`, `s3:GetObjectAcl`, `s3:PutObjectAcl`, `s3:DeleteObjectTagging`, `s3:PutObjectTagging` and the annotation actions, and for their diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index a78b66c039..5ae71bce64 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -1301,10 +1301,12 @@ public class IamConditionContextResolver { /** * The generated record keys of one EC2 ARN (see {@link #putResourceKeys}), retaining their caller-scoped - * lookup. Clear earlier generated tag keys before the shared {@link #resourceTags} path reads this ARN. + * lookup. Clear earlier generated tag keys before the shared {@link #resourceTags} path reads this ARN. The ARN of + * the resource a create makes, which EC2 holds nothing under yet, takes the keys its request gives + * ({@link #withMadeResourceKeys}) from the request's {@code form}. */ public Map> withEc2ResourceContext(String scope, String action, String resource, - String region, String accountId, + String region, String accountId, Map form, Map> context) { if (!"ec2".equals(scope) || RequestResources.hasIndividualTargets(action) || !AwsArnUtils.isArn(resource) || !ec2Service.isResolvable()) { @@ -1317,12 +1319,17 @@ public class IamConditionContextResolver { String resourceRegion = arn.region().isEmpty() ? region : arn.region(); String resourceAccount = arn.accountId().isEmpty() ? accountId : arn.accountId(); String[] parts = arn.resource().split("/", 2); - if (parts.length != 2 || parts[1].contains("*") || parts[1].contains("?")) { + if (parts.length != 2) { return context; } + boolean callerResource = region.equals(resourceRegion) && accountId.equals(resourceAccount); + if (parts[1].contains("*") || parts[1].contains("?")) { + Map made = callerResource && "*".equals(parts[1]) + ? madeResourceKeys(action, parts[0]) : Map.of(); + return made.isEmpty() ? context : withMadeResourceKeys(context, made, form, region, accountId); + } List prefixes = RequestResourceMembers.table().resourceTagKeys() .getOrDefault("ec2", Map.of()).getOrDefault(parts[0], List.of()); - boolean callerResource = region.equals(resourceRegion) && accountId.equals(resourceAccount); Map keys = callerResource ? ec2ResourceKeys(parts[0]) : Map.of(); if (prefixes.isEmpty() && keys.isEmpty()) { return context; @@ -1336,6 +1343,81 @@ public class IamConditionContextResolver { return result; } + /** + * The structure keys a create's request gives the resource of its type it makes ({@code made}): each the ARN of + * its type, every variable filled by the EC2 Query parameter the table gives it, a Region or account the request + * leaves out being the request's own, in that Region's partition ({@code CreateVpcPeeringConnection}'s + * {@code ec2:AccepterVpc}, a VPC of the request's Region and the caller's account without {@code PeerRegion} and + * {@code PeerOwnerId}, as botocore documents their defaults). A resource EC2 holds under the ARN's id is in the + * account holding it, whatever account the request claims, as its handler records it + * ({@link Ec2Service#heldAccount}). A key whose ARN's own variable the request leaves out stays absent. + */ + private Map> withMadeResourceKeys(Map> context, + Map made, + Map form, String region, String accountId) { + Map> result = context == null ? new LinkedHashMap<>() : new LinkedHashMap<>(context); + result.keySet().removeAll(made.keySet()); + made.forEach((key, spec) -> { + Map filling = new HashMap<>(); + spec.query().forEach((variable, parameter) -> { + String value = form.get(parameter); + if (value != null && !value.isBlank()) { + filling.put(variable, value); + } + }); + Set variables = ec2ResourceKeys(spec.type()).get(key).fill().keySet(); + ownId(variables, filling).flatMap(id -> ec2Service.get() + .heldAccount(filling.getOrDefault("Region", region), spec.arn(), id)) + .ifPresent(holder -> filling.put("Account", holder)); + String arn = filledArn(spec.arn(), variables, filling, region, accountId); + if (arn != null) { + result.put(key, List.of(arn)); + } + }); + return result; + } + + /** The id an ARN of {@code variables} names its resource by: its one variable past the Region and account. */ + private static Optional ownId(Set variables, Map filling) { + List own = variables.stream() + .filter(variable -> !"Region".equals(variable) && !"Account".equals(variable)).toList(); + return own.size() == 1 ? Optional.ofNullable(filling.get(own.getFirst())) : Optional.empty(); + } + + /** The structure keys the request-resources table gives a create's resource of {@code type} it makes. */ + private static Map madeResourceKeys(String action, String type) { + Map keys = new LinkedHashMap<>(); + RequestResourceMembers.table().madeResourceKeys().getOrDefault(action, Map.of()).forEach((key, spec) -> { + if (spec.type().equals(type)) { + keys.put(key, spec); + } + }); + return keys; + } + + /** + * The ARN of EC2's type {@code type}, each of its {@code variables} taking its value in {@code filling}, the + * Region and account those of {@code region} and {@code accountId} it leaves out, in the partition of the Region + * it takes; null when it leaves out another variable, or when a Region or account it is given would move the + * ARN's other parts (a {@code PeerRegion} of {@code eu-west-1:111111111111:vpc/x} is no Region). + */ + private String filledArn(String type, Set variables, Map filling, String region, + String accountId) { + Map others = new HashMap<>(filling); + String arnRegion = others.remove("Region"); + String arnAccount = others.remove("Account"); + if (!others.keySet().containsAll(variables.stream() + .filter(variable -> !"Region".equals(variable) && !"Account".equals(variable)).toList())) { + return null; + } + arnRegion = arnRegion == null ? region : arnRegion; + arnAccount = arnAccount == null ? accountId : arnAccount; + String arn = RequestResources.filledArn("ec2", type, others, regionResolver.partitionForRegion(arnRegion), + arnRegion, arnAccount); + AwsArnUtils.Arn parsed = AwsArnUtils.parse(arn); + return parsed.region().equals(arnRegion) && parsed.accountId().equals(arnAccount) ? arn : null; + } + private void addResourceTags(Map> conditions, String resourceId, RequestResourceMembers.Targets targets) { if (resourceId == null || resourceId.isBlank() || !ec2Service.isResolvable()) { @@ -1386,8 +1468,9 @@ public class IamConditionContextResolver { /** * Each condition key the request-resources table gives EC2's resource {@code type} as a member of its botocore * shape, valued from that member of {@code held}, the resource EC2 holds under the target's id, as the ARN of the - * key's type where the Service Reference types the key as one. A member with no value, or no resource held, - * leaves the key absent. + * key's type where the Service Reference types the key as one. A structure key's fields fill its ARN, the Region + * and account the structure gives included (a peering connection's {@code AccepterVpcInfo}, the accepter VPC in + * its own Region and account). A member with no value, or no resource held, leaves the key absent. */ private void putResourceKeys(Map> conditions, String region, String type, Object held) { Map keys = ec2ResourceKeys(type); @@ -1398,20 +1481,46 @@ public class IamConditionContextResolver { String account = requestContext.getAccountId(); String partition = regionResolver.partitionForRegion(region); keys.forEach((key, spec) -> { - String value = memberValue(resource, spec.member()); + String value = spec.fill().isEmpty() ? memberValue(resource, spec.member()) + : structureArn(memberNode(resource, spec.member()), spec, region, account); if (value != null && !value.isBlank()) { - conditions.put(key, List.of(spec.arn() == null ? value + conditions.put(key, List.of(spec.arn() == null || !spec.fill().isEmpty() ? value : RequestResources.idArn("ec2", spec.arn(), value, partition, region, account))); } }); } + /** + * The ARN a structure key's {@code structure} gives, each variable of its type filled by the field the key's + * {@code fill} names; null when the structure is absent or leaves a field out. + */ + private String structureArn(JsonNode structure, RequestResourceMembers.ResourceKey spec, String region, + String accountId) { + if (structure == null || !structure.isObject()) { + return null; + } + Map filling = new HashMap<>(); + spec.fill().forEach((variable, field) -> { + String value = memberValue(structure, field); + if (value != null && !value.isBlank()) { + filling.put(variable, value); + } + }); + return filling.size() == spec.fill().size() + ? filledArn(spec.arn(), spec.fill().keySet(), filling, region, accountId) : null; + } + /** The scalar the resource holds in the botocore member {@code member}, its field of that name, case aside. */ private static String memberValue(JsonNode resource, String member) { + JsonNode value = memberNode(resource, member); + return value != null && value.isValueNode() && !value.isNull() ? JsonNodes.asText(value) : null; + } + + /** What the resource holds in the botocore member {@code member}, its field of that name, case aside. */ + private static JsonNode memberNode(JsonNode resource, String member) { for (Map.Entry field : resource.properties()) { - if (field.getKey().equalsIgnoreCase(member) && field.getValue().isValueNode() - && !field.getValue().isNull()) { - return JsonNodes.asText(field.getValue()); + if (field.getKey().equalsIgnoreCase(member)) { + return field.getValue(); } } return null; diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index 0c91058e29..933dfbf218 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -1281,8 +1281,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Map> taggedContext = targetContext; if ("ec2".equals(credentialScope) && !RequestResources.hasIndividualTargets(operationAction) && AwsArnUtils.isArn(resource)) { - taggedContext = conditionContextResolver.withEc2ResourceContext( - credentialScope, operationAction, resource, region, accountId, targetContext); + taggedContext = conditionContextResolver.withEc2ResourceContext(credentialScope, operationAction, + resource, region, accountId, IamConditionContextResolver.formParameters(ctx), + targetContext); } taggedContext = IamConditionContextResolver.withResourceTags(taggedContext, conditionContextResolver.resourceTags(action, resource)); diff --git a/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java b/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java index 1939d1f4d5..923bf0c423 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java +++ b/src/main/java/io/floci/aws/core/common/RequestResourceMembers.java @@ -372,9 +372,21 @@ final class RequestResourceMembers { /** * A condition key of a resource type that a member of the type's botocore shape names ({@code ec2:Vpc}, a * network interface's {@code VpcId}): its value is that member of the resource its service holds, as the ARN of - * the namespace's type {@code arn} where the Service Reference types the key as an ARN, as given otherwise. + * the namespace's type {@code arn} where the Service Reference types the key as an ARN, as given otherwise. A key + * with a {@code fill} names a structure member instead ({@code ec2:AccepterVpc}, a peering connection's + * {@code AccepterVpcInfo}), whose fields give the {@code arn} type's ARN, by the variable each fills + * ({@code Account} its {@code OwnerId}, {@code Region} its {@code Region}, {@code VpcId} its {@code VpcId}). */ - record ResourceKey(String member, String arn) { + record ResourceKey(String member, String arn, Map fill) { + } + + /** + * A structure key ({@link ResourceKey} with a {@code fill}) of the resource of {@code type} a create makes, read + * from its request: the ARN of the type {@code arn}, each variable filled by the EC2 Query parameter + * {@code query} gives it ({@code ec2:AccepterVpc}, {@code VpcId} from {@code PeerVpcId}), the Region and account a + * request leaves out being its own. + */ + record MadeResourceKey(String type, String arn, Map query) { } /** @@ -432,6 +444,7 @@ final class RequestResourceMembers { Map> located, Map> formats, Map>> resourceTagKeys, Map>> resourceKeys, + Map> madeResourceKeys, Set namespaces, Set notCovered, Set otherNamespaces, Map> forwarded, Map>> statements, Map>> locatedApart, Set unread, @@ -812,7 +825,8 @@ final class RequestResourceMembers { }); return new Table(Map.copyOf(entries), Map.copyOf(actsOn), Map.copyOf(creates), Map.copyOf(makes), Map.copyOf(targets), Map.copyOf(ec2Query), Map.copyOf(located), Map.copyOf(formats), - Map.copyOf(resourceTagKeys), resourceKeys, namespaces, + Map.copyOf(resourceTagKeys), resourceKeys, madeResourceKeys(document, resourceKeys, entries), + namespaces, Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()), names(document.path("otherNamespaces")), Map.copyOf(forwarded), statements(document, formats), Map.copyOf(locatedApart), Set.copyOf(unread), Map.copyOf(checkedAs), tagParents(document, formats), @@ -960,7 +974,10 @@ final class RequestResourceMembers { || !arn.isMissingNode() && !known.containsKey(JsonNodes.asText(arn, ""))) { throw new IllegalStateException(RESOURCE_NAME + " has malformed resource keys"); } - keys.put(key.getKey(), new ResourceKey(member, arn.isMissingNode() ? null : JsonNodes.asText(arn))); + Map fill = keyFill(key.getValue().path("fill"), + arn.isMissingNode() ? null : known.get(JsonNodes.asText(arn))); + keys.put(key.getKey(), new ResourceKey(member, arn.isMissingNode() ? null : JsonNodes.asText(arn), + fill)); }); types.put(type.getKey(), Map.copyOf(keys)); }); @@ -969,6 +986,79 @@ final class RequestResourceMembers { return Map.copyOf(result); } + /** + * A structure key's {@code fill}: a field for each variable of its ARN type's {@code format} but the partition, + * empty when the key has none, refused when it gives other variables or names no ARN type. + */ + private static Map keyFill(JsonNode fill, ArnFormat format) { + if (fill.isMissingNode()) { + return Map.of(); + } + Set variables = new LinkedHashSet<>(); + if (format != null) { + VARIABLE.matcher(format.format()).results().map(match -> match.group(1)) + .filter(variable -> !"Partition".equals(variable)).forEach(variables::add); + } + Map result = strings(fill); + if (format == null || !result.keySet().equals(variables) || result.containsValue("")) { + throw new IllegalStateException(RESOURCE_NAME + " has malformed resource keys"); + } + return result; + } + + /** + * The table's {@code madeResourceKeys}: for each create, its structure keys of the resource it makes, refused when + * the create makes no resource of that type, or the key is no structure key of the type with the same ARN type, + * or a parameter fills a variable the key's {@code fill} does not. + */ + private static Map> madeResourceKeys( + JsonNode document, Map>> resourceKeys, + Map> entries) { + JsonNode section = document.path("madeResourceKeys"); + if (!section.isMissingNode() && !section.isObject()) { + throw new IllegalStateException(RESOURCE_NAME + " has malformed made resource keys"); + } + Map> result = new LinkedHashMap<>(); + section.properties().forEach(operation -> { + String namespace = operation.getKey().split(":", 2)[0]; + Map keys = new LinkedHashMap<>(); + if (!operation.getValue().isObject()) { + throw new IllegalStateException(RESOURCE_NAME + " has malformed made resource keys"); + } + operation.getValue().properties().forEach(key -> { + String type = JsonNodes.asText(key.getValue().path("type"), ""); + String arn = JsonNodes.asText(key.getValue().path("arn"), ""); + ResourceKey stored = resourceKeys.getOrDefault(namespace, Map.of()).getOrDefault(type, Map.of()) + .get(key.getKey()); + Map query = strings(key.getValue().path("query")); + boolean made = entries.getOrDefault(operation.getKey(), List.of()).stream() + .anyMatch(resource -> resource.made() && resource.types().contains(type)); + if (!made || stored == null || stored.fill().isEmpty() || !arn.equals(stored.arn()) + || !stored.fill().keySet().containsAll(query.keySet()) || query.containsValue("")) { + throw new IllegalStateException(RESOURCE_NAME + " has malformed made resource keys"); + } + keys.put(key.getKey(), new MadeResourceKey(type, arn, query)); + }); + result.put(operation.getKey(), Map.copyOf(keys)); + }); + return Map.copyOf(result); + } + + /** A JSON object of strings, refused when it is not one. */ + private static Map strings(JsonNode node) { + if (!node.isObject()) { + throw new IllegalStateException(RESOURCE_NAME + " has malformed resource keys"); + } + Map result = new LinkedHashMap<>(); + node.properties().forEach(field -> { + if (!field.getValue().isString()) { + throw new IllegalStateException(RESOURCE_NAME + " has malformed resource keys"); + } + result.put(field.getKey(), JsonNodes.asText(field.getValue())); + }); + return Map.copyOf(result); + } + /** * A request the operation's service makes to another as the caller, joined with what the file records of its * action: the type it acts on and the {@code ViaService} key of its namespace, if any. diff --git a/src/main/java/io/floci/aws/core/common/RequestResources.java b/src/main/java/io/floci/aws/core/common/RequestResources.java index 91c84828cf..a63785c6a8 100644 --- a/src/main/java/io/floci/aws/core/common/RequestResources.java +++ b/src/main/java/io/floci/aws/core/common/RequestResources.java @@ -1390,7 +1390,6 @@ public final class RequestResources { 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 *}. */ /** * The ARN of the namespace's resource of {@code type} named by {@code id}, the one variable of its format past * partition, Region and account, as a request naming the resource by its id gives it. @@ -1407,6 +1406,17 @@ public final class RequestResources { return render(format, filling, partition, region, accountId); } + /** + * The ARN of the namespace's resource of {@code type} in {@code region} and {@code accountId}, each other variable + * of its format past the partition taking its value in {@code filling}, or else {@code *}. + */ + public static String filledArn(String namespace, String type, Map filling, String partition, + String region, String accountId) { + return render(RequestResourceMembers.table().formats().get(namespace).get(type).format(), filling, partition, + region, accountId); + } + + /** The format with each variable replaced once: the partition, Region and account, a value, or else {@code *}. */ private static String render(String format, Map filling, String partition, String region, String accountId) { Matcher variable = VARIABLE.matcher(format); diff --git a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java index 785353924d..43dca895eb 100644 --- a/src/main/java/io/floci/aws/services/ec2/Ec2Service.java +++ b/src/main/java/io/floci/aws/services/ec2/Ec2Service.java @@ -14576,6 +14576,27 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab return findAnyVpcEntry(region, vpcId).map(AccountAwareStorageBackend.OwnedEntry::account); } + /** + * The account holding EC2's resource of {@code type} under {@code id} in {@code region}, which a request naming + * that resource by its id acts on whatever account it claims: {@link #createVpcPeeringConnection} records the + * accepter VPC under the account holding it, whatever {@code PeerOwnerId} says. The caller's own first, as + * {@link #findVpcOwnerAccount} finds it, but read in place: a pre-multi-account entry is the default account's and + * stays where it is, as an IAM read must leave the store as it is. Empty when no account holds it, or for a type + * it does not answer for. + */ + public Optional heldAccount(String region, String type, String id) { + if (!"vpc".equals(type) || !(vpcs instanceof AccountAwareStorageBackend rawAccountAware)) { + return Optional.empty(); + } + @SuppressWarnings("unchecked") + AccountAwareStorageBackend accountAware = (AccountAwareStorageBackend) rawAccountAware; + String key = key(region, id); + List holders = accountAware.scanAllAccountEntries(key::equals).stream() + .map(AccountAwareStorageBackend.AccountEntry::accountId).toList(); + String caller = callerAccountId(); + return holders.contains(caller) ? Optional.of(caller) : holders.stream().findFirst(); + } + public List describeVpcPeeringConnections(String region, List ids, Map> filters) { return describeVpcPeeringConnections(region, ids, filterList(filters)); @@ -14585,15 +14606,24 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab List>> filters) { ensureDefaultResources(region); String caller = callerAccountId(); - return allVpcPeeringConnections().stream() - .filter(pcx -> visibleToAccount(pcx, caller)) - .filter(pcx -> visibleFromRegion(pcx, region)) - .filter(pcx -> ids.isEmpty() || ids.contains(pcx.getVpcPeeringConnectionId())) + return visibleVpcPeeringConnections(caller, region, ids) .map(pcx -> withStoredTags(pcx, caller, region)) .filter(pcx -> matchesFilters(pcx, filters, region)) .collect(Collectors.toList()); } + /** + * The peering connections {@code caller} sees from {@code region} ({@link #visibleToAccount}, + * {@link #visibleFromRegion}), those under {@code ids} when it names any, read across every account's store. + */ + private Stream visibleVpcPeeringConnections(String caller, String region, + Collection ids) { + return allVpcPeeringConnections().stream() + .filter(pcx -> visibleToAccount(pcx, caller)) + .filter(pcx -> visibleFromRegion(pcx, region)) + .filter(pcx -> ids.isEmpty() || ids.contains(pcx.getVpcPeeringConnectionId())); + } + /** * A peering connection's tags as the caller sees them from {@code region}: each side tags it in * its own account and region. A connection recorded before its create-time tags reached the tag @@ -17522,12 +17552,22 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab * The resources of {@code type} EC2 holds for the caller under {@code ids}, keyed by id, as its Describe operation * answers them, which the IAM condition keys the request-resources table reads from a resource's members are * valued from: a network interface of any kind, stored, held by an instance or owned by an endpoint or a NAT - * gateway. All of them come from one pass over the stores, so a request naming many costs no more lookups than one - * naming a single resource. Empty for a type it does not answer for. An id it holds nothing under is absent, and - * the request fails on it. Reads only: it creates no default resources. + * gateway, and a peering connection the caller is a party to, seen from the Region of either side. All of them + * come from one pass over the stores, so a request naming many costs no more lookups than one naming a single + * resource. Empty for a type it does not answer for. An id it holds nothing under is absent, and the request fails + * on it. Reads only: it creates no default resources. */ public Map heldResources(String region, String type, Collection ids) { - if (!"network-interface".equals(type) || ids.isEmpty()) { + if (ids.isEmpty()) { + return Map.of(); + } + if ("vpc-peering-connection".equals(type)) { + Map held = new HashMap<>(); + visibleVpcPeeringConnections(callerAccountId(), region, ids) + .forEach(pcx -> held.put(pcx.getVpcPeeringConnectionId(), pcx)); + return held; + } + if (!"network-interface".equals(type)) { return Map.of(); } // The id filter rather than the id list: a filter leaves out what it does not match, where an id the store diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json index 29446f7a14..5e128585ac 100644 --- a/src/main/resources/aws/iam-request-resources.json +++ b/src/main/resources/aws/iam-request-resources.json @@ -7,7 +7,8 @@ "pathFormats": {"apigateway": {"/restapis/{restapi_id}/models/{model_name}/default_template (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/restapis/${RestapiId}/models/${ModelName}/default_template", "/restapis/{restapi_id}/stages/{stage_name}/cache/authorizers (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/restapis/${RestapiId}/stages/${StageName}/cache/authorizers", "/restapis/{restapi_id}/stages/{stage_name}/cache/data (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/restapis/${RestapiId}/stages/${StageName}/cache/data", "/restapis/{restapi_id}/stages/{stage_name}/exports/{export_type} (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/restapis/${RestapiId}/stages/${StageName}/exports/${ExportType}", "/sdktypes (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/sdktypes", "/sdktypes/{sdktype_id} (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/sdktypes/${SdktypeId}", "/usageplans/{usageplanId}/keys/{keyId}/usage (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/usageplans/${UsageplanId}/keys/${KeyId}/usage", "/usageplans/{usageplanId}/usage (resource-path-specifier)": "arn:${Partition}:apigateway:${Region}::/usageplans/${UsageplanId}/usage", "Authorizer (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/authorizers/${Id}", "Authorizers (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/authorizers", "Deployment (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/deployments/${Id}", "Deployments (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/deployments", "Integration (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/resources/${ResourceId}/methods/${HttpMethod}/integration", "IntegrationResponse (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/resources/${ResourceId}/methods/${HttpMethod}/integration/responses/${StatusCode}", "Model (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/models/${ModelName}", "Models (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/models", "Stage (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/stages/${StageName}", "Stages (REST API resources)": "arn:${Partition}:apigateway:${Region}::/restapis/${ApiId}/stages"}}, "resourceTagKeys": {"access-analyzer": {"Analyzer": ["aws:ResourceTag/"]}, "acm": {"acme-domain-validation": ["aws:ResourceTag/"], "acme-endpoint": ["aws:ResourceTag/"], "acme-external-account-binding": ["aws:ResourceTag/"], "certificate": ["aws:ResourceTag/"]}, "airflow": {"environment": ["aws:ResourceTag/"], "rbac-role": ["aws:ResourceTag/"]}, "apigateway": {"AccessLogSettings": ["aws:ResourceTag/"], "Api": ["aws:ResourceTag/"], "ApiKey": ["aws:ResourceTag/"], "ApiKeys": ["aws:ResourceTag/"], "ApiMapping": ["aws:ResourceTag/"], "ApiMappings": ["aws:ResourceTag/"], "Apis": ["aws:ResourceTag/"], "Authorizer": ["aws:ResourceTag/"], "Authorizers": ["aws:ResourceTag/"], "AuthorizersCache": ["aws:ResourceTag/"], "BasePathMapping": ["aws:ResourceTag/"], "BasePathMappings": ["aws:ResourceTag/"], "ClientCertificate": ["aws:ResourceTag/"], "ClientCertificates": ["aws:ResourceTag/"], "Cors": ["aws:ResourceTag/"], "Deployment": ["aws:ResourceTag/"], "Deployments": ["aws:ResourceTag/"], "DocumentationPart": ["aws:ResourceTag/"], "DocumentationParts": ["aws:ResourceTag/"], "DocumentationVersion": ["aws:ResourceTag/"], "DocumentationVersions": ["aws:ResourceTag/"], "DomainName": ["aws:ResourceTag/"], "DomainNameAccessAssociations": ["aws:ResourceTag/"], "DomainNames": ["aws:ResourceTag/"], "ExportedAPI": ["aws:ResourceTag/"], "GatewayResponse": ["aws:ResourceTag/"], "GatewayResponses": ["aws:ResourceTag/"], "Integration": ["aws:ResourceTag/"], "IntegrationResponse": ["aws:ResourceTag/"], "IntegrationResponses": ["aws:ResourceTag/"], "Integrations": ["aws:ResourceTag/"], "Method": ["aws:ResourceTag/"], "MethodResponse": ["aws:ResourceTag/"], "Model": ["aws:ResourceTag/"], "ModelTemplate": ["aws:ResourceTag/"], "Models": ["aws:ResourceTag/"], "Portal": ["aws:ResourceTag/"], "PortalProduct": ["aws:ResourceTag/"], "PrivateBasePathMapping": ["aws:ResourceTag/"], "PrivateBasePathMappings": ["aws:ResourceTag/"], "PrivateDomainName": ["aws:ResourceTag/"], "ProductPage": ["aws:ResourceTag/"], "ProductRestEndpointPage": ["aws:ResourceTag/"], "RequestValidator": ["aws:ResourceTag/"], "RequestValidators": ["aws:ResourceTag/"], "Resource": ["aws:ResourceTag/"], "Resources": ["aws:ResourceTag/"], "RestApi": ["aws:ResourceTag/"], "RestApis": ["aws:ResourceTag/"], "Route": ["aws:ResourceTag/"], "RouteRequestParameter": ["aws:ResourceTag/"], "RouteResponse": ["aws:ResourceTag/"], "RouteResponses": ["aws:ResourceTag/"], "RouteSettings": ["aws:ResourceTag/"], "Routes": ["aws:ResourceTag/"], "RoutingRule": ["aws:ResourceTag/"], "Sdk": ["aws:ResourceTag/"], "Stage": ["aws:ResourceTag/"], "Stages": ["aws:ResourceTag/"], "Template": ["aws:ResourceTag/"], "UsagePlan": ["aws:ResourceTag/"], "UsagePlanKey": ["aws:ResourceTag/"], "UsagePlanKeys": ["aws:ResourceTag/"], "UsagePlans": ["aws:ResourceTag/"], "VpcLink": ["aws:ResourceTag/"], "VpcLinks": ["aws:ResourceTag/"]}, "app-integrations": {"application": ["aws:ResourceTag/"], "application-association": ["aws:ResourceTag/"], "data-integration": ["aws:ResourceTag/"], "data-integration-association": ["aws:ResourceTag/"], "event-integration": ["aws:ResourceTag/"], "event-integration-association": ["aws:ResourceTag/"]}, "appconfig": {"application": ["aws:ResourceTag/"], "configuration": ["aws:ResourceTag/"], "configurationprofile": ["aws:ResourceTag/"], "deployment": ["aws:ResourceTag/"], "deploymentstrategy": ["aws:ResourceTag/"], "environment": ["aws:ResourceTag/"], "experimentdefinition": ["aws:ResourceTag/"], "experimentrun": ["aws:ResourceTag/"], "extension": ["aws:ResourceTag/"], "extensionassociation": ["aws:ResourceTag/"]}, "application-autoscaling": {"ScalableTarget": ["aws:ResourceTag/"]}, "appsync": {"api": ["aws:ResourceTag/"], "channelNamespace": ["aws:ResourceTag/"], "domain": ["aws:ResourceTag/"], "graphqlapi": ["aws:ResourceTag/"]}, "aps": {"anomalydetector": ["aws:ResourceTag/"], "cluster": ["aws:ResourceTag/"], "rulegroupsnamespace": ["aws:ResourceTag/"], "scraper": ["aws:ResourceTag/"], "workspace": ["aws:ResourceTag/"]}, "athena": {"capacity-reservation": ["aws:ResourceTag/"], "datacatalog": ["aws:ResourceTag/"], "session": ["aws:ResourceTag/"], "system-table": ["aws:ResourceTag/"], "workgroup": ["aws:ResourceTag/"]}, "backup": {"backupAccessPoint": ["aws:ResourceTag/"], "backupPlan": ["aws:ResourceTag/"], "backupVault": ["aws:ResourceTag/"], "framework": ["aws:ResourceTag/"], "legalHold": ["aws:ResourceTag/"], "recoveryPoint": ["aws:ResourceTag/"], "reportPlan": ["aws:ResourceTag/"], "restoreTestingPlan": ["aws:ResourceTag/"], "tieringConfiguration": ["aws:ResourceTag/"]}, "batch": {"compute-environment": ["aws:ResourceTag/"], "consumable-resource": ["aws:ResourceTag/"], "job": ["aws:ResourceTag/"], "job-definition-revision": ["aws:ResourceTag/"], "job-queue": ["aws:ResourceTag/"], "quota-share": ["aws:ResourceTag/"], "scheduling-policy": ["aws:ResourceTag/"], "service-environment": ["aws:ResourceTag/"], "service-job": ["aws:ResourceTag/"]}, "bcm-data-exports": {"billingview": ["aws:ResourceTag/"], "export": ["aws:ResourceTag/"]}, "bcm-pricing-calculator": {"bill-estimate": ["aws:ResourceTag/"], "bill-scenario": ["aws:ResourceTag/"], "workload-estimate": ["aws:ResourceTag/"]}, "bedrock": {"advanced-prompt-optimization-job": ["aws:ResourceTag/"], "agent": ["aws:ResourceTag/"], "agent-alias": ["aws:ResourceTag/"], "anthropic-agent": ["aws:ResourceTag/"], "anthropic-memory-store": ["aws:ResourceTag/"], "anthropic-session": ["aws:ResourceTag/"], "application-inference-profile": ["aws:ResourceTag/"], "async-invoke": ["aws:ResourceTag/"], "automated-reasoning-policy": ["aws:ResourceTag/"], "automated-reasoning-policy-version": ["aws:ResourceTag/"], "blueprint": ["aws:ResourceTag/"], "blueprint-optimization-invocation": ["aws:ResourceTag/"], "custom-model": ["aws:ResourceTag/"], "custom-model-deployment": ["aws:ResourceTag/"], "data-automation-invocation-job": ["aws:ResourceTag/"], "data-automation-library": ["aws:ResourceTag/"], "data-automation-library-ingestion-job": ["aws:ResourceTag/"], "data-automation-project": ["aws:ResourceTag/"], "evaluation-job": ["aws:ResourceTag/"], "flow": ["aws:ResourceTag/"], "flow-alias": ["aws:ResourceTag/"], "guardrail": ["aws:ResourceTag/"], "imported-model": ["aws:ResourceTag/"], "knowledge-base": ["aws:ResourceTag/"], "model-copy-job": ["aws:ResourceTag/"], "model-customization-job": ["aws:ResourceTag/"], "model-evaluation-job": ["aws:ResourceTag/"], "model-import-job": ["aws:ResourceTag/"], "model-invocation-job": ["aws:ResourceTag/"], "project": ["aws:ResourceTag/"], "prompt": ["aws:ResourceTag/"], "prompt-router": ["aws:ResourceTag/"], "prompt-version": ["aws:ResourceTag/"], "provisioned-model": ["aws:ResourceTag/"], "retrieval-instruction": ["aws:ResourceTag/"], "session": ["aws:ResourceTag/"], "smart-router": ["aws:ResourceTag/"]}, "bedrock-agentcore": {"ab-test": ["aws:ResourceTag/"], "apikeycredentialprovider": ["aws:ResourceTag/"], "batch-evaluate": ["aws:ResourceTag/"], "browser-custom": ["aws:ResourceTag/"], "browser-profile": ["aws:ResourceTag/"], "capacity-provider": ["aws:ResourceTag/"], "code-interpreter-custom": ["aws:ResourceTag/"], "configuration-bundle": ["aws:ResourceTag/"], "consent-portal": ["aws:ResourceTag/"], "dataset": ["aws:ResourceTag/"], "evaluator": ["aws:ResourceTag/"], "gateway": ["aws:ResourceTag/"], "harness": ["aws:ResourceTag/"], "harness-endpoint": ["aws:ResourceTag/"], "memory": ["aws:ResourceTag/"], "oauth2credentialprovider": ["aws:ResourceTag/"], "online-evaluation-config": ["aws:ResourceTag/"], "payment-manager": ["aws:ResourceTag/"], "paymentcredentialprovider": ["aws:ResourceTag/"], "policy-engine": ["aws:ResourceTag/"], "recommendation": ["aws:ResourceTag/"], "runtime": ["aws:ResourceTag/"], "runtime-endpoint": ["aws:ResourceTag/"], "token-vault": ["aws:ResourceTag/"], "workload-identity": ["aws:ResourceTag/"], "workload-identity-directory": ["aws:ResourceTag/"]}, "budgets": {"budget": ["aws:ResourceTag/"], "budgetAction": ["aws:ResourceTag/"]}, "ce": {"anomalymonitor": ["aws:ResourceTag/"], "anomalysubscription": ["aws:ResourceTag/"], "billingview": ["aws:ResourceTag/"], "costcategory": ["aws:ResourceTag/"]}, "cloudformation": {"changeset": ["aws:ResourceTag/"], "stack": ["aws:ResourceTag/"], "stackset": ["aws:ResourceTag/"]}, "cloudfront": {"anycast-ip-list": ["aws:ResourceTag/"], "connection-function": ["aws:ResourceTag/"], "connection-group": ["aws:ResourceTag/"], "distribution": ["aws:ResourceTag/"], "distribution-tenant": ["aws:ResourceTag/"], "function": ["aws:ResourceTag/"], "key-value-store": ["aws:ResourceTag/"], "streaming-distribution": ["aws:ResourceTag/"], "trust-store": ["aws:ResourceTag/"], "vpcorigin": ["aws:ResourceTag/"]}, "cloudtrail": {"channel": ["aws:ResourceTag/"], "dashboard": ["aws:ResourceTag/"], "eventdatastore": ["aws:ResourceTag/"], "trail": ["aws:ResourceTag/"]}, "cloudwatch": {"access-grant": ["aws:ResourceTag/"], "access-profile": ["aws:ResourceTag/"], "alarm": ["aws:ResourceTag/"], "alarm-mute-rule": ["aws:ResourceTag/"], "alert": ["aws:ResourceTag/"], "dashboard": ["aws:ResourceTag/"], "dataset": ["aws:ResourceTag/"], "domain": ["aws:ResourceTag/"], "experiment": ["aws:ResourceTag/"], "ingestion-endpoint": ["aws:ResourceTag/"], "insight-rule": ["aws:ResourceTag/"], "integration": ["aws:ResourceTag/"], "lookup": ["aws:ResourceTag/"], "metric-query-definition": ["aws:ResourceTag/"], "metric-stream": ["aws:ResourceTag/"], "omni-agent-asset": ["aws:ResourceTag/"], "omni-dashboard": ["aws:ResourceTag/"], "omni-slo": ["aws:ResourceTag/"], "organization-access-grant": ["aws:ResourceTag/"], "organization-domain": ["aws:ResourceTag/"], "service": ["aws:ResourceTag/"], "slo": ["aws:ResourceTag/"], "space": ["aws:ResourceTag/"], "view": ["aws:ResourceTag/"]}, "codeartifact": {"domain": ["aws:ResourceTag/"], "package-group": ["aws:ResourceTag/"], "repository": ["aws:ResourceTag/"]}, "codebuild": {"project": ["aws:ResourceTag/"], "report-group": ["aws:ResourceTag/"]}, "codeguru-reviewer": {"association": ["aws:ResourceTag/"]}, "codepipeline": {"action": ["aws:ResourceTag/"], "actiontype": ["aws:ResourceTag/"], "pipeline": ["aws:ResourceTag/"], "stage": ["aws:ResourceTag/"], "webhook": ["aws:ResourceTag/"]}, "cognito-identity": {"identitypool": ["aws:ResourceTag/"]}, "cognito-idp": {"userpool": ["aws:ResourceTag/"]}, "comprehend": {"document-classification-job": ["aws:ResourceTag/"], "document-classifier": ["aws:ResourceTag/"], "document-classifier-endpoint": ["aws:ResourceTag/"], "dominant-language-detection-job": ["aws:ResourceTag/"], "entities-detection-job": ["aws:ResourceTag/"], "entity-recognizer": ["aws:ResourceTag/"], "entity-recognizer-endpoint": ["aws:ResourceTag/"], "events-detection-job": ["aws:ResourceTag/"], "flywheel": ["aws:ResourceTag/"], "flywheel-dataset": ["aws:ResourceTag/"], "key-phrases-detection-job": ["aws:ResourceTag/"], "pii-entities-detection-job": ["aws:ResourceTag/"], "sentiment-detection-job": ["aws:ResourceTag/"], "targeted-sentiment-detection-job": ["aws:ResourceTag/"], "topics-detection-job": ["aws:ResourceTag/"]}, "config": {"AggregationAuthorization": ["aws:ResourceTag/"], "ConfigRule": ["aws:ResourceTag/"], "ConfigurationAggregator": ["aws:ResourceTag/"], "ConfigurationRecorder": ["aws:ResourceTag/"], "ConformancePack": ["aws:ResourceTag/"], "Connector": ["aws:ResourceTag/"], "OrganizationConfigRule": ["aws:ResourceTag/"], "OrganizationConformancePack": ["aws:ResourceTag/"], "StoredQuery": ["aws:ResourceTag/"]}, "connect": {"agent-status": ["aws:ResourceTag/"], "ai-agent": ["aws:ResourceTag/"], "application": ["aws:ResourceTag/"], "attached-file": ["aws:ResourceTag/"], "authentication-profile": ["aws:ResourceTag/"], "contact": ["aws:ResourceTag/"], "contact-evaluation": ["aws:ResourceTag/"], "contact-flow": ["aws:ResourceTag/"], "contact-flow-module": ["aws:ResourceTag/"], "customer-managed-view": ["aws:ResourceTag/"], "customer-managed-view-version": ["aws:ResourceTag/"], "data-table": ["aws:ResourceTag/"], "email-address": ["aws:ResourceTag/"], "evaluation-form": ["aws:ResourceTag/"], "extraction-definition": ["aws:ResourceTag/"], "hierarchy-group": ["aws:ResourceTag/"], "hours-of-operation": ["aws:ResourceTag/"], "instance": ["aws:ResourceTag/"], "integration-association": ["aws:ResourceTag/"], "metric": ["aws:ResourceTag/"], "notification": ["aws:ResourceTag/"], "phone-number": ["aws:ResourceTag/"], "prompt": ["aws:ResourceTag/"], "qualified-customer-managed-view": ["aws:ResourceTag/"], "qualified-metric": ["aws:ResourceTag/"], "queue": ["aws:ResourceTag/"], "quick-connect": ["aws:ResourceTag/"], "routing-profile": ["aws:ResourceTag/"], "rule": ["aws:ResourceTag/"], "security-profile": ["aws:ResourceTag/"], "task-template": ["aws:ResourceTag/"], "traffic-distribution-group": ["aws:ResourceTag/"], "use-case": ["aws:ResourceTag/"], "user": ["aws:ResourceTag/"], "vocabulary": ["aws:ResourceTag/"], "wildcard-phone-number": ["aws:ResourceTag/"], "workspace": ["aws:ResourceTag/"]}, "controltower": {"EnabledBaseline": ["aws:ResourceTag/"], "EnabledControl": ["aws:ResourceTag/"], "LandingZone": ["aws:ResourceTag/"]}, "datasync": {"agent": ["aws:ResourceTag/"], "discoveryjob": ["aws:ResourceTag/"], "location": ["aws:ResourceTag/"], "storagesystem": ["aws:ResourceTag/"], "task": ["aws:ResourceTag/"], "taskexecution": ["aws:ResourceTag/"]}, "detective": {"Graph": ["aws:ResourceTag/"]}, "dlm": {"policy": ["aws:ResourceTag/"]}, "dms": {"Certificate": ["aws:ResourceTag/"], "DataMigration": ["aws:ResourceTag/"], "DataProvider": ["aws:ResourceTag/"], "Endpoint": ["aws:ResourceTag/"], "EventSubscription": ["aws:ResourceTag/"], "InstanceProfile": ["aws:ResourceTag/"], "MigrationProject": ["aws:ResourceTag/"], "ReplicationConfig": ["aws:ResourceTag/"], "ReplicationInstance": ["aws:ResourceTag/"], "ReplicationSubnetGroup": ["aws:ResourceTag/"], "ReplicationTask": ["aws:ResourceTag/"], "ReplicationTaskAssessmentRun": ["aws:ResourceTag/"], "ReplicationTaskIndividualAssessment": ["aws:ResourceTag/"]}, "dsql": {"Cluster": ["aws:ResourceTag/"], "Stream": ["aws:ResourceTag/"]}, "dynamodb": {"index": ["aws:ResourceTag/"], "stream": ["aws:ResourceTag/"], "table": ["aws:ResourceTag/"]}, "ec2": {"application-status-check": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-block": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-manager-data-export": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-cancellation-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "capacity-reservation-modification-quote": ["aws:ResourceTag/", "ec2:ResourceTag/"], "carrier-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "client-vpn-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "coip-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "customer-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "declarative-policies-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dedicated-host": ["aws:ResourceTag/", "ec2:ResourceTag/"], "dhcp-options": ["aws:ResourceTag/", "ec2:ResourceTag/"], "egress-only-internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-gpu": ["aws:ResourceTag/", "ec2:ResourceTag/"], "elastic-ip": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "export-instance-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fleet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "fpga-image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "host-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image": ["aws:ResourceTag/", "ec2:ResourceTag/"], "image-usage-report": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-image-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "import-snapshot-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-connect-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-event-window": ["aws:ResourceTag/", "ec2:ResourceTag/"], "internet-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-external-resource-verification-token": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-internet-registry-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-policy": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-pool-allocation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-prefix-list-resolver-target": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-resource-discovery-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipam-scope": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipv4pool-ec2": ["aws:ResourceTag/", "ec2:ResourceTag/"], "ipv6pool-ec2": ["aws:ResourceTag/", "ec2:ResourceTag/"], "key-pair": ["aws:ResourceTag/", "ec2:ResourceTag/"], "launch-template": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table-virtual-interface-group-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-route-table-vpc-association": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-virtual-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "local-gateway-virtual-interface-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "mac-modification-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "natgateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-acl": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-access-scope": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-access-scope-analysis": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-analysis": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-insights-path": ["aws:ResourceTag/", "ec2:ResourceTag/"], "network-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "outpost-lag": ["aws:ResourceTag/", "ec2:ResourceTag/"], "placement-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "prefix-list": ["aws:ResourceTag/", "ec2:ResourceTag/"], "replace-root-volume-task": ["aws:ResourceTag/", "ec2:ResourceTag/"], "reserved-instances": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-server-peer": ["aws:ResourceTag/", "ec2:ResourceTag/"], "route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-interface": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-network": ["aws:ResourceTag/", "ec2:ResourceTag/"], "secondary-subnet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "security-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "security-group-rule": ["aws:ResourceTag/", "ec2:ResourceTag/"], "snapshot": ["aws:ResourceTag/", "ec2:ResourceTag/"], "spot-fleet-request": ["aws:ResourceTag/", "ec2:ResourceTag/"], "spot-instances-request": ["aws:ResourceTag/", "ec2:ResourceTag/"], "subnet": ["aws:ResourceTag/", "ec2:ResourceTag/"], "subnet-cidr-reservation": ["aws:ResourceTag/", "ec2:ResourceTag/"], "traffic-mirror-filter": ["aws:ResourceTag/", "ec2:ResourceTag/"], "traffic-mirror-filter-rule": ["aws:ResourceTag/", "ec2:ResourceTag/"], "traffic-mirror-session": ["aws:ResourceTag/", "ec2:ResourceTag/"], "traffic-mirror-target": ["aws:ResourceTag/", "ec2:ResourceTag/"], "transit-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"], "transit-gateway-attachment": ["aws:ResourceTag/", "ec2:ResourceTag/"], "transit-gateway-connect-peer": ["aws:ResourceTag/", "ec2:ResourceTag/"], "transit-gateway-metering-policy": ["aws:ResourceTag/", "ec2:ResourceTag/"], "transit-gateway-multicast-domain": ["aws:ResourceTag/", "ec2:ResourceTag/"], "transit-gateway-policy-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "transit-gateway-route-table": ["aws:ResourceTag/", "ec2:ResourceTag/"], "transit-gateway-route-table-announcement": ["aws:ResourceTag/", "ec2:ResourceTag/"], "verified-access-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "verified-access-endpoint-target": ["aws:ResourceTag/", "ec2:ResourceTag/"], "verified-access-group": ["aws:ResourceTag/", "ec2:ResourceTag/"], "verified-access-instance": ["aws:ResourceTag/", "ec2:ResourceTag/"], "verified-access-policy": ["aws:ResourceTag/", "ec2:ResourceTag/"], "verified-access-trust-provider": ["aws:ResourceTag/", "ec2:ResourceTag/"], "volume": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc-block-public-access-exclusion": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc-encryption-control": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc-endpoint-connection": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc-endpoint-service": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc-endpoint-service-permission": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc-flow-log": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpc-peering-connection": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpn-concentrator": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpn-connection": ["aws:ResourceTag/", "ec2:ResourceTag/"], "vpn-gateway": ["aws:ResourceTag/", "ec2:ResourceTag/"]}, "ec2-instance-connect": {"instance": ["aws:ResourceTag/", "ec2:ResourceTag/"], "instance-connect-endpoint": ["aws:ResourceTag/", "ec2:ResourceTag/"]}, "ecr": {"repository": ["aws:ResourceTag/", "ecr:ResourceTag/"]}, "ecs": {"capacity-provider": ["aws:ResourceTag/", "ecs:ResourceTag/"], "cluster": ["aws:ResourceTag/", "ecs:ResourceTag/"], "container-instance": ["aws:ResourceTag/", "ecs:ResourceTag/"], "daemon": ["aws:ResourceTag/"], "daemon-deployment": ["aws:ResourceTag/"], "daemon-revision": ["aws:ResourceTag/"], "daemon-task-definition": ["aws:ResourceTag/"], "gateway": ["aws:ResourceTag/"], "gateway-route": ["aws:ResourceTag/"], "service": ["aws:ResourceTag/", "ecs:ResourceTag/"], "service-deployment": ["aws:ResourceTag/"], "service-revision": ["aws:ResourceTag/"], "task": ["aws:ResourceTag/", "ecs:ResourceTag/"], "task-definition": ["aws:ResourceTag/", "ecs:ResourceTag/"], "task-set": ["aws:ResourceTag/", "ecs:ResourceTag/"]}, "eks": {"access-entry": ["aws:ResourceTag/"], "addon": ["aws:ResourceTag/"], "capability": ["aws:ResourceTag/"], "cluster": ["aws:ResourceTag/"], "dashboard": ["aws:ResourceTag/"], "eks-anywhere-subscription": ["aws:ResourceTag/"], "fargateprofile": ["aws:ResourceTag/"], "identityproviderconfig": ["aws:ResourceTag/"], "nodegroup": ["aws:ResourceTag/"], "podidentityassociation": ["aws:ResourceTag/"]}, "elasticache": {"cluster": ["aws:ResourceTag/"], "globalreplicationgroup": ["aws:ResourceTag/"], "parametergroup": ["aws:ResourceTag/"], "replicationgroup": ["aws:ResourceTag/"], "reserved-instance": ["aws:ResourceTag/"], "securitygroup": ["aws:ResourceTag/"], "serverlesscache": ["aws:ResourceTag/"], "serverlesscachesnapshot": ["aws:ResourceTag/"], "snapshot": ["aws:ResourceTag/"], "subnetgroup": ["aws:ResourceTag/"], "user": ["aws:ResourceTag/"], "usergroup": ["aws:ResourceTag/"]}, "elasticfilesystem": {"access-point": ["aws:ResourceTag/"], "file-system": ["aws:ResourceTag/"]}, "elasticloadbalancing": {"listener-rule/app": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "listener-rule/net": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "listener/app": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "listener/gwy": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "listener/net": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "loadbalancer": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "loadbalancer/app/": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "loadbalancer/gwy/": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "loadbalancer/net/": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "proxy": ["aws:ResourceTag/"], "targetgroup": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"], "truststore": ["aws:ResourceTag/", "elasticloadbalancing:ResourceTag/"]}, "elasticmapreduce": {"cluster": ["aws:ResourceTag/", "elasticmapreduce:ResourceTag/"], "editor": ["aws:ResourceTag/", "elasticmapreduce:ResourceTag/"], "notebook-execution": ["aws:ResourceTag/", "elasticmapreduce:ResourceTag/"], "session": ["aws:ResourceTag/", "elasticmapreduce:ResourceTag/"], "studio": ["aws:ResourceTag/", "elasticmapreduce:ResourceTag/"]}, "emr-containers": {"jobRun": ["aws:ResourceTag/"], "jobTemplate": ["aws:ResourceTag/"], "managedEndpoint": ["aws:ResourceTag/"], "securityConfiguration": ["aws:ResourceTag/"], "virtualCluster": ["aws:ResourceTag/"]}, "emr-serverless": {"application": ["aws:ResourceTag/"], "jobRun": ["aws:ResourceTag/"], "session": ["aws:ResourceTag/"]}, "es": {"application": ["aws:ResourceTag/"], "datasource": ["aws:ResourceTag/"], "domain": ["aws:ResourceTag/"], "es_role": ["aws:ResourceTag/"], "opensearchservice_role": ["aws:ResourceTag/"]}, "events": {"event-bus": ["aws:ResourceTag/"], "event-busv2": ["aws:ResourceTag/"], "event-sourcev2": ["aws:ResourceTag/"], "rule-on-custom-event-bus": ["aws:ResourceTag/"], "rule-on-default-event-bus": ["aws:ResourceTag/"], "subscriber": ["aws:ResourceTag/"]}, "firehose": {"deliverystream": ["aws:ResourceTag/"]}, "fis": {"action": ["aws:ResourceTag/"], "experiment": ["aws:ResourceTag/"], "experiment-template": ["aws:ResourceTag/"]}, "globalaccelerator": {"accelerator": ["aws:ResourceTag/"], "attachment": ["aws:ResourceTag/"], "endpointgroup": ["aws:ResourceTag/"], "listener": ["aws:ResourceTag/"]}, "glue": {"blueprint": ["aws:ResourceTag/"], "catalog": ["aws:ResourceTag/"], "connection": ["aws:ResourceTag/"], "connectionType": ["aws:ResourceTag/"], "crawler": ["aws:ResourceTag/"], "customEntityType": ["aws:ResourceTag/"], "dataQualityEvaluationConfig": ["aws:ResourceTag/"], "dataQualityRuleset": ["aws:ResourceTag/"], "database": ["aws:ResourceTag/"], "devendpoint": ["aws:ResourceTag/"], "integration": ["aws:ResourceTag/"], "integrationResourceProperty": ["aws:ResourceTag/"], "job": ["aws:ResourceTag/"], "mlTransform": ["aws:ResourceTag/"], "registry": ["aws:ResourceTag/"], "schema": ["aws:ResourceTag/"], "session": ["aws:ResourceTag/"], "table": ["aws:ResourceTag/"], "tableversion": ["aws:ResourceTag/"], "trigger": ["aws:ResourceTag/"], "usageProfile": ["aws:ResourceTag/"], "userdefinedfunction": ["aws:ResourceTag/"], "workflow": ["aws:ResourceTag/"]}, "guardduty": {"customdetectionruleassociation": ["aws:ResourceTag/"], "detector": ["aws:ResourceTag/"], "filter": ["aws:ResourceTag/"], "ipset": ["aws:ResourceTag/"], "malwareprotectionplan": ["aws:ResourceTag/"], "publishingDestination": ["aws:ResourceTag/"], "threatentityset": ["aws:ResourceTag/"], "threatintelset": ["aws:ResourceTag/"], "trustedentityset": ["aws:ResourceTag/"]}, "iam": {"instance-profile": ["aws:ResourceTag/"], "mfa": ["aws:ResourceTag/"], "oidc-provider": ["aws:ResourceTag/"], "policy": ["aws:ResourceTag/"], "role": ["aws:ResourceTag/", "iam:ResourceTag/"], "saml-provider": ["aws:ResourceTag/"], "server-certificate": ["aws:ResourceTag/"], "user": ["aws:ResourceTag/", "iam:ResourceTag/"], "workload-identity-provider": ["aws:ResourceTag/"], "workload-identity-template": ["aws:ResourceTag/"]}, "inspector2": {"CIS Scan Configuration": ["aws:ResourceTag/"], "Code Security Integration": ["aws:ResourceTag/"], "Code Security Scan Configuration": ["aws:ResourceTag/"], "Connector": ["aws:ResourceTag/"], "Filter": ["aws:ResourceTag/"]}, "kafka": {"assessment": ["aws:ResourceTag/"], "channel": ["aws:ResourceTag/"], "cluster": ["aws:ResourceTag/"], "replicator": ["aws:ResourceTag/"], "vpc-connection": ["aws:ResourceTag/"]}, "kinesis": {"channel": ["aws:ResourceTag/"], "consumer": ["aws:ResourceTag/"], "kmsKey": ["aws:ResourceTag/"], "queue": ["aws:ResourceTag/"], "stream": ["aws:ResourceTag/"]}, "kinesisanalytics": {"application": ["aws:ResourceTag/"], "snapshot": ["aws:ResourceTag/"]}, "kinesisvideo": {"channel": ["aws:ResourceTag/"], "stream": ["aws:ResourceTag/"]}, "kms": {"key": ["aws:ResourceTag/"]}, "lambda": {"capacityProvider": ["aws:ResourceTag/"], "code signing config": ["aws:ResourceTag/"], "durable execution": ["aws:ResourceTag/"], "eventSourceMapping": ["aws:ResourceTag/"], "function": ["aws:ResourceTag/"], "function alias": ["aws:ResourceTag/"], "function version": ["aws:ResourceTag/"], "microvmImage": ["aws:ResourceTag/"], "networkConnector": ["aws:ResourceTag/"], "runtime": ["aws:ResourceTag/"], "runtimeAlias": ["aws:ResourceTag/"], "runtimeVersion": ["aws:ResourceTag/"], "webFunction": ["aws:ResourceTag/"], "webFunctionEndpoint": ["aws:ResourceTag/"], "webFunctionRevision": ["aws:ResourceTag/"]}, "lightsail": {"Alarm": ["aws:ResourceTag/"], "Bucket": ["aws:ResourceTag/"], "Certificate": ["aws:ResourceTag/"], "ContactMethod": ["aws:ResourceTag/"], "ContainerService": ["aws:ResourceTag/"], "Disk": ["aws:ResourceTag/"], "DiskSnapshot": ["aws:ResourceTag/"], "Distribution": ["aws:ResourceTag/"], "Domain": ["aws:ResourceTag/"], "Instance": ["aws:ResourceTag/"], "InstanceSnapshot": ["aws:ResourceTag/"], "KeyPair": ["aws:ResourceTag/"], "LoadBalancer": ["aws:ResourceTag/"], "RelationalDatabase": ["aws:ResourceTag/"], "RelationalDatabaseSnapshot": ["aws:ResourceTag/"], "StaticIp": ["aws:ResourceTag/"]}, "logs": {"anomaly-detector": ["aws:ResourceTag/"], "delivery": ["aws:ResourceTag/"], "delivery-destination": ["aws:ResourceTag/"], "delivery-source": ["aws:ResourceTag/"], "destination": ["aws:ResourceTag/"], "log-group": ["aws:ResourceTag/"], "log-stream": ["aws:ResourceTag/"], "lookup-table": ["aws:ResourceTag/"], "scheduled-query": ["aws:ResourceTag/"]}, "macie2": {"AllowList": ["aws:ResourceTag/"], "ClassificationJob": ["aws:ResourceTag/"], "CustomDataIdentifier": ["aws:ResourceTag/"], "FindingsFilter": ["aws:ResourceTag/"], "Member": ["aws:ResourceTag/"]}, "memorydb": {"acl": ["aws:ResourceTag/"], "cluster": ["aws:ResourceTag/"], "multiregioncluster": ["aws:ResourceTag/"], "parametergroup": ["aws:ResourceTag/"], "reservednode": ["aws:ResourceTag/"], "snapshot": ["aws:ResourceTag/"], "subnetgroup": ["aws:ResourceTag/"], "user": ["aws:ResourceTag/"]}, "mq": {"brokers": ["aws:ResourceTag/"], "configurations": ["aws:ResourceTag/"]}, "network-firewall": {"ContainerAssociation": ["aws:ResourceTag/"], "Firewall": ["aws:ResourceTag/"], "FirewallPolicy": ["aws:ResourceTag/"], "FirewallPolicyV2": ["aws:ResourceTag/"], "FirewallRuleGroup": ["aws:ResourceTag/"], "IpsRuleGroup": ["aws:ResourceTag/"], "Proxy": ["aws:ResourceTag/"], "ProxyConfiguration": ["aws:ResourceTag/"], "ProxyRuleGroup": ["aws:ResourceTag/"], "StatefulRuleGroup": ["aws:ResourceTag/"], "StatelessRuleGroup": ["aws:ResourceTag/"], "TLSInspectionConfiguration": ["aws:ResourceTag/"], "VpcEndpointAssociation": ["aws:ResourceTag/"]}, "oam": {"Link": ["aws:ResourceTag/"], "Sink": ["aws:ResourceTag/"]}, "observabilityadmin": {"connector": ["aws:ResourceTag/"], "dataset-integration": ["aws:ResourceTag/"], "organization-centralization-rule": ["aws:ResourceTag/"], "organization-telemetry-rule": ["aws:ResourceTag/"], "s3tableintegration": ["aws:ResourceTag/"], "telemetry-enrichment": ["aws:ResourceTag/"], "telemetry-pipeline": ["aws:ResourceTag/"], "telemetry-rule": ["aws:ResourceTag/"]}, "organizations": {"account": ["aws:ResourceTag/"], "organizationalunit": ["aws:ResourceTag/"], "policy": ["aws:ResourceTag/"], "resourcepolicy": ["aws:ResourceTag/"], "responsibilitytransfer": ["aws:ResourceTag/"], "root": ["aws:ResourceTag/"]}, "payment-cryptography": {"approval-team": ["aws:ResourceTag/"], "key": ["aws:ResourceTag/"]}, "pipes": {"pipe": ["aws:ResourceTag/"]}, "quicksight": {"accessControlApplication": ["aws:ResourceTag/"], "actionconnector": ["aws:ResourceTag/"], "analysis": ["aws:ResourceTag/"], "app": ["aws:ResourceTag/"], "brand": ["aws:ResourceTag/"], "customization": ["aws:ResourceTag/"], "custompermissions": ["aws:ResourceTag/"], "dashboard": ["aws:ResourceTag/"], "dashboardSnapshotJob": ["aws:ResourceTag/"], "dataset": ["aws:ResourceTag/"], "datasource": ["aws:ResourceTag/"], "dlpSetting": ["aws:ResourceTag/"], "emailCustomizationTemplate": ["aws:ResourceTag/"], "flow": ["aws:ResourceTag/"], "folder": ["aws:ResourceTag/"], "inboundConnector": ["aws:ResourceTag/"], "ingestion": ["aws:ResourceTag/"], "knowledgeBase": ["aws:ResourceTag/"], "namespace": ["aws:ResourceTag/"], "oauthClientApplication": ["aws:ResourceTag/"], "template": ["aws:ResourceTag/"], "theme": ["aws:ResourceTag/"], "topic": ["aws:ResourceTag/"], "user": ["aws:ResourceTag/"], "vpcconnection": ["aws:ResourceTag/"]}, "ram": {"customer-managed-permission": ["aws:ResourceTag/", "ram:ResourceTag/"], "resource-share": ["aws:ResourceTag/", "ram:ResourceTag/"]}, "rds": {"auto-backup": ["aws:ResourceTag/"], "branch": ["aws:ResourceTag/"], "cev": ["aws:ResourceTag/"], "cluster": ["aws:ResourceTag/", "rds:cluster-tag/"], "cluster-auto-backup": ["aws:ResourceTag/"], "cluster-endpoint": ["aws:ResourceTag/"], "cluster-group": ["aws:ResourceTag/"], "cluster-group-auto-backup": ["aws:ResourceTag/"], "cluster-group-snapshot": ["aws:ResourceTag/"], "cluster-pg": ["aws:ResourceTag/", "rds:cluster-pg-tag/"], "cluster-snapshot": ["aws:ResourceTag/", "rds:cluster-snapshot-tag/"], "db": ["aws:ResourceTag/", "rds:db-tag/"], "db-capacity-reservation": ["aws:ResourceTag/"], "deployment": ["aws:ResourceTag/"], "es": ["aws:ResourceTag/", "rds:es-tag/"], "global-cluster": ["aws:ResourceTag/"], "integration": ["aws:ResourceTag/"], "og": ["aws:ResourceTag/", "rds:og-tag/"], "pg": ["aws:ResourceTag/", "rds:pg-tag/"], "proxy": ["aws:ResourceTag/"], "proxy-endpoint": ["aws:ResourceTag/"], "ri": ["aws:ResourceTag/", "rds:ri-tag/"], "secgrp": ["aws:ResourceTag/", "rds:secgrp-tag/"], "shardgrp": ["aws:ResourceTag/"], "snapshot": ["aws:ResourceTag/", "rds:snapshot-tag/"], "snapshot-tenant-database": ["aws:ResourceTag/"], "subgrp": ["aws:ResourceTag/", "rds:subgrp-tag/"], "target-group": ["aws:ResourceTag/"], "tenant-database": ["aws:ResourceTag/"]}, "rds-data": {"cluster": ["aws:ResourceTag/"]}, "redshift": {"cluster": ["aws:ResourceTag/"], "datashare": ["aws:ResourceTag/"], "eventsubscription": ["aws:ResourceTag/"], "hsmclientcertificate": ["aws:ResourceTag/"], "hsmconfiguration": ["aws:ResourceTag/"], "integration": ["aws:ResourceTag/"], "parametergroup": ["aws:ResourceTag/"], "qev2idcapplication": ["aws:ResourceTag/"], "redshiftidcapplication": ["aws:ResourceTag/"], "securitygroup": ["aws:ResourceTag/"], "securitygroupingress-cidr": ["aws:ResourceTag/"], "securitygroupingress-ec2securitygroup": ["aws:ResourceTag/"], "snapshot": ["aws:ResourceTag/"], "snapshotcopygrant": ["aws:ResourceTag/"], "snapshotschedule": ["aws:ResourceTag/"], "subnetgroup": ["aws:ResourceTag/"], "usagelimit": ["aws:ResourceTag/"]}, "redshift-data": {"cluster": ["aws:ResourceTag/"], "workgroup": ["aws:ResourceTag/"]}, "redshift-serverless": {"expressConfiguration": ["aws:ResourceTag/"], "namespace": ["aws:ResourceTag/"], "recoveryPoint": ["aws:ResourceTag/"], "snapshot": ["aws:ResourceTag/"], "workgroup": ["aws:ResourceTag/"]}, "rekognition": {"collection": ["aws:ResourceTag/"], "dataset": ["aws:ResourceTag/"], "project": ["aws:ResourceTag/"], "projectversion": ["aws:ResourceTag/"], "streamprocessor": ["aws:ResourceTag/"]}, "resource-explorer-2": {"index": ["aws:ResourceTag/"], "view": ["aws:ResourceTag/"]}, "resource-groups": {"group": ["aws:ResourceTag/"], "tagSyncTask": ["aws:ResourceTag/"]}, "route53": {"healthchecksource": ["aws:ResourceTag/"]}, "route53resolver": {"autodefined-rule": ["aws:ResourceTag/"], "firewall-config": ["aws:ResourceTag/"], "firewall-domain-list": ["aws:ResourceTag/"], "firewall-rule-group": ["aws:ResourceTag/"], "firewall-rule-group-association": ["aws:ResourceTag/"], "outpost-resolver": ["aws:ResourceTag/"], "resolver-dnssec-config": ["aws:ResourceTag/"], "resolver-endpoint": ["aws:ResourceTag/"], "resolver-query-log-config": ["aws:ResourceTag/"], "resolver-rule": ["aws:ResourceTag/"]}, "rum": {"AppMonitorResource": ["aws:ResourceTag/"]}, "s3": {"accessgrant": ["aws:ResourceTag/"], "accessgrantsinstance": ["aws:ResourceTag/"], "accessgrantslocation": ["aws:ResourceTag/"], "accesspoint": ["aws:ResourceTag/", "s3:AccessPointTag/"], "accesspointobject": ["aws:ResourceTag/"], "bucket": ["aws:ResourceTag/", "s3:BucketTag/"], "job": ["aws:ResourceTag/"], "object": ["aws:ResourceTag/"], "storagelensconfiguration": ["aws:ResourceTag/"], "storagelensgroup": ["aws:ResourceTag/"]}, "s3tables": {"StorageLens": ["aws:ResourceTag/"], "Table": ["aws:ResourceTag/"], "TableBucket": ["aws:ResourceTag/", "s3tables:TableBucketTag/"]}, "s3vectors": {"Index": ["aws:ResourceTag/"], "VectorBucket": ["aws:ResourceTag/", "s3vectors:VectorBucketTag/"]}, "sagemaker": {"action": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "ai-benchmark-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "ai-recommendation-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "ai-workload-config": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "algorithm": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "app": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "app-image-config": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "artifact": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "automl-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "cluster": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "cluster-scheduler-config": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "code-repository": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "compilation-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "compute-quota": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "context": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "data-quality-job-definition": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "device": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "device-fleet": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "domain": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "edge-deployment-plan": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "edge-packaging-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "endpoint": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "endpoint-config": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "experiment": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "experiment-trial": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "experiment-trial-component": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "extension": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "feature-group": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "flow-definition": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "global-inference-gateway": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "hub": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "hub-content": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "human-task-ui": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "hyper-parameter-tuning-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "image": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "image-version": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "inference-component": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "inference-experiment": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "inference-recommendations-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "inference-router": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "labeling-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "leaderboard": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "lineage-group": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "mlflow-app": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model-bias-job-definition": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model-card": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model-card-export-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model-explainability-job-definition": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model-monitor-config": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model-package": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model-package-group": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "model-quality-job-definition": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "monitoring-schedule": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "notebook-instance": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "notebook-instance-lifecycle-config": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "optimization-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "partner-app": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "pipeline": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "pipeline-execution": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "processing-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "project": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "reserved-capacity": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "sm-capacity-reservation": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "space": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "studio-lifecycle-config": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "training-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "training-plan": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "training-session": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "transform-job": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "user-profile": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "workforce": ["aws:ResourceTag/", "sagemaker:ResourceTag/"], "workteam": ["aws:ResourceTag/", "sagemaker:ResourceTag/"]}, "scheduler": {"schedule-group": ["aws:ResourceTag/"]}, "secretsmanager": {"Secret": ["aws:ResourceTag/", "secretsmanager:ResourceTag/"]}, "securityhub": {"aggregatorv2": ["aws:ResourceTag/"], "automation-rule": ["aws:ResourceTag/"], "automation-rulev2": ["aws:ResourceTag/"], "configuration-policy": ["aws:ResourceTag/"], "connector": ["aws:ResourceTag/"], "connectorv2": ["aws:ResourceTag/"], "hub": ["aws:ResourceTag/"], "hubv2": ["aws:ResourceTag/"]}, "servicediscovery": {"namespace": ["aws:ResourceTag/"], "service": ["aws:ResourceTag/"]}, "ses": {"addon-instance": ["aws:ResourceTag/"], "addon-subscription": ["aws:ResourceTag/"], "configuration-set": ["aws:ResourceTag/"], "contact-list": ["aws:ResourceTag/"], "custom-verification-email-template": ["aws:ResourceTag/"], "dedicated-ip-pool": ["aws:ResourceTag/"], "deliverability-test-report": ["aws:ResourceTag/"], "identity": ["aws:ResourceTag/"], "mailmanager-address-list": ["aws:ResourceTag/"], "mailmanager-archive": ["aws:ResourceTag/"], "mailmanager-ingress-point": ["aws:ResourceTag/"], "mailmanager-rule-set": ["aws:ResourceTag/"], "mailmanager-smtp-relay": ["aws:ResourceTag/"], "mailmanager-traffic-policy": ["aws:ResourceTag/"], "multi-region-endpoint": ["aws:ResourceTag/"], "template": ["aws:ResourceTag/"], "tenant": ["aws:ResourceTag/"]}, "signer": {"signing-profile": ["aws:ResourceTag/"]}, "sns": {"topic": ["aws:ResourceTag/"]}, "sqs": {"queue": ["aws:ResourceTag/"]}, "ssm": {"association": ["aws:ResourceTag/"], "automation-execution": ["aws:ResourceTag/", "ssm:resourceTag/"], "cloud-connector": ["aws:ResourceTag/"], "document": ["aws:ResourceTag/", "ssm:resourceTag/"], "instance": ["aws:ResourceTag/", "ssm:resourceTag/"], "maintenancewindow": ["aws:ResourceTag/", "ssm:resourceTag/"], "managed-instance": ["aws:ResourceTag/", "ssm:resourceTag/"], "opsitem": ["aws:ResourceTag/"], "opsmetadata": ["aws:ResourceTag/", "ssm:resourceTag/"], "parameter": ["aws:ResourceTag/", "ssm:resourceTag/"], "patchbaseline": ["aws:ResourceTag/", "ssm:resourceTag/"], "task": ["aws:ResourceTag/"], "windowtarget": ["aws:ResourceTag/", "ssm:resourceTag/"], "windowtask": ["aws:ResourceTag/", "ssm:resourceTag/"]}, "sso": {"Application": ["aws:ResourceTag/"], "Instance": ["aws:ResourceTag/"], "PermissionSet": ["aws:ResourceTag/"], "TrustedTokenIssuer": ["aws:ResourceTag/"]}, "states": {"activity": ["aws:ResourceTag/"], "execution": ["aws:ResourceTag/"], "statemachine": ["aws:ResourceTag/"], "statemachinealias": ["aws:ResourceTag/"], "statemachineversion": ["aws:ResourceTag/"]}, "sts": {"role": ["aws:ResourceTag/", "iam:ResourceTag/"]}, "textract": {"adapter": ["aws:ResourceTag/"], "adapterversion": ["aws:ResourceTag/"], "blueprint": ["aws:ResourceTag/"], "job": ["aws:ResourceTag/"], "project": ["aws:ResourceTag/"]}, "timestream-influxdb": {"db-backup": ["aws:ResourceTag/"], "db-cluster": ["aws:ResourceTag/"], "db-instance": ["aws:ResourceTag/"], "db-parameter-group": ["aws:ResourceTag/"]}, "transcribe": {"callanalyticscategory": ["aws:ResourceTag/"], "callanalyticsjob": ["aws:ResourceTag/"], "languagemodel": ["aws:ResourceTag/"], "medicalscribejob": ["aws:ResourceTag/"], "medicaltranscriptionjob": ["aws:ResourceTag/"], "medicalvocabulary": ["aws:ResourceTag/"], "transcriptionjob": ["aws:ResourceTag/"], "vocabulary": ["aws:ResourceTag/"], "vocabularyfilter": ["aws:ResourceTag/"]}, "transfer": {"agreement": ["aws:ResourceTag/"], "certificate": ["aws:ResourceTag/"], "connector": ["aws:ResourceTag/"], "host-key": ["aws:ResourceTag/"], "profile": ["aws:ResourceTag/"], "server": ["aws:ResourceTag/"], "user": ["aws:ResourceTag/"], "webapp": ["aws:ResourceTag/"], "workflow": ["aws:ResourceTag/"]}, "translate": {"parallel-data": ["aws:ResourceTag/"], "terminology": ["aws:ResourceTag/"]}, "wafv2": {"ipset": ["aws:ResourceTag/"], "regexpatternset": ["aws:ResourceTag/"], "rulegroup": ["aws:ResourceTag/"], "webacl": ["aws:ResourceTag/"]}, "xray": {"group": ["aws:ResourceTag/"], "sampling-rule": ["aws:ResourceTag/"]}}, "containerTagKeys": {"s3": {"accesspointobject": {"s3:AccessPointTag/": {"type": "accesspoint", "arn": "arn:${Partition}:s3:${Region}:${Account}:accesspoint/${AccessPointName}"}}, "object": {"s3:BucketTag/": {"type": "bucket", "arn": "arn:${Partition}:s3:::${BucketName}"}}}, "s3tables": {"Table": {"s3tables:TableBucketTag/": {"type": "TableBucket", "arn": "arn:${Partition}:s3tables:${Region}:${Account}:bucket/${TableBucketName}"}}}, "s3vectors": {"Index": {"s3vectors:VectorBucketTag/": {"type": "VectorBucket", "arn": "arn:${Partition}:s3vectors:${Region}:${Account}:bucket/${BucketName}"}}}}, - "resourceKeys": {"ec2": {"capacity-reservation": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:CapacityReservationFleet": {"member": "CapacityReservationFleetId", "arn": "capacity-reservation-fleet"}, "ec2:EbsOptimized": {"member": "EbsOptimized"}, "ec2:EndDateType": {"member": "EndDateType"}, "ec2:EphemeralStorage": {"member": "EphemeralStorage"}, "ec2:InstanceMatchCriteria": {"member": "InstanceMatchCriteria"}, "ec2:InstanceType": {"member": "InstanceType"}, "ec2:Tenancy": {"member": "Tenancy"}}, "carrier-gateway": {"ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "dhcp-options": {"ec2:DhcpOptionsID": {"member": "DhcpOptionsId"}}, "fpga-image": {"ec2:Owner": {"member": "OwnerId"}, "ec2:Public": {"member": "Public"}}, "image": {"ec2:ImageID": {"member": "ImageId"}, "ec2:ImageType": {"member": "ImageType"}, "ec2:Owner": {"member": "OwnerId"}, "ec2:Public": {"member": "Public"}, "ec2:RootDeviceType": {"member": "RootDeviceType"}}, "instance": {"ec2:EbsOptimized": {"member": "EbsOptimized"}, "ec2:InstanceID": {"member": "InstanceId"}, "ec2:InstanceType": {"member": "InstanceType"}, "ec2:RootDeviceType": {"member": "RootDeviceType"}}, "internet-gateway": {"ec2:InternetGatewayID": {"member": "InternetGatewayId"}}, "launch-template": {"ec2:LaunchTemplate": {"member": "LaunchTemplateId", "arn": "launch-template"}}, "network-acl": {"ec2:NetworkAclID": {"member": "NetworkAclId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "network-interface": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:NetworkInterfaceID": {"member": "NetworkInterfaceId"}, "ec2:Subnet": {"member": "SubnetId", "arn": "subnet"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "reserved-instances": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:InstanceType": {"member": "InstanceType"}}, "route-table": {"ec2:RouteTableID": {"member": "RouteTableId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "secondary-interface": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}}, "security-group": {"ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "snapshot": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:Encrypted": {"member": "Encrypted"}, "ec2:Owner": {"member": "OwnerId"}, "ec2:SnapshotID": {"member": "SnapshotId"}, "ec2:VolumeSize": {"member": "VolumeSize"}}, "subnet": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:SubnetID": {"member": "SubnetId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "transit-gateway": {"ec2:transitGatewayId": {"member": "TransitGatewayId"}}, "transit-gateway-attachment": {"ec2:transitGatewayAttachmentId": {"member": "TransitGatewayAttachmentId"}}, "transit-gateway-connect-peer": {"ec2:transitGatewayConnectPeerId": {"member": "TransitGatewayConnectPeerId"}}, "transit-gateway-metering-policy": {"ec2:transitGatewayMeteringPolicyId": {"member": "TransitGatewayMeteringPolicyId"}}, "transit-gateway-multicast-domain": {"ec2:transitGatewayMulticastDomainId": {"member": "TransitGatewayMulticastDomainId"}}, "transit-gateway-policy-table": {"ec2:transitGatewayPolicyTableId": {"member": "TransitGatewayPolicyTableId"}}, "transit-gateway-route-table": {"ec2:transitGatewayRouteTableId": {"member": "TransitGatewayRouteTableId"}}, "transit-gateway-route-table-announcement": {"ec2:transitGatewayRouteTableAnnouncementId": {"member": "TransitGatewayRouteTableAnnouncementId"}}, "volume": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:Encrypted": {"member": "Encrypted"}, "ec2:KmsKeyId": {"member": "KmsKeyId"}, "ec2:VolumeID": {"member": "VolumeId"}, "ec2:VolumeInitializationRate": {"member": "VolumeInitializationRate"}, "ec2:VolumeType": {"member": "VolumeType"}}, "vpc": {"ec2:VpcID": {"member": "VpcId"}}, "vpc-peering-connection": {"ec2:VpcPeeringConnectionID": {"member": "VpcPeeringConnectionId"}}}}, + "resourceKeys": {"ec2": {"capacity-reservation": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:CapacityReservationFleet": {"member": "CapacityReservationFleetId", "arn": "capacity-reservation-fleet"}, "ec2:EbsOptimized": {"member": "EbsOptimized"}, "ec2:EndDateType": {"member": "EndDateType"}, "ec2:EphemeralStorage": {"member": "EphemeralStorage"}, "ec2:InstanceMatchCriteria": {"member": "InstanceMatchCriteria"}, "ec2:InstanceType": {"member": "InstanceType"}, "ec2:Tenancy": {"member": "Tenancy"}}, "carrier-gateway": {"ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "dhcp-options": {"ec2:DhcpOptionsID": {"member": "DhcpOptionsId"}}, "fpga-image": {"ec2:Owner": {"member": "OwnerId"}, "ec2:Public": {"member": "Public"}}, "image": {"ec2:ImageID": {"member": "ImageId"}, "ec2:ImageType": {"member": "ImageType"}, "ec2:Owner": {"member": "OwnerId"}, "ec2:Public": {"member": "Public"}, "ec2:RootDeviceType": {"member": "RootDeviceType"}}, "instance": {"ec2:EbsOptimized": {"member": "EbsOptimized"}, "ec2:InstanceID": {"member": "InstanceId"}, "ec2:InstanceType": {"member": "InstanceType"}, "ec2:RootDeviceType": {"member": "RootDeviceType"}}, "internet-gateway": {"ec2:InternetGatewayID": {"member": "InternetGatewayId"}}, "launch-template": {"ec2:LaunchTemplate": {"member": "LaunchTemplateId", "arn": "launch-template"}}, "network-acl": {"ec2:NetworkAclID": {"member": "NetworkAclId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "network-interface": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:NetworkInterfaceID": {"member": "NetworkInterfaceId"}, "ec2:Subnet": {"member": "SubnetId", "arn": "subnet"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "reserved-instances": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:InstanceType": {"member": "InstanceType"}}, "route-table": {"ec2:RouteTableID": {"member": "RouteTableId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "secondary-interface": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}}, "security-group": {"ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "snapshot": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:Encrypted": {"member": "Encrypted"}, "ec2:Owner": {"member": "OwnerId"}, "ec2:SnapshotID": {"member": "SnapshotId"}, "ec2:VolumeSize": {"member": "VolumeSize"}}, "subnet": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:SubnetID": {"member": "SubnetId"}, "ec2:Vpc": {"member": "VpcId", "arn": "vpc"}}, "transit-gateway": {"ec2:transitGatewayId": {"member": "TransitGatewayId"}}, "transit-gateway-attachment": {"ec2:transitGatewayAttachmentId": {"member": "TransitGatewayAttachmentId"}}, "transit-gateway-connect-peer": {"ec2:transitGatewayConnectPeerId": {"member": "TransitGatewayConnectPeerId"}}, "transit-gateway-metering-policy": {"ec2:transitGatewayMeteringPolicyId": {"member": "TransitGatewayMeteringPolicyId"}}, "transit-gateway-multicast-domain": {"ec2:transitGatewayMulticastDomainId": {"member": "TransitGatewayMulticastDomainId"}}, "transit-gateway-policy-table": {"ec2:transitGatewayPolicyTableId": {"member": "TransitGatewayPolicyTableId"}}, "transit-gateway-route-table": {"ec2:transitGatewayRouteTableId": {"member": "TransitGatewayRouteTableId"}}, "transit-gateway-route-table-announcement": {"ec2:transitGatewayRouteTableAnnouncementId": {"member": "TransitGatewayRouteTableAnnouncementId"}}, "volume": {"ec2:AvailabilityZone": {"member": "AvailabilityZone"}, "ec2:AvailabilityZoneId": {"member": "AvailabilityZoneId"}, "ec2:Encrypted": {"member": "Encrypted"}, "ec2:KmsKeyId": {"member": "KmsKeyId"}, "ec2:VolumeID": {"member": "VolumeId"}, "ec2:VolumeInitializationRate": {"member": "VolumeInitializationRate"}, "ec2:VolumeType": {"member": "VolumeType"}}, "vpc": {"ec2:VpcID": {"member": "VpcId"}}, "vpc-peering-connection": {"ec2:AccepterVpc": {"member": "AccepterVpcInfo", "arn": "vpc", "fill": {"Account": "OwnerId", "Region": "Region", "VpcId": "VpcId"}}, "ec2:RequesterVpc": {"member": "RequesterVpcInfo", "arn": "vpc", "fill": {"Account": "OwnerId", "Region": "Region", "VpcId": "VpcId"}}, "ec2:VpcPeeringConnectionID": {"member": "VpcPeeringConnectionId"}}}}, + "madeResourceKeys": {"ec2:CreateVpcPeeringConnection": {"ec2:AccepterVpc": {"type": "vpc-peering-connection", "arn": "vpc", "query": {"Account": "PeerOwnerId", "Region": "PeerRegion", "VpcId": "PeerVpcId"}}, "ec2:RequesterVpc": {"type": "vpc-peering-connection", "arn": "vpc", "query": {"VpcId": "VpcId"}}}}, "unqualified": {"ssm": ["parameter"], "states": ["statemachine"]}, "mintedIds": {"events": ["api-destination", "connection"]}, "mintedSuffixes": {"secretsmanager": {"Secret": "-??????"}}, diff --git a/src/test/java/io/floci/aws/core/common/Ec2PeeringVpcContextIntegrationTest.java b/src/test/java/io/floci/aws/core/common/Ec2PeeringVpcContextIntegrationTest.java new file mode 100644 index 0000000000..e479eebad4 --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/Ec2PeeringVpcContextIntegrationTest.java @@ -0,0 +1,160 @@ +package io.floci.aws.core.common; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.function.Executable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.ec2.Ec2Client; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; + +import java.net.URI; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** + * A VPC peering connection's {@code ec2:AccepterVpc} and {@code ec2:RequesterVpc} under IAM enforcement: the ARN of + * each VPC it joins, in that VPC's own Region and account. A create takes them for the connection it makes from its + * request, and every later action from the connection EC2 holds, so a cross-account, cross-Region peering can be + * scoped by either side, as the VPC Peering Guide's example policies do. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class Ec2PeeringVpcContextIntegrationTest { + private static final String REQUESTER = "000000000000"; + private static final String ACCEPTER = "111111111111"; + + @TestHTTPResource("/") + URI endpoint; + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @ParameterizedTest + @CsvSource({"us-east-1,us-west-2,aws", "us-gov-west-1,us-gov-east-1,aws-us-gov", + "cn-north-1,cn-northwest-1,aws-cn"}) + void eachSideOfAPeeringIsItsVpcsArnInItsOwnRegionAndAccount(String region, String peerRegion, + String partition) { + String requesterUser = "pcx-requester-" + UUID.randomUUID(); + String accepterUser = "pcx-accepter-" + UUID.randomUUID(); + UserCredentials requesterKeys = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), + auth(REQUESTER, region, "iam"), requesterUser); + UserCredentials accepterKeys = EnforcementFixtures.createUser(cleanup, endpoint.getPort(), + auth(ACCEPTER, peerRegion, "iam"), accepterUser); + String requesterArn = "arn:" + partition + ":ec2:" + region + ":" + REQUESTER + ":"; + String accepterArn = "arn:" + partition + ":ec2:" + peerRegion + ":" + ACCEPTER + ":"; + try (Ec2Client requesterAdmin = AwsTestClients.create(Ec2Client.builder(), REQUESTER, Region.of(region), + endpoint); + Ec2Client accepterAdmin = AwsTestClients.create(Ec2Client.builder(), ACCEPTER, Region.of(peerRegion), + endpoint); + Ec2Client requester = AwsTestClients.create(Ec2Client.builder(), requesterKeys.accessKeyId(), + requesterKeys.secretAccessKey(), Region.of(region), endpoint); + Ec2Client accepter = AwsTestClients.create(Ec2Client.builder(), accepterKeys.accessKeyId(), + accepterKeys.secretAccessKey(), Region.of(peerRegion), endpoint)) { + String requesterVpc = requesterAdmin.createVpc(r -> r.cidrBlock("10.211.0.0/16")).vpc().vpcId(); + String accepterVpc = accepterAdmin.createVpc(r -> r.cidrBlock("10.212.0.0/16")).vpc().vpcId(); + String otherVpc = accepterAdmin.createVpc(r -> r.cidrBlock("10.213.0.0/16")).vpc().vpcId(); + String sides = "\"ec2:AccepterVpc\":\"" + accepterArn + "vpc/" + accepterVpc + + "\",\"ec2:RequesterVpc\":\"" + requesterArn + "vpc/" + requesterVpc + "\""; + String pcx = null; + try { + // The request's VPC is checked too, and the reference lists neither key on it: a grant requiring + // the accepter VPC on every resource refuses the create. + putPolicy(REQUESTER, region, requesterUser, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"ec2:CreateVpcPeeringConnection","Resource":"*", + "Condition":{"ArnEquals":{%s}}}]} + """.formatted(sides)); + assertRefused(() -> requester.createVpcPeeringConnection(r -> r.vpcId(requesterVpc) + .peerVpcId(accepterVpc).peerOwnerId(ACCEPTER).peerRegion(peerRegion))); + + // A grant to peer with the requester's own VPCs alone: claiming its own account for the accepter's + // VPC, or leaving PeerOwnerId out, does not make that VPC its own. + putPolicy(REQUESTER, region, requesterUser, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"ec2:CreateVpcPeeringConnection","Resource":"%svpc/*"}, + {"Effect":"Allow","Action":"ec2:CreateVpcPeeringConnection", + "Resource":"%svpc-peering-connection/*", + "Condition":{"ArnLike":{"ec2:AccepterVpc":"arn:%s:ec2:*:%s:vpc/*"}}}]} + """.formatted(requesterArn, requesterArn, partition, REQUESTER)); + assertRefused(() -> requester.createVpcPeeringConnection(r -> r.vpcId(requesterVpc) + .peerVpcId(accepterVpc).peerOwnerId(REQUESTER).peerRegion(peerRegion))); + assertRefused(() -> requester.createVpcPeeringConnection(r -> r.vpcId(requesterVpc) + .peerVpcId(accepterVpc).peerRegion(peerRegion))); + + putPolicy(REQUESTER, region, requesterUser, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"ec2:CreateVpcPeeringConnection","Resource":"%svpc/*"}, + {"Effect":"Allow","Action":["ec2:CreateVpcPeeringConnection","ec2:DeleteVpcPeeringConnection"], + "Resource":"%svpc-peering-connection/*","Condition":{"ArnEquals":{%s}}}]} + """.formatted(requesterArn, requesterArn, sides)); + assertRefused(() -> requester.createVpcPeeringConnection(r -> r.vpcId(requesterVpc) + .peerVpcId(otherVpc).peerOwnerId(ACCEPTER).peerRegion(peerRegion))); + // Without PeerRegion the accepter VPC is one of the request's own Region. + assertRefused(() -> requester.createVpcPeeringConnection(r -> r.vpcId(requesterVpc) + .peerVpcId(accepterVpc).peerOwnerId(ACCEPTER))); + String created = requester.createVpcPeeringConnection(r -> r.vpcId(requesterVpc) + .peerVpcId(accepterVpc).peerOwnerId(ACCEPTER).peerRegion(peerRegion)) + .vpcPeeringConnection().vpcPeeringConnectionId(); + pcx = created; + + // The accepter, in its own account and Region, is scoped by the VPC that asked. + putPolicy(ACCEPTER, peerRegion, accepterUser, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"ec2:AcceptVpcPeeringConnection","Resource":"%svpc-peering-connection/*", + "Condition":{"ArnEquals":{"ec2:RequesterVpc":"%svpc/vpc-0000000000000000f"}}}]} + """.formatted(accepterArn, requesterArn)); + assertRefused(() -> accepter.acceptVpcPeeringConnection(r -> r.vpcPeeringConnectionId(created))); + putPolicy(ACCEPTER, peerRegion, accepterUser, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"ec2:AcceptVpcPeeringConnection","Resource":"%svpc-peering-connection/*", + "Condition":{"ArnEquals":{"ec2:RequesterVpc":"%svpc/%s"}}}]} + """.formatted(accepterArn, requesterArn, requesterVpc)); + assertEquals("active", accepter.acceptVpcPeeringConnection(r -> r.vpcPeeringConnectionId(created)) + .vpcPeeringConnection().status().codeAsString()); + + // The requester deletes it only while both VPCs are the ones its grant names. + putPolicy(REQUESTER, region, requesterUser, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"ec2:DeleteVpcPeeringConnection","Resource":"%svpc-peering-connection/*", + "Condition":{"ArnEquals":{%s}}}]} + """.formatted(requesterArn, sides.replace("vpc/" + accepterVpc, "vpc/" + otherVpc))); + assertRefused(() -> requester.deleteVpcPeeringConnection(r -> r.vpcPeeringConnectionId(created))); + putPolicy(REQUESTER, region, requesterUser, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"ec2:DeleteVpcPeeringConnection","Resource":"%svpc-peering-connection/*", + "Condition":{"ArnEquals":{%s}}}]} + """.formatted(requesterArn, sides)); + requester.deleteVpcPeeringConnection(r -> r.vpcPeeringConnectionId(created)); + pcx = null; + } finally { + if (pcx != null) { + String leftOver = pcx; + requesterAdmin.deleteVpcPeeringConnection(r -> r.vpcPeeringConnectionId(leftOver)); + } + requesterAdmin.deleteVpc(r -> r.vpcId(requesterVpc)); + accepterAdmin.deleteVpc(r -> r.vpcId(accepterVpc)); + accepterAdmin.deleteVpc(r -> r.vpcId(otherVpc)); + } + } + } + + private void putPolicy(String account, String region, String user, String policy) { + EnforcementFixtures.putUserPolicy(endpoint.getPort(), auth(account, region, "iam"), user, "peering", policy); + } + + private static void assertRefused(Executable call) { + assertEquals("UnauthorizedOperation", + assertThrows(Ec2Exception.class, call).awsErrorDetails().errorCode()); + } +} diff --git a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java index 22141f12b7..080bc9a682 100644 --- a/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java +++ b/src/test/java/io/floci/aws/core/common/IamConditionContextResolverTest.java @@ -16,6 +16,8 @@ import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ec2.Ec2StoredResourceArns; import io.floci.aws.services.ec2.model.NetworkInterface; import io.floci.aws.services.ec2.model.Tag; +import io.floci.aws.services.ec2.model.VpcPeeringConnection; +import io.floci.aws.services.ec2.model.VpcPeeringConnectionVpcInfo; import io.floci.aws.services.ec2.portforward.Ec2PortForwardManager; import io.floci.aws.services.iam.IamPolicyEvaluator; import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; @@ -1017,9 +1019,98 @@ class IamConditionContextResolverTest { "arn:aws:ec2:us-east-1:123456789012:vpc-endpoint/*", "us-east-1", "123456789012", original)); } + @Test + void aPeeringConnectionGivesEachVpcItJoinsAsAnArnInThatVpcsOwnRegionAndAccount() { + VpcPeeringConnection crossAccount = peeringConnection("pcx-1", peeringSide("vpc-req", "123456789012", + "us-east-1"), peeringSide("vpc-acc", "111111111111", "eu-west-1")); + VpcPeeringConnection noAccepterRegion = peeringConnection("pcx-2", peeringSide("vpc-req", "123456789012", + "us-east-1"), peeringSide("vpc-acc", "111111111111", null)); + when(ec2Service.heldResources("us-east-1", "vpc-peering-connection", List.of("pcx-1"))) + .thenReturn(Map.of("pcx-1", crossAccount)); + when(ec2Service.heldResources("us-east-1", "vpc-peering-connection", List.of("pcx-2"))) + .thenReturn(Map.of("pcx-2", noAccepterRegion)); + + Map> context = resolver.withEc2ResourceContext("ec2", "ec2:AcceptVpcPeeringConnection", + "arn:aws:ec2:us-east-1:123456789012:vpc-peering-connection/pcx-1", "us-east-1", "123456789012", + Map.of(), Map.of()); + assertEquals(List.of("arn:aws:ec2:eu-west-1:111111111111:vpc/vpc-acc"), context.get("ec2:AccepterVpc")); + assertEquals(List.of("arn:aws:ec2:us-east-1:123456789012:vpc/vpc-req"), context.get("ec2:RequesterVpc")); + assertEquals(List.of("pcx-1"), context.get("ec2:VpcPeeringConnectionID")); + + // A side the connection holds without its Region leaves that side's key absent. + Map> partial = resolver.withEc2ResourceContext("ec2", "ec2:DeleteVpcPeeringConnection", + "arn:aws:ec2:us-east-1:123456789012:vpc-peering-connection/pcx-2", "us-east-1", "123456789012", + Map.of(), Map.of("ec2:AccepterVpc", List.of("arn:aws:ec2:us-east-1:123456789012:vpc/stale"))); + assertFalse(partial.containsKey("ec2:AccepterVpc")); + assertEquals(List.of("arn:aws:ec2:us-east-1:123456789012:vpc/vpc-req"), partial.get("ec2:RequesterVpc")); + } + + @Test + void aPeeringCreateGivesTheConnectionItMakesTheVpcsItsRequestNames() { + String made = "arn:aws:ec2:us-east-1:123456789012:vpc-peering-connection/*"; + Map> context = resolver.withEc2ResourceContext("ec2", "ec2:CreateVpcPeeringConnection", + made, "us-east-1", "123456789012", Map.of("VpcId", "vpc-req", "PeerVpcId", "vpc-acc", + "PeerOwnerId", "111111111111", "PeerRegion", "eu-west-1"), + Map.of("aws:RequestTag/Team", List.of("payments"))); + assertEquals(List.of("arn:aws:ec2:eu-west-1:111111111111:vpc/vpc-acc"), context.get("ec2:AccepterVpc")); + assertEquals(List.of("arn:aws:ec2:us-east-1:123456789012:vpc/vpc-req"), context.get("ec2:RequesterVpc")); + assertEquals(List.of("payments"), context.get("aws:RequestTag/Team")); + + // A VPC EC2 holds is in the account holding it, as the connection records it, whatever account is claimed. + when(ec2Service.heldAccount("eu-west-1", "vpc", "vpc-held")).thenReturn(Optional.of("222222222222")); + assertEquals(List.of("arn:aws:ec2:eu-west-1:222222222222:vpc/vpc-held"), resolver.withEc2ResourceContext( + "ec2", "ec2:CreateVpcPeeringConnection", made, "us-east-1", "123456789012", Map.of("VpcId", "vpc-req", + "PeerVpcId", "vpc-held", "PeerOwnerId", "123456789012", "PeerRegion", "eu-west-1"), Map.of()) + .get("ec2:AccepterVpc")); + + // Without PeerOwnerId and PeerRegion the accepter VPC is the caller's, in the request's Region and partition. + Map> own = resolver.withEc2ResourceContext("ec2", "ec2:CreateVpcPeeringConnection", + "arn:aws-us-gov:ec2:us-gov-west-1:123456789012:vpc-peering-connection/*", "us-gov-west-1", + "123456789012", Map.of("VpcId", "vpc-req", "PeerVpcId", "vpc-acc"), Map.of()); + assertEquals(List.of("arn:aws-us-gov:ec2:us-gov-west-1:123456789012:vpc/vpc-acc"), own.get("ec2:AccepterVpc")); + + // A request without the accepter's VPC names no accepter VPC, and a peer Region or account that would move + // the ARN's other parts names none either. + assertFalse(resolver.withEc2ResourceContext("ec2", "ec2:CreateVpcPeeringConnection", made, "us-east-1", + "123456789012", Map.of("VpcId", "vpc-req"), Map.of()).containsKey("ec2:AccepterVpc")); + assertFalse(resolver.withEc2ResourceContext("ec2", "ec2:CreateVpcPeeringConnection", made, "us-east-1", + "123456789012", Map.of("VpcId", "vpc-req", "PeerVpcId", "vpc-acc", + "PeerRegion", "eu-west-1:111111111111:vpc/x"), Map.of()).containsKey("ec2:AccepterVpc")); + assertFalse(resolver.withEc2ResourceContext("ec2", "ec2:CreateVpcPeeringConnection", made, "us-east-1", + "123456789012", Map.of("VpcId", "vpc-req", "PeerVpcId", "vpc-acc", + "PeerOwnerId", "111111111111:vpc/x"), Map.of()).containsKey("ec2:AccepterVpc")); + + // The request's VPC, and another operation's connections, take no keys from the request. + Map form = Map.of("VpcId", "vpc-req", "PeerVpcId", "vpc-acc"); + assertFalse(resolver.withEc2ResourceContext("ec2", "ec2:CreateVpcPeeringConnection", + "arn:aws:ec2:us-east-1:123456789012:vpc/vpc-req", "us-east-1", "123456789012", form, Map.of()) + .containsKey("ec2:AccepterVpc")); + Map> original = Map.of(); + assertSame(original, resolver.withEc2ResourceContext("ec2", "ec2:DescribeVpcPeeringConnections", made, + "us-east-1", "123456789012", form, original)); + } + + private static VpcPeeringConnection peeringConnection(String id, VpcPeeringConnectionVpcInfo requester, + VpcPeeringConnectionVpcInfo accepter) { + VpcPeeringConnection connection = new VpcPeeringConnection(); + connection.setVpcPeeringConnectionId(id); + connection.setRequesterVpcInfo(requester); + connection.setAccepterVpcInfo(accepter); + return connection; + } + + private static VpcPeeringConnectionVpcInfo peeringSide(String vpcId, String ownerId, String region) { + VpcPeeringConnectionVpcInfo side = new VpcPeeringConnectionVpcInfo(); + side.setVpcId(vpcId); + side.setOwnerId(ownerId); + side.setRegion(region); + return side; + } + private Map> ec2ResourceContext(IamConditionContextResolver reading, String scope, String action, String resource, String region, String account, Map> context) { - Map> record = reading.withEc2ResourceContext(scope, action, resource, region, account, context); + Map> record = reading.withEc2ResourceContext(scope, action, resource, region, account, + Map.of(), context); IamConditionContextResolver tags = reading == resolver ? resolverReading(new Ec2StoredResourceArns(ec2Service, new RegionResolver(region, account))) : reading; return IamConditionContextResolver.withResourceTags(record, tags.resourceTags(resource)); diff --git a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java index 8fb9f9e7be..22a9b070f6 100644 --- a/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java +++ b/src/test/java/io/floci/aws/core/common/RequestResourceMembersTest.java @@ -1,6 +1,7 @@ package io.floci.aws.core.common; import io.floci.aws.core.common.RequestResourceMembers.ArnFormat; +import io.floci.aws.core.common.RequestResourceMembers.MadeResourceKey; import io.floci.aws.core.common.RequestResourceMembers.Member; import io.floci.aws.core.common.RequestResourceMembers.Resource; import io.floci.aws.testing.MockQueryRequests; @@ -44,6 +45,79 @@ class RequestResourceMembersTest { private static final ObjectMapper MAPPER = JacksonConfig.jsonMapper(); + /** + * A structure key's fill gives the field of each variable of its ARN type's format but the partition, and a + * create's made resource keys are structure keys of the type it makes, each parameter filling one of the key's + * variables; anything else is refused. + */ + @Test + void structureAndMadeResourceKeysAreReadAndChecked() throws Exception { + ObjectNode document = (ObjectNode) MAPPER.readTree(""" + { + "namespaces": {"ec2": ["ec2"]}, + "arnFormats": {"ec2": { + "vpc": "arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}", + "vpc-peering-connection": + "arn:${Partition}:ec2:${Region}:${Account}:vpc-peering-connection/${VpcPeeringConnectionId}" + }}, + "resourceKeys": {"ec2": {"vpc-peering-connection": { + "ec2:AccepterVpc": {"member": "AccepterVpcInfo", "arn": "vpc", + "fill": {"Account": "OwnerId", "Region": "Region", "VpcId": "VpcId"}}, + "ec2:VpcPeeringConnectionID": {"member": "VpcPeeringConnectionId"} + }}}, + "madeResourceKeys": {"ec2:CreateVpcPeeringConnection": { + "ec2:AccepterVpc": {"type": "vpc-peering-connection", "arn": "vpc", + "query": {"Account": "PeerOwnerId", "Region": "PeerRegion", + "VpcId": "PeerVpcId"}} + }}, + "operations": { + "ec2:CreateVpcPeeringConnection": {"resources": [ + {"type": "vpc-peering-connection", "fill": {}, "made": true}]}, + "ec2:AcceptVpcPeeringConnection": {"resources": [ + {"type": "vpc-peering-connection", "fill": {"VpcPeeringConnectionId": "VpcPeeringConnectionId"}}]} + } + } + """); + RequestResourceMembers.Table table = parse(document.toString()); + Map keys = + table.resourceKeys().get("ec2").get("vpc-peering-connection"); + assertEquals(Map.of("Account", "OwnerId", "Region", "Region", "VpcId", "VpcId"), + keys.get("ec2:AccepterVpc").fill()); + assertEquals(Map.of(), keys.get("ec2:VpcPeeringConnectionID").fill()); + assertEquals(new MadeResourceKey("vpc-peering-connection", "vpc", + Map.of("Account", "PeerOwnerId", "Region", "PeerRegion", "VpcId", "PeerVpcId")), + table.madeResourceKeys().get("ec2:CreateVpcPeeringConnection").get("ec2:AccepterVpc")); + for (String fill : List.of("{\"Region\":\"Region\",\"VpcId\":\"VpcId\"}", + "{\"Account\":\"OwnerId\",\"Partition\":\"P\",\"Region\":\"Region\",\"VpcId\":\"VpcId\"}", + "{\"Account\":\"\",\"Region\":\"Region\",\"VpcId\":\"VpcId\"}", "\"OwnerId\"")) { + ObjectNode changed = document.deepCopy(); + ((ObjectNode) changed.path("resourceKeys").path("ec2").path("vpc-peering-connection") + .path("ec2:AccepterVpc")).set("fill", MAPPER.readTree(fill)); + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> parse(changed.toString())); + assertTrue(failure.getMessage().contains("resource keys"), failure.getMessage()); + } + ObjectNode unfilled = document.deepCopy(); + ((ObjectNode) unfilled.path("resourceKeys").path("ec2").path("vpc-peering-connection") + .path("ec2:VpcPeeringConnectionID")).set("fill", MAPPER.readTree("{\"VpcId\":\"VpcId\"}")); + assertThrows(IllegalStateException.class, () -> parse(unfilled.toString())); + for (String made : List.of( + "{\"ec2:CreateVpcPeeringConnection\":{\"ec2:AccepterVpc\":{\"type\":\"vpc\",\"arn\":\"vpc\"," + + "\"query\":{\"VpcId\":\"PeerVpcId\"}}}}", + "{\"ec2:CreateVpcPeeringConnection\":{\"ec2:AccepterVpc\":{\"type\":\"vpc-peering-connection\"," + + "\"arn\":\"vpc-peering-connection\",\"query\":{\"VpcId\":\"PeerVpcId\"}}}}", + "{\"ec2:CreateVpcPeeringConnection\":{\"ec2:AccepterVpc\":{\"type\":\"vpc-peering-connection\"," + + "\"arn\":\"vpc\",\"query\":{\"Partition\":\"PeerPartition\"}}}}", + "{\"ec2:CreateVpcPeeringConnection\":{\"ec2:VpcPeeringConnectionID\":{\"type\":" + + "\"vpc-peering-connection\",\"arn\":\"vpc\",\"query\":{}}}}", + "{\"ec2:AcceptVpcPeeringConnection\":{\"ec2:AccepterVpc\":{\"type\":\"vpc-peering-connection\"," + + "\"arn\":\"vpc\",\"query\":{\"VpcId\":\"PeerVpcId\"}}}}")) { + ObjectNode changed = document.deepCopy(); + changed.set("madeResourceKeys", MAPPER.readTree(made)); + IllegalStateException failure = assertThrows(IllegalStateException.class, () -> parse(changed.toString())); + assertTrue(failure.getMessage().contains("resource keys"), failure.getMessage()); + } + } + /** * The types the table gives as lying within a type's format are its narrower ones, which an ARN fitting both is * read as; a list naming a type its namespace has no format for, the type itself, or nothing, is refused. diff --git a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java index 4f722e3e36..db450e2f29 100644 --- a/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java +++ b/src/test/java/io/floci/aws/services/ec2/Ec2ServiceTest.java @@ -454,6 +454,28 @@ class Ec2ServiceTest { assertTrue(service.describeVolumes("us-east-1", List.of(), Map.of()).isEmpty()); } + /** + * The account holding a VPC, as IAM reads it for a peering request's accepter: in place, a pre-multi-account VPC + * the default account's, its entry left where it is. + */ + @Test + void heldAccountReadsAVpcsHolderWithoutMovingItsEntry() { + InMemoryStorage raw = new InMemoryStorage<>(); + Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class), + mock(Ec2PortForwardManager.class), mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), + new Ec2InstanceTypeCatalog(), new InMemoryStorageFactory(Map.of("ec2-vpcs.json", + new AccountAwareStorageBackend<>(raw, null, "000000000000")))); + raw.put("us-east-1::vpc-legacy", new Vpc()); + raw.put("111111111111/us-east-1::vpc-other", new Vpc()); + Set stored = Set.copyOf(raw.keys()); + + assertEquals(Optional.of("000000000000"), service.heldAccount("us-east-1", "vpc", "vpc-legacy")); + assertEquals(Optional.of("111111111111"), service.heldAccount("us-east-1", "vpc", "vpc-other")); + assertEquals(Optional.empty(), service.heldAccount("eu-west-1", "vpc", "vpc-other")); + assertEquals(Optional.empty(), service.heldAccount("us-east-1", "subnet", "vpc-other")); + assertEquals(stored, Set.copyOf(raw.keys())); + } + @Test void describeInstancesScansTheVolumeStoreOnceWhateverTheInstanceCount() { InMemoryStorage volumeStore = spy(new InMemoryStorage()); diff --git a/tools/aws/fetch_ec2_request_samples.py b/tools/aws/fetch_ec2_request_samples.py new file mode 100644 index 0000000000..4f8354035b --- /dev/null +++ b/tools/aws/fetch_ec2_request_samples.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Copy the sample requests and their sample responses from pages of the EC2 API reference. + +Each page's examples give a Query request ("Sample Request") and, for some, what EC2 answered to it ("Sample +Response"). A request directly followed by its response is copied as a pair: the request's parameters with their +values, and every leaf of the response with its XML element path. The generator joins a request parameter to the +member of the record the request makes that holds the same value in AWS's own sample, which botocore does not say +(`CreateVpcPeeringConnection`'s `PeerVpcId` is the accepter VPC's id, documented only as "The ID of the VPC with which +you are creating the VPC peering connection"). The fetched data says nothing of its own about any parameter. +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.parse +import urllib.request +import xml.etree.ElementTree as ET +from datetime import datetime, timezone +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/ec2-request-samples.json" +PAGES = {"CreateVpcPeeringConnection": + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVpcPeeringConnection.html"} +# Query parameters every EC2 request carries, which name nothing of the operation's own. +COMMON_PARAMETERS = {"Action", "Version"} + + +def _blocks(page: str) -> list[str]: + return [html.unescape(re.sub(r"<[^>]+>", "", block)).strip() + for block in re.findall(r"]*>(.*?)", page, re.S)] + + +def _request(operation: str, text: str) -> dict[str, str] | None: + """The parameters of a sample Query request for `operation`, or None when the block is not one.""" + joined = "".join(line.strip() for line in text.splitlines()) + if not joined.startswith("https://"): + return None + query = urllib.parse.urlsplit(joined).query + parameters = dict(urllib.parse.parse_qsl(query, keep_blank_values=True)) + if parameters.get("Action") != operation: + return None + return {name: value for name, value in parameters.items() + if name not in COMMON_PARAMETERS and name != "AUTHPARAMS" and value != ""} + + +def _response(operation: str, text: str) -> list[dict] | None: + """Every leaf of a sample response to `operation`, with its element path below the root, or None when the block + is not one.""" + if not re.match(r"<" + re.escape(operation) + r"Response(?:\s|>)", text): + return None + try: + root = ET.fromstring(text) + except ET.ParseError as error: + raise ValueError(f"{operation} has a malformed XML response example") from error + leaves = [] + + def walk(node: ET.Element, path: list[str]) -> None: + if not len(node) and (node.text or "").strip(): + leaves.append({"path": path, "value": node.text.strip()}) + for child in node: + walk(child, path + [child.tag.rsplit("}", 1)[-1]]) + + walk(root, []) + return leaves + + +def read_samples(operation: str, page: str) -> list[dict]: + """Each sample request of `operation` the page follows with its sample response, in the page's order.""" + samples = [] + blocks = _blocks(page) + for index, text in enumerate(blocks[:-1]): + request = _request(operation, text) + response = _response(operation, blocks[index + 1]) if request is not None else None + if request and response: + samples.append({"request": request, "response": response}) + if not samples: + raise ValueError(f"{operation} has no sample request followed by its response: the page layout changed") + return samples + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def build(pages: dict[str, str]) -> dict: + return { + "_source": {"fetcher": "tools/aws/fetch_ec2_request_samples.py", + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "pages": list(PAGES.values())}, + "namespace": "ec2", + "operations": {operation: {"page": url, "samples": read_samples(operation, pages[url])} + for operation, url in PAGES.items()}, + } + + +def stale(vendored: dict, pages: dict[str, str]) -> bool: + built = build(pages) + return any(vendored.get(key) != built[key] for key in ("namespace", "operations")) + + +def fetch_all(fetch=None) -> tuple[dict[str, str]]: + fetch = fetch or fetch_url + return ({url: fetch(url) for url in PAGES.values()},) + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--verify", action="store_true") + args = parser.parse_args(argv) + try: + pages, = fetch_all(fetch) + result = build(pages) + if args.verify: + if stale(json.loads(OUTPUT.read_text()), pages): + print("error: EC2 request samples changed; rerun tools/aws/fetch_ec2_request_samples.py", + file=sys.stderr) + return 1 + else: + OUTPUT.write_text(json.dumps(result, indent=2) + "\n") + except (OSError, ValueError, ET.ParseError) as error: + print(f"error: could not read EC2 request samples ({error})", file=sys.stderr) + return 2 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index ddd1361bad..6c133a975c 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -133,7 +133,12 @@ continues, with that type's format in its variables, filled with the tags of the and, for those id-list namespaces, `resourceKeys` the type's other condition keys that name a member of its botocore shape (`ec2:Vpc` a network interface's `VpcId`), which its service answers from the resource it holds, as an ARN where the reference types the -key as one. +key as one. In a namespace `STRUCTURE_KEYS` opts in, an ARN key named as another type with a word before it names the +structure of the type's shape that begins with the key's name, whose members fill that type's ARN (`ec2:AccepterVpc` +a peering connection's `AccepterVpcInfo`, its `VpcId`, `Region` and owning account). `madeResourceKeys` gives a create +the keys the reference lists on the resource it makes, read from its request: the request parameter that AWS's own +sample of the operation (`SAMPLE_SOURCES`) answers with in that structure's member, and the parameter named as another +member of it with the same word before it (`PeerRegion` beside `PeerVpcId` and `PeerOwnerId`). Beyond the members' names, botocore's shapes and documentation say what a member names, and the rule reads them: - a member whose documentation names the type, word for word ("The name of the pipeline to start"), fills its variable when it is the kind the variable is (a name, an id), and is found by the type's service otherwise @@ -362,6 +367,7 @@ import fetch_codeartifact_permissions import fetch_dms_arn_formats import fetch_dynamodb_permissions import fetch_ec2_id_examples +import fetch_ec2_request_samples import fetch_iam_identifiers import fetch_kms_api_permissions import fetch_lambda_layer_permissions @@ -698,6 +704,29 @@ TAG_INHERITANCE_FETCHERS = { ID_EXAMPLE_SOURCES = {"ec2": fetch_ec2_id_examples.OUTPUT} ID_EXAMPLE_FETCHERS = {"ec2": fetch_ec2_id_examples} +# --------------------------------------------------------------------------------------------------------------------- +# STRUCTURE_KEYS: the namespaces whose resource types' ARN condition keys may name a structure of the type's botocore +# shape (`resource_keys`): a key named as another type of the namespace with a word before it (`ec2:AccepterVpc`, the +# `vpc` type), the one structure member beginning with the key's name (a peering connection's `AccepterVpcInfo`), +# whose members fill that type's ARN: its own variables by name (`VpcId`), the Region from the member named as one, +# and the account from the member documented as "The ID of the ... account". Opted into for EC2 alone, whose peering +# connection keeps each VPC it joins that way; every other namespace's rows are unchanged. +# --------------------------------------------------------------------------------------------------------------------- +STRUCTURE_KEYS = ("ec2",) +# A member documented as an account's id: "The ID of the Amazon Web Services account that owns the VPC." +ACCOUNT_ID_DOC_RE = re.compile(r"^the id of the (?:amazon web services |aws )?account\b") + +# --------------------------------------------------------------------------------------------------------------------- +# SAMPLE_SOURCES: AWS's own sample requests of a namespace's operations, each with the response AWS gave to it, which +# say what a create's request parameter becomes in the record it makes where botocore does not +# (`CreateVpcPeeringConnection`'s `PeerVpcId`, documented only as "The ID of the VPC with which you are creating the +# VPC peering connection", comes back as its `accepterVpcInfo`'s `vpcId`). Granted for EC2's API reference pages alone +# (tools/aws/fetch_ec2_request_samples.py's `PAGES`). Its file is written by its own script from those pages, +# unchanged, and the generator only reads it (`made_resource_keys`): nothing about a parameter is stated here. +# --------------------------------------------------------------------------------------------------------------------- +SAMPLE_SOURCES = {"ec2": fetch_ec2_request_samples.OUTPUT} +SAMPLE_FETCHERS = {"ec2": fetch_ec2_request_samples} + # --------------------------------------------------------------------------------------------------------------------- # REQUIRED_TYPE_SOURCE: which resource types each action of a granted namespace always acts on, as its page of the # Service Authorization Reference marks them ("Resource types (*required)": DeleteGroupMembership's `Group*`, @@ -1007,7 +1036,9 @@ def resource_keys(documents: list[dict], data: Path, namespaces: dict[str, list[ the member without its `Id` (`ec2:Vpc` its `VpcId`, `ec2:NetworkInterfaceID` its `NetworkInterfaceId`), holding a scalar. Each is `{"member": }`, with `"arn": ` where the reference types the key as an ARN and the namespace has a type named as the key (`ec2:Vpc` takes a `vpc` ARN); an ARN key with no such type is left out, as - are keys with a variable and keys no member names. The type's service holds the member's value for the resource + are keys with a variable and keys no member names, but in a namespace `STRUCTURE_KEYS` opts in (`structure_key`), + where an ARN key named as another type with a word before it is the structure member that fills that type's ARN, + with `"fill"` its members by the variable each fills. The type's service holds the member's value for the resource a request names, which is the key's value.""" result = {} for document in documents: @@ -1018,8 +1049,9 @@ def resource_keys(documents: list[dict], data: Path, namespaces: dict[str, list[ shapes = {} for model in load_models(data, set(namespaces[namespace])).values(): shapes.update(model["shapes"]) - types = {resource["Name"] for resource in document.get("Resources", []) if resource.get("ARNFormats")} - by_shape_name = {_shape_name(kind).lower(): kind for kind in types} + formats = {resource["Name"]: resource["ARNFormats"][0] for resource in document.get("Resources", []) + if resource.get("ARNFormats")} + by_shape_name = {_shape_name(kind).lower(): kind for kind in formats} found = {} for resource in document.get("Resources", []): shape = shapes.get(_shape_name(resource["Name"])) @@ -1032,6 +1064,11 @@ def resource_keys(documents: list[dict], data: Path, namespaces: dict[str, list[ continue named = key.split(":", 1)[1].lower() member = members.get(named) or members.get(named + "id") + if member is None and namespace in STRUCTURE_KEYS and "ARN" in key_types.get(key, []): + structured = structure_key(named, shape, shapes, by_shape_name, formats) + if structured is not None: + keys[key] = structured + continue if member is None or shapes.get(member[1], {}).get("type") not in SCALAR_SHAPES: continue spec = {"member": member[0]} @@ -1047,6 +1084,160 @@ def resource_keys(documents: list[dict], data: Path, namespaces: dict[str, list[ return dict(sorted(result.items())) +def _valid_made_keys(made_keys: object, operations: dict, resource_keys_document: dict) -> bool: + """Whether `madeResourceKeys` gives, for each create of a namespace with samples (`SAMPLE_SOURCES`), structure keys + of a type it makes, sorted, each with that key's ARN type and parameters for variables its `fill` gives.""" + if not isinstance(made_keys, dict): + return False + for operation, keys in made_keys.items(): + namespace = operation.split(":", 1)[0] + if namespace not in SAMPLE_SOURCES or operation not in operations or not isinstance(keys, dict) or not keys \ + or list(keys) != sorted(keys): + return False + for key, spec in keys.items(): + if not isinstance(spec, dict) or set(spec) != {"type", "arn", "query"} \ + or not isinstance(spec["type"], str) or not isinstance(spec["query"], dict): + return False + stored = resource_keys_document.get(namespace, {}).get(spec["type"], {}).get(key, {}) + if "fill" not in stored or spec["arn"] != stored.get("arn") or not all( + isinstance(parameter, str) and variable in stored["fill"] + for variable, parameter in spec["query"].items()): + return False + if not any(resource.get("made") and resource.get("type") == spec["type"] + for resource in operations[operation].get("resources", [])): + return False + return True + + +def _fills_format(fill: object, format_: str) -> bool: + """Whether `fill` gives a member for every variable of an ARN format but its partition.""" + return isinstance(fill, dict) and all(isinstance(member, str) for member in fill.values()) and set(fill) == { + variable for variable in VARIABLE_RE.findall(format_) if variable != "Partition"} + + +def structure_key(named: str, shape: dict, shapes: dict, by_shape_name: dict[str, str], + formats: dict[str, str]) -> dict | None: + """The reading of an ARN key, its name lowered (`acceptervpc`), that names another type of the namespace with a word + before it (the `vpc` type, the longest type whose shape name ends it): `{"member", "arn", "fill"}`, the one structure + member of the type's botocore shape `shape` whose name begins with the key's (`AccepterVpcInfo`), and its string + members filling the other type's ARN, by variable: the type's own variables from the member named as each, the + Region from the one member named as a Region, and the account from the one documented as an account's id + (`ACCOUNT_ID_DOC_RE`). None when the name ends in no other type, or no one structure fills every variable.""" + named_types = [name for name in by_shape_name if named.endswith(name) and named != name] + if not named_types: + return None + kind = by_shape_name[max(named_types, key=len)] + structures = [(name, spec["shape"]) for name, spec in shape.get("members", {}).items() + if name.lower().startswith(named) and shapes.get(spec["shape"], {}).get("type") == "structure"] + if len(structures) != 1: + return None + member, structure = structures[0] + fields = {name: spec for name, spec in shapes[structure].get("members", {}).items() + if shapes.get(spec["shape"], {}).get("type") == "string"} + fill = {} + for variable in VARIABLE_RE.findall(formats.get(kind, "")): + if variable == "Partition": + continue + if variable == "Region": + found = [name for name in fields if name.lower().endswith("region")] + elif variable == "Account": + found = [name for name, spec in fields.items() + if ACCOUNT_ID_DOC_RE.match(_lead_text(spec.get("documentation")))] + else: + found = [name for name in fields if name.lower() == variable.lower()] + if len(found) != 1: + return None + fill[variable] = found[0] + return {"member": member, "arn": kind, "fill": dict(sorted(fill.items()))} + + +def made_resource_keys(documents: list[dict], data: Path, namespaces: dict[str, list[str]], + keys: dict[str, dict[str, dict]], operations: dict[str, dict]) -> dict[str, dict[str, dict]]: + """For each create of a namespace with AWS's own samples (`SAMPLE_SOURCES`), the structure keys (`keys`, from + `structure_key`) of the resource it makes (`made`) that the reference lists on that resource for its action, read + from its request: `{"type", "arn", "query"}`, the made type, the key's ARN type, and the EC2 Query parameter + filling each variable (`sample_fill`). A variable no parameter fills is the request's own Region or account.""" + result: dict[str, dict[str, dict]] = {} + for document in documents: + namespace = document["Name"] + if namespace not in SAMPLE_SOURCES or namespace not in namespaces: + continue + source = json.loads(SAMPLE_SOURCES[namespace].read_text(encoding="utf-8")) + actions = {action["Name"]: action for action in document.get("Actions", [])} + models = load_models(data, set(namespaces[namespace])) + for name, granted in sorted(source.get("operations", {}).items()): + operation = f"{namespace}:{name}" + listed = {resource["Name"]: set(resource.get("ConditionKeys") or []) + for resource in actions.get(name, {}).get("Resources", [])} + found = {} + for kind in [resource["type"] for resource in operations.get(operation, {}).get("resources", []) + if resource.get("made")]: + for key, spec in keys.get(namespace, {}).get(kind, {}).items(): + if "fill" not in spec or key not in listed.get(kind, set()): + continue + query = sample_fill(models, name, kind, spec, granted.get("samples", [])) + if query is not None: + found[key] = {"type": kind, "arn": spec["arn"], "query": query} + if found: + result[operation] = dict(sorted(found.items())) + return dict(sorted(result.items())) + + +def sample_fill(models: dict[str, dict], operation: str, kind: str, spec: dict, samples: list[dict]) -> dict | None: + """The EC2 Query parameters of `operation`'s request filling the variables of a structure key of the type `kind` + it makes (`spec`'s `fill`): each the parameter AWS's samples answer with, in the made record's structure member, by + the same value (`PeerVpcId=vpc-a1b2c3d4` and `accepterVpcInfo`'s `vpcId`), every one of them the member it fills + behind the same word, if any (`Peer`), and behind that word the parameter named as another member of the structure + (`PeerRegion`). None when the samples join no parameter, the words differ, or a variable of the type's own (the + `VpcId`) has no parameter.""" + for model in models.values(): + spec_op = model["operations"].get(operation) + if spec_op is None or "input" not in spec_op or "output" not in spec_op or "ec2" not in _protocols(model): + continue + shapes = model["shapes"] + request = shapes[spec_op["input"]["shape"]].get("members", {}) + wire = {name: member.get("queryName", member.get("locationName", name)[:1].upper() + + member.get("locationName", name)[1:]) + for name, member in request.items() + if shapes[member["shape"]].get("type") in SCALAR_SHAPES} + record = [name for name, member in shapes[spec_op["output"]["shape"]].get("members", {}).items() + if member["shape"] == _shape_name(kind)] + if len(record) != 1: + return None + record_member = shapes[spec_op["output"]["shape"]]["members"][record[0]] + structure_member = shapes[_shape_name(kind)].get("members", {}).get(spec["member"]) + if structure_member is None: + return None + structure = shapes[structure_member["shape"]].get("members", {}) + path = [record_member.get("locationName", record[0]), structure_member.get("locationName", spec["member"])] + joined: dict[str, str] = {} + for field in spec["fill"].values(): + located = path + [structure.get(field, {}).get("locationName", field)] + for sample in samples: + values = [leaf["value"] for leaf in sample.get("response", []) if leaf.get("path") == located] + named = sorted({member for member, query in wire.items() for value in values + if sample.get("request", {}).get(query) == value}) + if len(named) == 1: + if joined.get(field, named[0]) != named[0]: + return None + joined[field] = named[0] + if not joined or any(not member.endswith(field) for field, member in joined.items()): + return None + words = {member[:-len(field)] for field, member in joined.items()} + if len(words) != 1: + return None + word = next(iter(words)) + query = {} + for variable, field in spec["fill"].items(): + member = joined.get(field) or (word + field if word + field in wire else None) + if member is not None: + query[variable] = wire[member] + elif variable not in KNOWN_VARIABLES: + return None + return dict(sorted(query.items())) + return None + + def _shape_name(kind: str) -> str: """The botocore shape a resource type of the reference names: `network-interface` is `NetworkInterface`.""" return "".join(part[:1].upper() + part[1:] for part in kind.split("-")) @@ -5856,6 +6047,7 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) -> models, prefixes.get(namespace_of(operation)), forwarded, routed.get(operation)), operation, models) unqualified = unqualified_types(formats, operations, namespaces, data) alternates = alternate_formats(formats) + keys = resource_keys(documents, data, namespaces) return { "_source": { "generator": "tools/aws/regen_iam_request_resources.py", @@ -5873,7 +6065,8 @@ def build(documents: list[dict], provenance: str, data: Path, botocore: str) -> "pathFormats": path_formats, "resourceTagKeys": resource_tag_keys(documents, formats), "containerTagKeys": container_tag_keys(documents, formats), - "resourceKeys": resource_keys(documents, data, namespaces), + "resourceKeys": keys, + "madeResourceKeys": made_resource_keys(documents, data, namespaces, keys, operations), "unqualified": unqualified, "mintedIds": minted, "mintedSuffixes": suffixes, @@ -6044,8 +6237,8 @@ def render(document: dict) -> str: lines = ["{"] for key in ("_source", "namespaces", "notCovered", "otherNamespaces", "arnFormats", "pathFormats", "resourceTagKeys", "containerTagKeys", - "resourceKeys", "unqualified", "mintedIds", "mintedSuffixes", "integerVariables", "alternateFormats", - "narrowerFormats", "tagParents", + "resourceKeys", "madeResourceKeys", "unqualified", "mintedIds", "mintedSuffixes", "integerVariables", + "alternateFormats", "narrowerFormats", "tagParents", "forwardedActions", "statementActions", "statements"): lines.append(f' "{key}": {json.dumps(document[key])},') @@ -6148,12 +6341,17 @@ def validate(document: dict) -> list[str]: kind not in formats.get(namespace, {}) or not isinstance(keys, dict) or not keys or list(keys) != sorted(keys) or any( not re.fullmatch(rf"{re.escape(namespace)}:[A-Za-z0-9]+", key) or not isinstance(spec, dict) - or set(spec) - {"member", "arn"} or not isinstance(spec.get("member"), str) + or set(spec) - {"member", "arn", "fill"} or not isinstance(spec.get("member"), str) or ("arn" in spec and spec["arn"] not in formats.get(namespace, {})) + or ("fill" in spec and (namespace not in STRUCTURE_KEYS or "arn" not in spec + or not _fills_format(spec["fill"], formats[namespace][spec["arn"]]))) for key, spec in keys.items()) for kind, keys in kinds.items()) for namespace, kinds in resource_keys_document.items()): problems.append("resourceKeys is not member-named condition keys of supported resource types") + if not _valid_made_keys(document.get("madeResourceKeys", {}), document.get("operations", {}), + resource_keys_document): + problems.append("madeResourceKeys is not structure keys of the resources creates make") 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, {}) @@ -6724,9 +6922,13 @@ def main(argv: list[str] | None = None) -> int: untrue.append("resourceTagKeys differ from AWS Service Reference") if document.get("containerTagKeys", {}) != container_tag_keys(documents, formats): untrue.append("containerTagKeys differ from AWS Service Reference") - if document.get("resourceKeys", {}) != resource_keys(documents, resolve_botocore_data(args.botocore_data)[0], - document["namespaces"]): + botocore_data = resolve_botocore_data(args.botocore_data)[0] + upstream_keys = resource_keys(documents, botocore_data, document["namespaces"]) + if document.get("resourceKeys", {}) != upstream_keys: untrue.append("resourceKeys differ from AWS Service Reference and botocore") + if document.get("madeResourceKeys", {}) != made_resource_keys(documents, botocore_data, document["namespaces"], + upstream_keys, document["operations"]): + untrue.append("madeResourceKeys differ from AWS Service Reference, botocore and AWS's samples") untrue += verify_forwarded(document, documents) untrue += verify_permission_actions(document, documents) untrue += verify_group_actions(document, documents) @@ -6738,6 +6940,8 @@ def main(argv: list[str] | None = None) -> int: **TAG_INHERITANCE_SOURCES}, {**PERMISSION_FETCHERS, **ID_EXAMPLE_FETCHERS, **ARN_FORMAT_FETCHERS, **TAG_INHERITANCE_FETCHERS}) + # Keyed by namespace like the sources above, and EC2 has both, so verified apart. + untrue += verify_sources(SAMPLE_SOURCES, SAMPLE_FETCHERS) untrue += verify_required_type_source() except OSError as e: print(f"error: {e}", file=sys.stderr) diff --git a/tools/aws/sources/ec2-request-samples.json b/tools/aws/sources/ec2-request-samples.json new file mode 100644 index 0000000000..39bce6f426 --- /dev/null +++ b/tools/aws/sources/ec2-request-samples.json @@ -0,0 +1,129 @@ +{ + "_source": { + "fetcher": "tools/aws/fetch_ec2_request_samples.py", + "retrieved": "2026-12-05", + "pages": [ + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVpcPeeringConnection.html" + ] + }, + "namespace": "ec2", + "operations": { + "CreateVpcPeeringConnection": { + "page": "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateVpcPeeringConnection.html", + "samples": [ + { + "request": { + "VpcId": "vpc-1a2b3c4d", + "PeerVpcId": "vpc-a1b2c3d4", + "PeerOwnerId": "123456789012" + }, + "response": [ + { + "path": [ + "requestId" + ], + "value": "7a62c49f-347e-4fc4-9331-6e8eEXAMPLE" + }, + { + "path": [ + "vpcPeeringConnection", + "vpcPeeringConnectionId" + ], + "value": "pcx-73a5401a" + }, + { + "path": [ + "vpcPeeringConnection", + "requesterVpcInfo", + "ownerId" + ], + "value": "777788889999" + }, + { + "path": [ + "vpcPeeringConnection", + "requesterVpcInfo", + "vpcId" + ], + "value": "vpc-1a2b3c4d" + }, + { + "path": [ + "vpcPeeringConnection", + "requesterVpcInfo", + "cidrBlock" + ], + "value": "10.0.0.0/28" + }, + { + "path": [ + "vpcPeeringConnection", + "requesterVpcInfo", + "peeringOptions", + "allowEgressFromLocalClassicLinkToRemoteVpc" + ], + "value": "false" + }, + { + "path": [ + "vpcPeeringConnection", + "requesterVpcInfo", + "peeringOptions", + "allowEgressFromLocalVpcToRemoteClassicLink" + ], + "value": "false" + }, + { + "path": [ + "vpcPeeringConnection", + "requesterVpcInfo", + "peeringOptions", + "allowDnsResolutionFromRemoteVpc" + ], + "value": "false" + }, + { + "path": [ + "vpcPeeringConnection", + "accepterVpcInfo", + "ownerId" + ], + "value": "123456789012" + }, + { + "path": [ + "vpcPeeringConnection", + "accepterVpcInfo", + "vpcId" + ], + "value": "vpc-a1b2c3d4" + }, + { + "path": [ + "vpcPeeringConnection", + "status", + "code" + ], + "value": "initiating-request" + }, + { + "path": [ + "vpcPeeringConnection", + "status", + "message" + ], + "value": "Initiating Request to 123456789012" + }, + { + "path": [ + "vpcPeeringConnection", + "expirationTime" + ], + "value": "2014-02-18T14:37:25.000Z" + } + ] + } + ] + } + } +} diff --git a/tools/aws/test_fetch_ec2_request_samples.py b/tools/aws/test_fetch_ec2_request_samples.py new file mode 100644 index 0000000000..acbb60c07a --- /dev/null +++ b/tools/aws/test_fetch_ec2_request_samples.py @@ -0,0 +1,80 @@ +import html +import json + +import pytest + +import fetch_ec2_request_samples as f + + +def block(text): + return '
' + html.escape(text) + '
' + + +REQUEST = '''https://ec2.amazonaws.com/?Action=CreateVpcPeeringConnection +&VpcId=vpc-1a2b3c4d +&PeerVpcId=vpc-a1b2c3d4 +&PeerOwnerId=123456789012 +&AUTHPARAMS''' + +RESPONSE = ''' +7a62c49f-347e-4fc4-9331-6e8eEXAMPLE +pcx-73a5401a +777788889999vpc-1a2b3c4d +123456789012vpc-a1b2c3d4 + +''' + + +def page(request=REQUEST, response=RESPONSE): + return block(request) + block(response) + + +def test_pairs_a_sample_request_with_the_response_that_follows_it(): + assert f.read_samples("CreateVpcPeeringConnection", page()) == [{ + "request": {"VpcId": "vpc-1a2b3c4d", "PeerVpcId": "vpc-a1b2c3d4", "PeerOwnerId": "123456789012"}, + "response": [ + {"path": ["requestId"], "value": "7a62c49f-347e-4fc4-9331-6e8eEXAMPLE"}, + {"path": ["vpcPeeringConnection", "vpcPeeringConnectionId"], "value": "pcx-73a5401a"}, + {"path": ["vpcPeeringConnection", "requesterVpcInfo", "ownerId"], "value": "777788889999"}, + {"path": ["vpcPeeringConnection", "requesterVpcInfo", "vpcId"], "value": "vpc-1a2b3c4d"}, + {"path": ["vpcPeeringConnection", "accepterVpcInfo", "ownerId"], "value": "123456789012"}, + {"path": ["vpcPeeringConnection", "accepterVpcInfo", "vpcId"], "value": "vpc-a1b2c3d4"}]}] + + +def test_a_request_without_its_response_and_other_operations_are_left_out(): + other = REQUEST.replace("Action=CreateVpcPeeringConnection", "Action=OtherAction") + lone = REQUEST.replace("PeerOwnerId=123456789012", "PeerRegion=us-west-2") + source = block(other) + block(RESPONSE) + block(lone) + page() + assert f.read_samples("CreateVpcPeeringConnection", source) == \ + f.read_samples("CreateVpcPeeringConnection", page()) + + +@pytest.mark.parametrize("source", ["", block(REQUEST), block(RESPONSE)]) +def test_a_page_with_no_paired_sample_fails_closed(source): + with pytest.raises(ValueError, match="no sample request"): + f.read_samples("CreateVpcPeeringConnection", source) + + +def test_malformed_response_is_not_silently_omitted(): + with pytest.raises(ValueError, match="malformed XML"): + f.read_samples("CreateVpcPeeringConnection", page(response=RESPONSE.replace("", ""))) + + +def test_verification_detects_changed_samples_and_ignores_retrieval_date(tmp_path, monkeypatch): + output = tmp_path / "samples.json" + monkeypatch.setattr(f, "OUTPUT", output) + fetch = lambda url: page() + assert f.main([], fetch) == 0 + source = json.loads(output.read_text()) + source["_source"]["retrieved"] = "2000-01-01" + output.write_text(json.dumps(source)) + assert f.main(["--verify"], fetch) == 0 + assert f.main(["--verify"], lambda url: page(response=RESPONSE.replace("vpc-a1b2c3d4", "vpc-ffffffff"))) == 1 + + +def test_source_declares_namespace_and_pages_for_shared_verification(): + source = f.build({url: page() for url in f.PAGES.values()}) + assert source["namespace"] == "ec2" + assert source["_source"]["pages"] == list(f.PAGES.values()) + source["namespace"] = "other" + assert f.stale(source, {url: page() for url in f.PAGES.values()}) diff --git a/tools/aws/test_regen_iam_request_resources.py b/tools/aws/test_regen_iam_request_resources.py index 2c6f789373..0ebbe18aa1 100644 --- a/tools/aws/test_regen_iam_request_resources.py +++ b/tools/aws/test_regen_iam_request_resources.py @@ -2308,6 +2308,139 @@ def test_resource_keys_are_the_reference_keys_a_member_of_the_types_shape_names( assert r.resource_keys([document], Path("."), {}) == {} +PEERING_SHAPES = { + "VpcPeeringConnection": {"type": "structure", "members": { + "AccepterVpcInfo": {"shape": "VpcInfo", "locationName": "accepterVpcInfo"}, + "RequesterVpcInfo": {"shape": "VpcInfo", "locationName": "requesterVpcInfo"}, + "VpcPeeringConnectionId": {"shape": "String", "locationName": "vpcPeeringConnectionId"}}}, + "VpcInfo": {"type": "structure", "members": { + "CidrBlock": {"shape": "String", "locationName": "cidrBlock"}, + "OwnerId": {"shape": "String", "locationName": "ownerId", + "documentation": "

The ID of the Amazon Web Services account that owns the VPC.

"}, + "Region": {"shape": "String", "locationName": "region", + "documentation": "

The Region in which the VPC is located.

"}, + "VpcId": {"shape": "String", "locationName": "vpcId"}}}, + "String": {"type": "string"}} +PEERING_DOCUMENT = {"Name": "ec2", "ConditionKeys": [ + {"Name": "ec2:AccepterVpc", "Types": ["ARN"]}, {"Name": "ec2:RequesterVpc", "Types": ["ARN"]}, + {"Name": "ec2:VpcPeeringConnectionID", "Types": ["String"]}], + "Resources": [ + {"Name": "vpc-peering-connection", + "ARNFormats": ["arn:${Partition}:ec2:${Region}:${Account}:vpc-peering-connection/${VpcPeeringConnectionId}"], + "ConditionKeys": ["aws:ResourceTag/${TagKey}", "ec2:AccepterVpc", "ec2:RequesterVpc", + "ec2:VpcPeeringConnectionID"]}, + {"Name": "vpc", "ARNFormats": ["arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}"], + "ConditionKeys": []}], + "Actions": [{"Name": "CreateVpcPeeringConnection", "Resources": [ + {"Name": "vpc", "ConditionKeys": []}, + {"Name": "vpc-peering-connection", "ConditionKeys": ["ec2:AccepterVpc", "ec2:RequesterVpc"]}]}]} +PEERING_FILL = {"Account": "OwnerId", "Region": "Region", "VpcId": "VpcId"} + + +def test_structure_keys_fill_another_types_arn_from_the_structure_the_key_begins(monkeypatch): + import copy + + monkeypatch.setattr(r, "load_models", lambda data, clients: {"ec2": {"shapes": PEERING_SHAPES}}) + # An ARN key named as another type with a word before it reads the structure member beginning with its name, + # whose members fill that type's ARN: by name, the Region, and the member documented as an account's id. + assert r.resource_keys([PEERING_DOCUMENT], Path("."), {"ec2": ["ec2"]}) == {"ec2": {"vpc-peering-connection": { + "ec2:AccepterVpc": {"member": "AccepterVpcInfo", "arn": "vpc", "fill": PEERING_FILL}, + "ec2:RequesterVpc": {"member": "RequesterVpcInfo", "arn": "vpc", "fill": PEERING_FILL}, + "ec2:VpcPeeringConnectionID": {"member": "VpcPeeringConnectionId"}}}} + # A namespace not opted in reads no structure. + monkeypatch.setattr(r, "STRUCTURE_KEYS", ()) + assert r.resource_keys([PEERING_DOCUMENT], Path("."), {"ec2": ["ec2"]}) == {"ec2": {"vpc-peering-connection": { + "ec2:VpcPeeringConnectionID": {"member": "VpcPeeringConnectionId"}}}} + monkeypatch.setattr(r, "STRUCTURE_KEYS", ("ec2",)) + # A structure no member of which is documented as an account's id fills no ARN, and the key is left out. + undocumented = copy.deepcopy(PEERING_SHAPES) + del undocumented["VpcInfo"]["members"]["OwnerId"]["documentation"] + monkeypatch.setattr(r, "load_models", lambda data, clients: {"ec2": {"shapes": undocumented}}) + assert r.resource_keys([PEERING_DOCUMENT], Path("."), {"ec2": ["ec2"]}) == {"ec2": {"vpc-peering-connection": { + "ec2:VpcPeeringConnectionID": {"member": "VpcPeeringConnectionId"}}}} + + +def peering_create_model(request_members): + shapes = dict(PEERING_SHAPES) + shapes["CreateRequest"] = {"type": "structure", "members": request_members} + shapes["CreateResult"] = {"type": "structure", "members": { + "VpcPeeringConnection": {"shape": "VpcPeeringConnection", "locationName": "vpcPeeringConnection"}}} + return {"metadata": {"protocol": "ec2"}, "shapes": shapes, "operations": {"CreateVpcPeeringConnection": { + "input": {"shape": "CreateRequest"}, "output": {"shape": "CreateResult"}}}} + + +PEERING_REQUEST = {"PeerOwnerId": {"shape": "String", "locationName": "peerOwnerId"}, + "PeerVpcId": {"shape": "String", "locationName": "peerVpcId"}, + "VpcId": {"shape": "String", "locationName": "vpcId"}, + "PeerRegion": {"shape": "String"}} +PEERING_SAMPLE = {"request": {"VpcId": "vpc-1a2b3c4d", "PeerVpcId": "vpc-a1b2c3d4", "PeerOwnerId": "123456789012"}, + "response": [ + {"path": ["vpcPeeringConnection", "requesterVpcInfo", "ownerId"], "value": "777788889999"}, + {"path": ["vpcPeeringConnection", "requesterVpcInfo", "vpcId"], "value": "vpc-1a2b3c4d"}, + {"path": ["vpcPeeringConnection", "accepterVpcInfo", "ownerId"], "value": "123456789012"}, + {"path": ["vpcPeeringConnection", "accepterVpcInfo", "vpcId"], "value": "vpc-a1b2c3d4"}]} + + +def made_keys(monkeypatch, tmp_path, sample, request=PEERING_REQUEST, document=PEERING_DOCUMENT): + source = tmp_path / "samples.json" + source.write_text(json.dumps({"namespace": "ec2", "operations": { + "CreateVpcPeeringConnection": {"page": "https://example.test", "samples": [sample]}}})) + monkeypatch.setattr(r, "SAMPLE_SOURCES", {"ec2": source}) + monkeypatch.setattr(r, "load_models", lambda data, clients: {"ec2": peering_create_model(request)}) + keys = {"ec2": {"vpc-peering-connection": { + "ec2:AccepterVpc": {"member": "AccepterVpcInfo", "arn": "vpc", "fill": PEERING_FILL}, + "ec2:RequesterVpc": {"member": "RequesterVpcInfo", "arn": "vpc", "fill": PEERING_FILL}}}} + operations = {"ec2:CreateVpcPeeringConnection": {"resources": [ + {"type": "vpc", "fill": {"VpcId": "VpcId"}}, {"type": "vpc-peering-connection", "fill": {}, "made": True}]}} + return r.made_resource_keys([document], Path("."), {"ec2": ["ec2"]}, keys, operations) + + +def test_made_resource_keys_join_request_parameters_to_the_structure_by_awss_sample(monkeypatch, tmp_path): + import copy + + # The parameter AWS's sample answers with in the structure's member fills its variable, and behind the same + # word the parameter named as another of its members (PeerRegion); a variable none fills is the request's own. + assert made_keys(monkeypatch, tmp_path, PEERING_SAMPLE) == {"ec2:CreateVpcPeeringConnection": { + "ec2:AccepterVpc": {"type": "vpc-peering-connection", "arn": "vpc", + "query": {"Account": "PeerOwnerId", "Region": "PeerRegion", "VpcId": "PeerVpcId"}}, + "ec2:RequesterVpc": {"type": "vpc-peering-connection", "arn": "vpc", "query": {"VpcId": "VpcId"}}}} + # A sample whose values join no parameter to the accepter's members fills nothing of its own: the key is left out. + unjoined = copy.deepcopy(PEERING_SAMPLE) + unjoined["request"].update({"PeerVpcId": "vpc-ffffffff", "PeerOwnerId": "999999999999"}) + assert made_keys(monkeypatch, tmp_path, unjoined) == {"ec2:CreateVpcPeeringConnection": { + "ec2:RequesterVpc": {"type": "vpc-peering-connection", "arn": "vpc", "query": {"VpcId": "VpcId"}}}} + # Parameters joined behind different words name no one side. + renamed = {**{key: value for key, value in PEERING_REQUEST.items() if key != "PeerOwnerId"}, + "AccepterOwnerId": {"shape": "String", "locationName": "accepterOwnerId"}} + other_word = copy.deepcopy(PEERING_SAMPLE) + other_word["request"]["AccepterOwnerId"] = other_word["request"].pop("PeerOwnerId") + assert "ec2:AccepterVpc" not in made_keys(monkeypatch, tmp_path, other_word, renamed).get( + "ec2:CreateVpcPeeringConnection", {}) + # A key the reference does not list on the made resource for the create's action is not read from its request. + unlisted = copy.deepcopy(PEERING_DOCUMENT) + unlisted["Actions"][0]["Resources"][1]["ConditionKeys"] = ["ec2:RequesterVpc"] + assert made_keys(monkeypatch, tmp_path, PEERING_SAMPLE, document=unlisted) == { + "ec2:CreateVpcPeeringConnection": { + "ec2:RequesterVpc": {"type": "vpc-peering-connection", "arn": "vpc", "query": {"VpcId": "VpcId"}}}} + + +@pytest.mark.parametrize("mutate", [ + lambda d: d["madeResourceKeys"]["ec2:CreateVpcPeeringConnection"]["ec2:AccepterVpc"]["query"].update( + {"Partition": "PeerPartition"}), + lambda d: d["madeResourceKeys"]["ec2:CreateVpcPeeringConnection"]["ec2:AccepterVpc"].update({"arn": "subnet"}), + lambda d: d["madeResourceKeys"]["ec2:CreateVpcPeeringConnection"]["ec2:AccepterVpc"].update({"type": "vpc"}), + lambda d: d["madeResourceKeys"].update({"ec2:CreateVpc": d["madeResourceKeys"]["ec2:CreateVpcPeeringConnection"]}), + lambda d: d["resourceKeys"]["ec2"]["vpc-peering-connection"]["ec2:AccepterVpc"]["fill"].pop("Region"), +]) +def test_structure_and_made_resource_keys_are_validated(mutate): + import copy + + document = copy.deepcopy(json.loads(r.OUTPUT.read_text())) + assert not [problem for problem in r.validate(document) if "esourceKeys" in problem] + mutate(document) + assert [problem for problem in r.validate(document) if "esourceKeys" in problem] + + def test_id_prefixes_read_botocores_examples_by_the_shape_of_each_member(): ec2 = model({"DescribeGroups": {"GroupIds": "GroupIdList", "Label": "String"}}, "ec2") ec2["shapes"]["SecurityGroupId"] = {"type": "string"}