diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index ec4b6b2b23..a2ddee2647 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -1,8 +1,9 @@ name: IAM Data Drift -# Checks the three vendored files that come from AWS's live service reference rather than from a +# Checks the four vendored files that come from AWS's live service reference rather than from a # pinned dependency: the IAM service namespace list, the map of which resource each IAM action is -# authorized against, and the map of operations AWS authorizes as an action of another name. That +# authorized against, the map of operations AWS authorizes as an action of another name, and the +# table of the operations that pass a role and the services they pass it to. That # needs the live service reference index, so unlike every other check here it can # fail without anything in the repository having changed: an AWS outage, or a namespace AWS has # retired. It therefore runs on its own, never as part of a job that ordinary changes trigger. @@ -36,6 +37,9 @@ on: - 'src/main/resources/aws/iam-authorized-actions.json' - 'tools/aws/regen_iam_authorized_actions.py' - 'tools/aws/test_regen_iam_authorized_actions.py' + - 'src/main/resources/aws/iam-passed-roles.json' + - 'tools/aws/regen_iam_passed_roles.py' + - 'tools/aws/test_regen_iam_passed_roles.py' - '.github/workflows/iam-data-drift.yml' schedule: # Mondays at 06:00 UTC, before the working week rather than during it. diff --git a/Makefile b/Makefile index bde7e44d74..d3f5676475 100644 --- a/Makefile +++ b/Makefile @@ -64,7 +64,8 @@ PREFIX ?= $(HOME)/.local iam-action-resources-sync iam-action-resources-check iam-action-resources-verify \ iam-action-resources-test iam-authorized-actions-sync iam-authorized-actions-check \ cfn-property-types-sync cfn-property-types-check cfn-property-types-verify cfn-property-types-test \ - iam-authorized-actions-verify iam-authorized-actions-test iam-data-verify + iam-authorized-actions-verify iam-authorized-actions-test iam-passed-roles-sync iam-passed-roles-check \ + iam-passed-roles-verify iam-passed-roles-test iam-data-verify help: ## List the targets below @grep -hE '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}' @@ -305,6 +306,7 @@ aws-data-check: ## CI gate: the vendored AWS data must match a fresh generation echo " Run 'make aws-data-sync' with local/aws checked out and commit the result."; \ exit 1; \ } + @$(MAKE) --no-print-directory iam-passed-roles-check aws-data-test: ## Run the AWS data generators' unit tests $(PYTHON) -m pytest tools/aws -q @@ -365,11 +367,12 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A @# Both halves run even when the first fails, so one file's drift cannot hide the other's @# state. Sequential steps in CI stop at the first failure, which once left the action @# resource gate unexercised while the namespace list was stale. - @namespaces=0; actions=0; authorized=0; \ + @namespaces=0; actions=0; authorized=0; passed=0; \ $(MAKE) --no-print-directory iam-namespaces-verify || namespaces=$$?; \ $(MAKE) --no-print-directory iam-action-resources-verify || actions=$$?; \ $(MAKE) --no-print-directory iam-authorized-actions-verify || authorized=$$?; \ - if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ]; then \ + $(MAKE) --no-print-directory iam-passed-roles-verify || passed=$$?; \ + if [ $$namespaces -ne 0 ] || [ $$actions -ne 0 ] || [ $$authorized -ne 0 ] || [ $$passed -ne 0 ]; then \ echo ""; \ echo "error: vendored IAM data does not match upstream:"; \ if [ $$namespaces -ne 0 ]; then \ @@ -381,6 +384,9 @@ iam-data-verify: ## CI gate (online): every vendored IAM file must still match A if [ $$authorized -ne 0 ]; then \ echo " the map of operations to their IAM actions, see its message above"; \ fi; \ + if [ $$passed -ne 0 ]; then \ + echo " the table of the roles operations pass, see its message above"; \ + fi; \ exit 1; \ fi @@ -414,6 +420,34 @@ iam-authorized-actions-verify: ## CI gate (online): every vendored operation mus iam-authorized-actions-test: ## Run the IAM authorized-action generator's unit tests $(PYTHON) -m pytest tools/aws/test_regen_iam_authorized_actions.py -q +iam-passed-roles-sync: ## Regenerate src/main/resources/aws/iam-passed-roles.json from AWS and botocore (commit the result) + $(PYTHON) tools/aws/regen_iam_passed_roles.py + +iam-passed-roles-check: ## CI gate (offline): every vendored role member must be what the pinned botocore gives + @$(PYTHON) tools/aws/regen_iam_passed_roles.py --check || { \ + echo ""; \ + echo "error: src/main/resources/aws/iam-passed-roles.json is malformed or out of date."; \ + echo " Run 'make iam-passed-roles-sync' and commit the result."; \ + exit 1; \ + } + +iam-passed-roles-verify: ## CI gate (online): every vendored operation must still pass a role as AWS says + @$(PYTHON) tools/aws/regen_iam_passed_roles.py --verify; status=$$?; \ + if [ $$status -eq 2 ]; then \ + echo ""; \ + echo "error: could not reach AWS's service reference, so nothing was verified."; \ + exit 1; \ + elif [ $$status -ne 0 ]; then \ + echo ""; \ + echo "error: the vendored table reads a role from an operation AWS does not pass it from,"; \ + echo " or checks it for a service AWS does not pass it to."; \ + echo " Run 'make iam-passed-roles-sync' and commit the result."; \ + exit 1; \ + fi + +iam-passed-roles-test: ## Run the IAM passed role generator's unit tests + $(PYTHON) -m pytest tools/aws/test_regen_iam_passed_roles.py -q + cfn-property-types-sync: ## Regenerate src/main/resources/aws/cfn-property-types.json from AWS's resource schemas (commit the result) $(PYTHON) tools/aws/regen_cfn_property_types.py diff --git a/docs/services/iam.md b/docs/services/iam.md index cd5711cc83..3d6b901f48 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -1526,8 +1526,8 @@ role each passes: `targetRoleArn`, which the association's role assumes. `CreateAccessEntry` passes `principalArn` to `ec2.amazonaws.com` when its `type` is `EC2_LINUX` or `EC2_WINDOWS`: "If you create an access entry with type EC2_LINUX or EC2_WINDOWS, the IAM principal creating the access entry must have - the iam:PassRole permission." AWS also checks it for `CreateCapability`, `UpdateCapability`, - `RegisterCluster` and `UpdateClusterConfig`, which Floci does not serve. + the iam:PassRole permission." `CreateCapability`, `UpdateCapability` and `RegisterCluster`, which + Floci does not serve, are checked from the table below. - **CloudFormation:** `CreateStack`, `UpdateStack`, `DeleteStack`, `CreateChangeSet` and `ContinueUpdateRollback` pass `RoleARN` to `cloudformation.amazonaws.com` when the request names one. `CreateStackSet` and `UpdateStackSet` pass `AdministrationRoleARN`, or, for a self-managed @@ -1586,8 +1586,57 @@ holds it. Redshift takes a role only under the ARN IAM holds it under, path incl on the ARN as the request names it covers the role `COPY`, `UNLOAD` and Spectrum then use. The RDS user guide has the Enhanced Monitoring role checked: "The user that enables Enhanced Monitoring must be granted the PassRole permission." Removing a role from an RDS instance or cluster is checked as -adding one is, since the Service Reference lists `iam:PassRole` for both. The role parameters of -other services are not checked yet. +adding one is, since the Service Reference lists `iam:PassRole` for both. + +Every other operation the Service Reference lists with `iam:PassRole`, in the services Floci serves +over the JSON and Query protocols and Smithy RPC v2 CBOR and in the REST services whose routes are +authorized as operations, is checked from a table generated from the Service Reference and +botocore's models, `src/main/resources/aws/iam-passed-roles.json`. A request member names a role +when its name ends in `Role`, `RoleArn` or `RoleName` (or a plural, or one of those followed by +`Update` or `Override`) and it holds a string, or a list or map of them; it is read from a JSON or +CBOR body or from Query form parameters, in either list form, and its role is passed to the service +the Service Reference names. That covers Athena, CloudTrail, CloudWatch metric streams (to +`streams.metrics.cloudwatch.amazonaws.com`), CodeBuild, CodeDeploy, CodePipeline, Cognito, Config, +DataSync, ECR, Firehose, Glue, Kinesis Analytics, CloudWatch Logs, SageMaker, Secrets Manager, +Budgets actions, SES, SSM, Service Catalog, SWF, Textract, Transcribe and Transfer Family, among +others. The table lists an operation whether or not Floci serves it, so one Floci serves later is +checked from the start; one it does not serve answers `AccessDenied` rather than its usual error +when the caller may not pass the role. +- A member whose documentation says it takes a role by name, as a Glue job's `Role` and a CodeBuild + build's `serviceRoleOverride` do, is checked on the ARN IAM holds the role under, path included, + or, for a role IAM does not hold, the ARN the name gives. +- A role the Service Reference passes to no named service, as it does Cognito's group, user pool and + identity pool roles, is checked with no `iam:PassedToService`, so a grant conditioned on that key + does not cover it. +- Members that name no role passed to the service are left out: the roles a Budgets IAM action + attaches a policy to, a CodePipeline action's `roleArn`, which the pipeline's role assumes, the + execution role of each SSM target account, the roles a Glue job's code-generated nodes assume with + STS, a role a Redshift cluster already holds, and Firehose's Snowflake role. +- Members the rule does not see are added: a Cognito user pool's SMS caller roles, a Glue + connection's `ROLE_ARN` property ("The role to be used for running queries"), the role that + defines a Glue view, `TableInput.ViewDefinition.Definer` (Lake Formation's view prerequisites ask + for "The iam:PassRole permission for AWS Glue and Lake Formation"), and the Service Catalog + `AssumeRole` and `LAUNCH_ROLE` keys of a service action's definition and a provisioned product's + properties. +- Some operations are read by hand instead. SNS names its roles in attributes: a topic's + `SuccessFeedbackRoleArn` and `FailureFeedbackRoleArn`, which "are used to give + Amazon SNS write access to use CloudWatch Logs on your behalf", a platform application's + `SuccessFeedbackRoleArn` and `FailureFeedbackRoleArn`, a Firehose subscription's + `SubscriptionRoleArn` and the SMS `DeliveryStatusIAMRole`, read as the SNS handlers read the map. + A CloudWatch Logs subscription filter policy names its `RoleArn` in its document. A Service + Catalog launch constraint names its role in its `Parameters` document, by `RoleArn` or by + `LocalRoleName`, which is checked on the ARN IAM holds the role under, and an update goes by the + type of the constraint it changes. The type is matched in any case, since Floci keeps it as given. + An SWF decision is read from the attributes its `decisionType` names. +- Not read: an operation whose request names no role (SSM `CreateDocument`, for one); one whose role + is a parameter of the runbook it runs (SSM `StartAutomationExecution`, Config + `PutRemediationConfigurations`); one the Service Reference passes roles from to several services + without saying which member goes where (EMR `RunJobFlow`, whose `JobFlowRole` also names an + instance profile, EKS `UpdateClusterConfig`, CloudWatch Logs `CreateImportTask`, SageMaker + `CreateTrainingSession`); and one whose body is XML (S3 `PutBucketReplication`). EC2's + `RequestSpotFleet` names its roles in EC2's own protocol, one of them as an instance profile. The + REST services whose routes no rule maps yet, and API Gateway, which is authorized by HTTP method, + are not read either. A request that names its operation, in a Query `Action`, an `X-Amz-Target` header or a Smithy RPC v2 path (`/service//operation/`), is authorized as the action AWS checks for that @@ -1713,8 +1762,10 @@ policy it creates, checked against `*` like `logs:PutAccountPolicy` itself: `log for `DATA_PROTECTION_POLICY`, `logs:PutSubscriptionFilter` for `SUBSCRIPTION_FILTER_POLICY`, `logs:PutTransformer` for `TRANSFORMER_POLICY`, `logs:PutIndexPolicy` for `FIELD_INDEX_POLICY` and `logs:PutMetricExtractionPolicy` for `METRIC_EXTRACTION_POLICY`. Without it the request is refused with -`AccessDeniedException` and no policy is stored. The `iam:PassRole` a subscription filter policy with a -`RoleArn` also needs is not checked. +`AccessDeniedException` and no policy is stored. A subscription filter policy whose document names a +`RoleArn` also needs `iam:PassRole` on it for `logs.amazonaws.com`: "To perform a PutAccountPolicy +subscription filter operation for any destination except a Lambda function, you must also have the +iam:PassRole permission." `DescribeAccountPolicies` likewise needs the read action for the type it lists: `logs:GetDataProtectionPolicy`, `logs:DescribeSubscriptionFilters`, `logs:GetTransformer` or `logs:DescribeIndexPolicies`. Its reference names none for `METRIC_EXTRACTION_POLICY`, which needs only diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index a621af0cbc..7d834c6cb9 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -908,10 +908,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter { /** * A request that passes a role to a service also needs {@code iam:PassRole} on that role (see * {@link PassedRoles}), checked as the caller with {@code iam:PassedToService} naming the - * service and the keys that say who is calling, which {@code callerArns} writes when it is known. - * What a request names that holds roles, an instance profile, a launch template or a task - * definition, is looked up in the request's account, as the service resolves it; one that does not - * exist passes nothing, and the operation reports it. Returns true when the request was aborted. + * service, when AWS's Service Reference names one, and the keys that say who is calling, which + * {@code callerArns} writes when it is known. What a request names that holds roles, an instance + * profile, a launch template or a task definition, is looked up in the request's account, as the + * service resolves it; one that does not exist passes nothing, and the operation reports it. Returns + * true when the request was aborted. */ private boolean abortIfRolePassDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal, CallerArns callerArns, String action, String credentialScope, @@ -921,7 +922,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter { if (callerArns != null) { callerArns.putPrincipalKeys(context); } - context.put("iam:PassedToService", List.of(passed.passedToService())); + if (passed.passedToService() != null) { + context.put("iam:PassedToService", List.of(passed.passedToService())); + } if (abortIfDenied(ctx, caller, principal, "iam:PassRole", action, credentialScope, List.of(passed.roleArn()), List.of(context), region, accountId, akid)) { return true; @@ -980,6 +983,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter { public Optional heldRoleArn(String roleName) { return iamService.findRole(accountId, roleName).map(IamRole::getArn); } + + @Override + public Optional serviceCatalogConstraintType(String constraintId) { + return firstFound(lookup -> lookup.serviceCatalogConstraintType(constraintId)); + } }; } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoleMembers.java b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoleMembers.java new file mode 100644 index 0000000000..89666db8b9 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoleMembers.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Where each operation's request names the roles it passes, read once from the vendored + * {@code aws/iam-passed-roles.json}. + * + *

The file is generated by {@code tools/aws/regen_iam_passed_roles.py} from AWS's Service Reference, + * which lists {@code iam:PassRole} among an operation's authorized actions with the services the role goes + * to, and from botocore's model of the request, which gives the members that name a role. Every operation + * of the namespaces it reads is in it once: with the members to read, as one {@link PassedRoles} reads by + * hand, or as one whose request names no role it can read. {@code make iam-passed-roles-check} re-derives + * every member from botocore and {@code make iam-passed-roles-verify} checks every operation against AWS. + * + *

A missing or malformed resource is a build defect, so loading fails with + * {@link IllegalStateException} rather than leaving every operation it reads unchecked. + */ +final class PassedRoleMembers { + + static final String RESOURCE_NAME = "aws/iam-passed-roles.json"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** One step of a member path: a member, then each element of a list, each value of a map, or one key's value. */ + private static final Pattern STEP = Pattern.compile( + "([A-Za-z][A-Za-z0-9_]*)(?:\\[([A-Za-z0-9_]*)]|\\{([A-Za-z0-9_]*)})?"); + + /** How a member path goes on from a member. */ + enum Into { NONE, LIST, MAP, KEY } + + /** + * A step of a member path: the member {@code name}, then for {@link Into#LIST} each element, named + * {@code key} in the Query protocol when its shape names it, for {@link Into#MAP} each value, and for + * {@link Into#KEY} the value under {@code key}. + */ + record Step(String name, Into into, String key) { + } + + /** + * A member of a request that names a role, the service it is passed to (null when the Service Reference + * names none) and whether the member takes the role by name as well as by ARN. {@code queryKeys} matches + * the form parameters the Query protocol sends the member as; null for a member it cannot carry. + */ + record Member(String path, List steps, Pattern queryKeys, String passedTo, boolean byName) { + } + + /** The file: the members of each operation read from it, and the operations read by hand. */ + record Table(Map> members, Set byHand, Set notRead, + Set namespaces, Set notCovered, Set otherNamespaces) { + } + + private static final class Holder { + static final Table TABLE = VendoredResources.read(RESOURCE_NAME, "IAM passed role table", + PassedRoleMembers::parse); + } + + private PassedRoleMembers() { + } + + /** The members a request for {@code action} names its roles in; null when this table does not read it. */ + static List of(String action) { + return Holder.TABLE.members().get(action); + } + + static Table table() { + return Holder.TABLE; + } + + static Table parse(InputStream in) throws IOException { + JsonNode document = MAPPER.readTree(in); + JsonNode operations = document.path("operations"); + if (!operations.isObject() || operations.isEmpty()) { + throw new IllegalStateException(RESOURCE_NAME + " carries no operations"); + } + Map> members = new LinkedHashMap<>(); + Set byHand = new LinkedHashSet<>(); + Set notRead = new LinkedHashSet<>(); + operations.properties().forEach(operation -> { + JsonNode entry = operation.getValue(); + if (entry.has("byHand")) { + byHand.add(operation.getKey()); + } else if (entry.has("notRead")) { + notRead.add(operation.getKey()); + } else if (entry.path("roles").isArray() && !entry.path("roles").isEmpty()) { + List roles = new ArrayList<>(); + for (JsonNode role : entry.path("roles")) { + roles.add(member(operation.getKey(), role)); + } + members.put(operation.getKey(), List.copyOf(roles)); + } else { + throw new IllegalStateException(RESOURCE_NAME + " says nothing usable for " + operation.getKey()); + } + }); + return new Table(Map.copyOf(members), Set.copyOf(byHand), Set.copyOf(notRead), + Set.copyOf(document.path("namespaces").propertyStream().map(Map.Entry::getKey).toList()), + Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()), + Set.copyOf(document.path("otherNamespaces").valueStream().map(JsonNode::asText).toList())); + } + + private static Member member(String operation, JsonNode role) { + String path = role.path("member").asText(""); + List steps = new ArrayList<>(); + for (String step : path.split("\\.", -1)) { + Matcher matcher = STEP.matcher(step); + if (!matcher.matches()) { + throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path + + ", which is no member path"); + } + Into into = matcher.group(2) != null ? Into.LIST : matcher.group(3) == null ? Into.NONE + : matcher.group(3).isEmpty() ? Into.MAP : Into.KEY; + String key = into == Into.LIST ? matcher.group(2) : into == Into.KEY ? matcher.group(3) : null; + steps.add(new Step(matcher.group(1), into, key)); + } + String passedTo = role.hasNonNull("passedTo") ? role.get("passedTo").asText() : null; + return new Member(path, List.copyOf(steps), queryKeys(steps), passedTo, role.path("byName").asBoolean(false)); + } + + /** + * The form parameters the Query protocol sends a member as: a list's elements numbered under its name, + * generically as {@code member.N}, under the name its shape gives them or bare, as {@link AwsQueryLists} + * reads them, and a map's values as {@code entry.N.value}. A step into one key of a map is not read from a + * form, whose keys and values are separate parameters. + */ + private static Pattern queryKeys(List steps) { + StringBuilder regex = new StringBuilder(); + for (Step step : steps) { + if (step.into() == Into.KEY) { + return null; + } + if (!regex.isEmpty()) { + regex.append("\\."); + } + regex.append(Pattern.quote(step.name())); + if (step.into() == Into.LIST) { + regex.append(step.key().isEmpty() ? "(\\.member)?" : "(\\.member|\\." + Pattern.quote(step.key()) + ")?") + .append("\\.\\d+"); + } else if (step.into() == Into.MAP) { + regex.append("\\.entry\\.\\d+\\.value"); + } + } + return Pattern.compile(regex.toString()); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java index 65e3a0aa63..8d3fd41da9 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/PassedRoles.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.core.common; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.cbor.CBORFactory; @@ -10,6 +11,7 @@ import org.jboss.logging.Logger; import java.io.IOException; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -21,7 +23,14 @@ import java.util.regex.Pattern; * The IAM user guide: "To pass a role (and its permissions) to an AWS service, a user must have * permissions to pass the role to the service." AWS's Service Reference names, for each operation * that passes one, the service the role goes to, which the check offers as {@code iam:PassedToService}; - * where the request carries the role differs per operation and is listed here. + * where the request carries the role differs per operation. + * + *

Most operations name their roles in plain request members, which {@link PassedRoleMembers} reads + * from a table generated from the Service Reference and botocore's models. A member that takes a role + * by name is read as the role IAM holds under that name, or else the one the name gives in the + * request's account, and a role the Service Reference passes to no named service is checked with no + * {@code iam:PassedToService}. The operations below are read here instead, since their roles are not + * such a member. * *

An EC2 request names an instance profile rather than a role, and passes the roles the profile * holds. Launching from a launch template passes nothing here: the EC2 user guide warns that a user @@ -89,6 +98,20 @@ import java.util.regex.Pattern; * {@code IAM_ROLE_ARN} setting, as SQL Server's backup and audit options do. A DMS endpoint passes to * {@code dms.amazonaws.com} its service access role and the roles its settings name for each engine, and * a replication instance the role its Kerberos settings name. + * + *

An SNS topic's delivery status roles are attributes, which "are used to give Amazon SNS write access + * to use CloudWatch Logs on your behalf": {@code SuccessFeedbackRoleArn} and + * {@code FailureFeedbackRoleArn} for each kind of endpoint. So are a platform application's + * {@code SuccessFeedbackRoleArn} and {@code FailureFeedbackRoleArn}, a Firehose subscription's + * {@code SubscriptionRoleArn} and the SMS {@code DeliveryStatusIAMRole}; all go to {@code sns.amazonaws.com}. + * A CloudWatch Logs subscription filter policy names its role in its document: "To perform a + * PutAccountPolicy subscription filter operation for any destination except a Lambda function, you must + * also have the iam:PassRole permission." + * + *

A Service Catalog launch constraint names its launch role in its parameters document, by + * {@code RoleArn} or by {@code LocalRoleName}, which names the role without its path, so it is checked on + * the ARN IAM holds the role under. An SWF decision that starts a workflow execution names its Lambda role + * in the attributes its {@code decisionType} names. */ final class PassedRoles { @@ -118,6 +141,27 @@ final class PassedRoles { private static final String REDSHIFT_SERVERLESS = ServicePrincipals.of("redshift-serverless"); private static final String RDS = ServicePrincipals.of("rds"); private static final String DMS = ServicePrincipals.of("dms"); + private static final String SNS = ServicePrincipals.of("sns"); + private static final String LOGS = ServicePrincipals.of("logs"); + private static final String SERVICE_CATALOG = ServicePrincipals.of("servicecatalog"); + private static final String SWF = ServicePrincipals.of("swf"); + + /** The topic attributes that name a delivery status role, a success and a failure one per kind of endpoint. */ + private static final Set SNS_TOPIC_ROLES = Set.of( + "ApplicationSuccessFeedbackRoleArn", "ApplicationFailureFeedbackRoleArn", + "FirehoseSuccessFeedbackRoleArn", "FirehoseFailureFeedbackRoleArn", + "HTTPSuccessFeedbackRoleArn", "HTTPFailureFeedbackRoleArn", + "LambdaSuccessFeedbackRoleArn", "LambdaFailureFeedbackRoleArn", + "SQSSuccessFeedbackRoleArn", "SQSFailureFeedbackRoleArn"); + private static final Set SNS_SUBSCRIPTION_ROLES = Set.of("SubscriptionRoleArn"); + private static final Set SNS_PLATFORM_ROLES = Set.of("SuccessFeedbackRoleArn", "FailureFeedbackRoleArn"); + private static final Set SNS_SMS_ROLES = Set.of("DeliveryStatusIAMRole"); + private static final String SUBSCRIPTION_FILTER_POLICY = "SUBSCRIPTION_FILTER_POLICY"; + private static final String LAUNCH_CONSTRAINT = "LAUNCH"; + /** The SWF decisions that start a workflow execution, and the member each carries its attributes in. */ + private static final Map SWF_EXECUTION_DECISIONS = Map.of( + "ContinueAsNewWorkflowExecution", "continueAsNewWorkflowExecutionDecisionAttributes", + "StartChildWorkflowExecution", "startChildWorkflowExecutionDecisionAttributes"); /** The RDS operations whose request takes a {@code MonitoringRoleArn}. */ private static final Set RDS_MONITORING_ROLE = Set.of("rds:CreateDBCluster", "rds:CreateDBInstance", @@ -162,7 +206,7 @@ final class PassedRoles { private static final String DEFAULT_AUTOSCALING_ROLE = ":role/aws-service-role/" + AUTOSCALING + "/AWSServiceRoleForAutoScaling"; - /** A role a request passes, and the service principal it is passed to. */ + /** A role a request passes, and the service principal it is passed to; null when AWS names none. */ record PassedRole(String roleArn, String passedToService) { } @@ -199,6 +243,9 @@ final class PassedRoles { /** The ARN, path included, of the role IAM holds under {@code roleName}; empty when it holds none. */ Optional heldRoleArn(String roleName); + + /** The type of the Service Catalog constraint {@code constraintId}; empty when there is none. */ + Optional serviceCatalogConstraintType(String constraintId); } private PassedRoles() { @@ -206,6 +253,15 @@ final class PassedRoles { /** The roles a request for {@code action} passes; empty when the operation passes none or the request names none. */ static List of(String action, ContainerRequestContext ctx, Lookups lookups) { + List byHand = byHand(action, ctx, lookups); + return byHand != null ? byHand : fromTable(PassedRoleMembers.of(action), ctx, lookups); + } + + /** + * The roles a request for {@code action} passes, for an operation read here rather than from the table; + * null for any other. + */ + static List byHand(String action, ContainerRequestContext ctx, Lookups lookups) { return switch (action) { case "lambda:CreateFunction", "lambda:UpdateFunctionConfiguration" -> fromJson(ctx, LAMBDA, "Role"); case "lambda:CreateWebFunction" -> @@ -268,10 +324,211 @@ final class PassedRoles { case "dms:CreateEndpoint", "dms:ModifyEndpoint" -> dmsEndpointRoles(jsonBody(ctx)); case "dms:CreateReplicationInstance", "dms:ModifyReplicationInstance" -> fromJson(ctx, DMS, "KerberosAuthenticationSettings", "KeyCacheSecretIamArn"); - default -> List.of(); + case "sns:CreateTopic" -> snsAttributeRoles(ctx, "Attributes", SNS_TOPIC_ROLES); + case "sns:SetTopicAttributes" -> snsAttributeRole(ctx, SNS_TOPIC_ROLES); + case "sns:Subscribe" -> snsAttributeRoles(ctx, "Attributes", SNS_SUBSCRIPTION_ROLES); + case "sns:SetSubscriptionAttributes" -> snsAttributeRole(ctx, SNS_SUBSCRIPTION_ROLES); + case "sns:CreatePlatformApplication", "sns:SetPlatformApplicationAttributes" -> + snsAttributeRoles(ctx, "Attributes", SNS_PLATFORM_ROLES); + case "sns:SetSMSAttributes" -> snsAttributeRoles(ctx, "attributes", SNS_SMS_ROLES); + case "logs:PutAccountPolicy" -> subscriptionFilterPolicyRole(jsonBody(ctx)); + case "servicecatalog:CreateConstraint" -> launchConstraintRoles(jsonBody(ctx), lookups, false); + case "servicecatalog:UpdateConstraint" -> launchConstraintRoles(jsonBody(ctx), lookups, true); + case "swf:RespondDecisionTaskCompleted" -> swfDecisionRoles(jsonBody(ctx)); + default -> null; }; } + /** + * The roles a request names in the members the table gives for its operation: from its form parameters + * when it comes in the Query protocol, and from its JSON or CBOR body otherwise. + */ + private static List fromTable(List members, ContainerRequestContext ctx, + Lookups lookups) { + if (members == null) { + return List.of(); + } + Map form = IamConditionContextResolver.formParameters(ctx); + JsonNode body = form.isEmpty() ? jsonBody(ctx) : null; + List passed = new ArrayList<>(); + for (PassedRoleMembers.Member member : members) { + List roles = new ArrayList<>(); + if (!form.isEmpty()) { + if (member.queryKeys() != null) { + form.forEach((key, value) -> { + if (member.queryKeys().matcher(key).matches()) { + roles.add(value); + } + }); + } + } else { + collect(body, member.steps(), 0, roles); + } + passed.addAll(passed(member.byName() ? heldOrNamedRoles(roles, lookups) : roles, + member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo()))); + } + return passed; + } + + private static void collect(JsonNode node, List steps, int index, List found) { + if (node == null) { + return; + } + if (index == steps.size()) { + if (node.isTextual()) { + found.add(node.asText()); + } + return; + } + PassedRoleMembers.Step step = steps.get(index); + JsonNode value = node.get(step.name()); + switch (step.into()) { + case NONE -> collect(value, steps, index + 1, found); + case KEY -> collect(value == null ? null : value.get(step.key()), steps, index + 1, found); + case LIST, MAP -> { + if (value != null && (step.into() == PassedRoleMembers.Into.LIST ? value.isArray() : value.isObject())) { + for (JsonNode element : value) { + collect(element, steps, index + 1, found); + } + } + } + } + } + + /** Roles given by ARN or by name: a name is the role IAM holds under it, or else the one it gives. */ + private static List heldOrNamedRoles(List roles, Lookups lookups) { + List arns = new ArrayList<>(); + for (String role : roles) { + if (!role.isBlank()) { + arns.add(role.startsWith("arn:") ? role + : lookups.heldRoleArn(role).orElseGet(() -> lookups.roleArn(role))); + } + } + return arns; + } + + /** + * The roles among an SNS request's attributes {@code map}, read as the SNS handlers read the map: from a + * form, each {@code map.entry.N} from 1 up to the first with no key, the last value of a key named twice; + * from a JSON body, the {@code map} object. + */ + private static List snsAttributeRoles(ContainerRequestContext ctx, String map, Set roleAttributes) { + Map form = IamConditionContextResolver.formParameters(ctx); + Map attributes = new LinkedHashMap<>(); + if (!form.isEmpty()) { + for (int i = 1; form.get(map + ".entry." + i + ".key") != null; i++) { + attributes.put(form.get(map + ".entry." + i + ".key"), form.get(map + ".entry." + i + ".value")); + } + } else { + JsonNode body = jsonBody(ctx); + JsonNode values = body == null ? null : body.get(map); + if (values != null && values.isObject()) { + values.properties().forEach(entry -> attributes.put(entry.getKey(), entry.getValue().asText(null))); + } + } + List roles = new ArrayList<>(); + attributes.forEach((name, value) -> { + if (roleAttributes.contains(name)) { + roles.add(value); + } + }); + return passed(roles, SNS); + } + + /** + * The role an SNS {@code AttributeValue} names, when its {@code AttributeName} is one that names a role; a + * request with no value names none, and is left to SNS to answer. + */ + private static List snsAttributeRole(ContainerRequestContext ctx, Set roleAttributes) { + Map form = IamConditionContextResolver.formParameters(ctx); + String name; + String value; + if (!form.isEmpty()) { + name = form.get("AttributeName"); + value = form.get("AttributeValue"); + } else { + JsonNode body = jsonBody(ctx); + name = body == null ? null : body.path("AttributeName").asText(null); + value = body == null ? null : body.path("AttributeValue").asText(null); + } + if (name == null || value == null || !roleAttributes.contains(name)) { + return List.of(); + } + return passed(List.of(value), SNS); + } + + /** The role a CloudWatch Logs subscription filter policy's document names; another policy names none. */ + private static List subscriptionFilterPolicyRole(JsonNode body) { + if (body == null || !SUBSCRIPTION_FILTER_POLICY.equals(body.path("policyType").asText(null))) { + return List.of(); + } + return passed(values(embeddedJson(body.get("policyDocument")), "RoleArn"), LOGS); + } + + /** + * The launch role a Service Catalog launch constraint names in its {@code Parameters}, a JSON document, + * by {@code RoleArn} or by {@code LocalRoleName}, which names the role of that name in the caller's + * account without its path. A constraint of another type names no launch role. An update is read by + * the type Floci keeps for the constraint, since its request names none. The type is matched in any + * case, since Floci keeps it as given. + */ + private static List launchConstraintRoles(JsonNode body, Lookups lookups, boolean update) { + JsonNode parameters = body == null ? null : embeddedJson(body.get("Parameters")); + if (parameters == null) { + return List.of(); + } + String type; + if (update) { + String id = blankToNull(body.path("Id").asText(null)); + type = id == null ? null : lookups.serviceCatalogConstraintType(id).orElse(null); + } else { + type = body.path("Type").asText(null); + } + if (!LAUNCH_CONSTRAINT.equalsIgnoreCase(type)) { + return List.of(); + } + List roles = new ArrayList<>(values(parameters, "RoleArn")); + for (String name : values(parameters, "LocalRoleName")) { + if (!name.isBlank()) { + roles.add(lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name))); + } + } + return passed(roles, SERVICE_CATALOG); + } + + /** + * The roles of the decisions that start a workflow execution, each read from the attributes its + * {@code decisionType} names, as the SWF handler reads a decision. + */ + private static List swfDecisionRoles(JsonNode body) { + JsonNode decisions = body == null ? null : body.get("decisions"); + if (decisions == null || !decisions.isArray()) { + return List.of(); + } + List roles = new ArrayList<>(); + for (JsonNode decision : decisions) { + String attributes = SWF_EXECUTION_DECISIONS.get(decision.path("decisionType").asText("")); + if (attributes != null) { + roles.addAll(values(decision, attributes, "lambdaRole")); + } + } + return passed(roles, SWF); + } + + /** The JSON document a string member holds; null when the member holds no JSON. */ + private static JsonNode embeddedJson(JsonNode member) { + if (member == null || !member.isTextual()) { + return null; + } + try { + return MAPPER.readTree(member.asText()); + } catch (JsonProcessingException e) { + // A document that is not JSON has no member to name a role in. + LOG.debugv(e, "Embedded document is not JSON, so it passes no role"); + return null; + } + } + /** * The role AddRoleToInstanceProfile adds, which {@code RoleName} names without its path: the ARN IAM * holds it under, or else the one the name gives, so a role IAM does not hold is checked as named. diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java b/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java index a93aef47bf..968f512056 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/PassedRoleLookup.java @@ -7,8 +7,9 @@ import java.util.Optional; * Looks up what a stored resource holds that the {@code iam:PassRole} check of a request needs, for * the operations that pass a role the request does not name itself: an ECS task started from a task * definition runs with the definition's roles, a self-managed StackSet that names no - * administration role uses the default one, and an Auto Scaling group launches its instances with - * the instance profile of its launch template, or of the instance its launch configuration was made from. + * administration role uses the default one, an Auto Scaling group launches its instances with + * the instance profile of its launch template, or of the instance its launch configuration was made from, + * and a Service Catalog constraint update names no type, which says whether it sets a launch role. * *

Implemented by the services that own those resources, each answering for its own and leaving * the default for the rest; consumed lazily by {@code IamEnforcementFilter} via @@ -61,4 +62,9 @@ public interface PassedRoleLookup { String version, String region) { return Optional.empty(); } + + /** The type of the Service Catalog constraint {@code constraintId}; empty when there is none. */ + default Optional serviceCatalogConstraintType(String constraintId) { + return Optional.empty(); + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java b/src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java index 63ebb5617a..afa32f70ec 100644 --- a/src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java +++ b/src/main/java/io/github/hectorvent/floci/services/servicecatalog/ServiceCatalogService.java @@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.iam.PassedRoleLookup; import io.github.hectorvent.floci.services.organizations.OrganizationsService; import io.github.hectorvent.floci.services.organizations.model.CreateAccountStatus; import io.github.hectorvent.floci.services.organizations.model.OrganizationAccount; @@ -22,7 +23,7 @@ import java.util.Optional; import java.util.UUID; @ApplicationScoped -public class ServiceCatalogService { +public class ServiceCatalogService implements PassedRoleLookup { static final String CONTROL_TOWER_PORTFOLIO_ID = "port-flocicontrol1"; static final String CONTROL_TOWER_PORTFOLIO_NAME = "AWS Control Tower Account Factory Portfolio"; @@ -998,6 +999,12 @@ public class ServiceCatalogService { return require(associationStore, id, "constraint").deepCopy(); } + /** The constraint's type, which says whether an update of its parameters sets a launch role. */ + @Override + public Optional serviceCatalogConstraintType(String constraintId) { + return associationStore.get(constraintId).map(constraint -> constraint.path("Type").asText("")); + } + public ObjectNode describeProvisionedProduct(String id, String name) { if (id != null && !id.isBlank()) { return require(provisionedProductStore, id, "provisioned product").deepCopy(); diff --git a/src/main/resources/aws/iam-passed-roles.json b/src/main/resources/aws/iam-passed-roles.json new file mode 100644 index 0000000000..41ec05025e --- /dev/null +++ b/src/main/resources/aws/iam-passed-roles.json @@ -0,0 +1,1066 @@ +{ + "_source": {"generator": "tools/aws/regen_iam_passed_roles.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.113 (installed package)", "retrieved": "2026-10-24", "note": "make iam-passed-roles-check re-derives every member from botocore; make iam-passed-roles-verify checks every operation against AWS."}, + "namespaces": {"application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "autoscaling": ["autoscaling"], "budgets": ["budgets"], "cloudformation": ["cloudcontrol", "cloudformation"], "cloudtrail": ["cloudtrail"], "cloudwatch": ["cloudwatch", "cloudwatchomni"], "codebuild": ["codebuild"], "codedeploy": ["codedeploy"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "comprehend": ["comprehend"], "config": ["config"], "datasync": ["datasync"], "dms": ["dms"], "dsql": ["dsql"], "ec2": ["ec2"], "ecr": ["ecr"], "ecs": ["ecs"], "eks": ["eks"], "elasticmapreduce": ["emr"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "glue": ["glue"], "iam": ["iam"], "kinesis": ["kinesis"], "kinesisanalytics": ["kinesisanalytics", "kinesisanalyticsv2"], "lambda": ["lambda", "lambda-core", "lambda-microvms", "lambda-web"], "logs": ["logs"], "pipes": ["pipes"], "rds": ["docdb", "neptune", "rds"], "redshift": ["redshift"], "redshift-serverless": ["redshift-serverless"], "rekognition": ["rekognition"], "resource-groups": ["resource-groups"], "s3": ["s3", "s3control"], "sagemaker": ["sagemaker"], "scheduler": ["scheduler"], "secretsmanager": ["secretsmanager"], "servicecatalog": ["servicecatalog"], "ses": ["mailmanager", "pinpoint-email", "ses", "sesv2"], "sns": ["sns"], "ssm": ["ssm"], "states": ["stepfunctions"], "swf": ["swf"], "textract": ["textract"], "transcribe": ["transcribe"], "transfer": ["transfer"], "translate": ["translate"]}, + "notCovered": {"access-analyzer": "REST routes no rule maps yet", "airflow": "REST routes no rule maps yet", "apigateway": "authorized by HTTP method, so no request is checked as one of these operations", "appconfig": "REST routes no rule maps yet", "appsync": "REST routes no rule maps yet", "aps": "REST routes no rule maps yet", "aws-marketplace": "REST routes no rule maps yet", "backup": "REST routes no rule maps yet", "batch": "REST routes no rule maps yet", "bedrock": "REST routes no rule maps yet", "bedrock-agentcore": "REST routes no rule maps yet", "cloudfront": "REST routes no rule maps yet", "dlm": "REST routes no rule maps yet", "elasticfilesystem": "REST routes no rule maps yet", "emr-serverless": "REST routes no rule maps yet", "es": "REST routes no rule maps yet", "fis": "REST routes no rule maps yet", "guardduty": "REST routes no rule maps yet", "iot": "REST routes no rule maps yet", "kafka": "REST routes no rule maps yet", "macie2": "REST routes no rule maps yet", "mq": "REST routes no rule maps yet", "rum": "REST routes no rule maps yet", "s3tables": "REST routes no rule maps yet"}, + "otherNamespaces": ["agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "aoss", "appflow", "appmesh", "apprunner", "appstream", "arc-region-switch", "backup-gateway", "backup-search", "bcm-dashboards", "braket", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "codeconnections", "codestar-connections", "cognito-sync", "comprehendmedical", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "elemental-inference", "emr-containers", "entityresolution", "fms", "forecast", "frauddetector", "gamelift", "gameliftstreams", "geo", "grafana", "greengrass", "groundstation", "health-agent", "healthlake", "imagebuilder", "inspector", "iotdeviceadvisor", "iotfleetwise", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "kafkaconnect", "kendra", "lex", "lookoutequipment", "m2", "machinelearning", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "medical-imaging", "mobiletargeting", "neptune-graph", "observabilityadmin", "odb", "omics", "opensearch", "osis", "partnercentral", "pcs", "personalize", "profile", "proton", "qbusiness", "quicksight", "repostspace", "resiliencehub", "rolesanywhere", "s3files", "sagemaker-geospatial", "securityagent", "securitylake", "shield", "sms-voice", "snowball", "social-messaging", "ssm-incidents", "ssm-quicksetup", "storagegateway", "supportapp", "synthetics", "timestream", "voiceid", "wellarchitected", "wisdom", "workmail", "workspaces"], + "operations": { + "application-autoscaling:RegisterScalableTarget": {"passedTo": ["application-autoscaling"], "byHand": "the scalable target's role"}, + "athena:CreateWorkGroup": {"passedTo": ["athena"], "roles": [ + {"member": "Configuration.ExecutionRole", "passedTo": "athena"} + ]}, + "athena:StartSession": {"passedTo": ["athena"], "roles": [ + {"member": "ExecutionRole", "passedTo": "athena"} + ]}, + "athena:UpdateWorkGroup": {"passedTo": ["athena"], "roles": [ + {"member": "ConfigurationUpdates.ExecutionRole", "passedTo": "athena"} + ]}, + "autoscaling:CreateAutoScalingGroup": {"passedTo": ["autoscaling", "ec2"], "byHand": "the roles of each launch template's instance profile, and the service-linked and lifecycle hook roles"}, + "autoscaling:CreateLaunchConfiguration": {"passedTo": ["ec2"], "byHand": "the roles of the instance profile it names or takes from an instance"}, + "autoscaling:PutLifecycleHook": {"passedTo": ["autoscaling"], "byHand": "the hook's role"}, + "autoscaling:UpdateAutoScalingGroup": {"passedTo": ["autoscaling"], "byHand": "the roles of each launch template's instance profile, and the service-linked and lifecycle hook roles"}, + "budgets:CreateBudgetAction": {"passedTo": ["budgets"], "roles": [ + {"member": "ExecutionRoleArn", "passedTo": "budgets"} + ]}, + "budgets:UpdateBudgetAction": {"passedTo": ["budgets"], "roles": [ + {"member": "ExecutionRoleArn", "passedTo": "budgets"} + ]}, + "cloudformation:ActivateType": {"passedTo": ["resources.cloudformation"], "roles": [ + {"member": "ExecutionRoleArn", "passedTo": "resources.cloudformation"}, + {"member": "LoggingConfig.LogRoleArn", "passedTo": "resources.cloudformation"} + ]}, + "cloudformation:ContinueUpdateRollback": {"passedTo": ["cloudformation"], "byHand": "the stack's service role"}, + "cloudformation:CreateChangeSet": {"passedTo": ["cloudformation"], "byHand": "the stack's service role"}, + "cloudformation:CreateResource": {"passedTo": ["cloudformation"], "roles": [ + {"member": "RoleArn", "passedTo": "cloudformation"} + ]}, + "cloudformation:CreateStack": {"passedTo": ["cloudformation"], "byHand": "the stack's service role"}, + "cloudformation:CreateStackSet": {"passedTo": ["cloudformation"], "byHand": "the administration role, named or the default one"}, + "cloudformation:DeleteResource": {"passedTo": ["cloudformation"], "roles": [ + {"member": "RoleArn", "passedTo": "cloudformation"} + ]}, + "cloudformation:DeleteStack": {"passedTo": ["cloudformation"], "byHand": "the stack's service role"}, + "cloudformation:GetResource": {"passedTo": ["cloudformation"], "roles": [ + {"member": "RoleArn", "passedTo": "cloudformation"} + ]}, + "cloudformation:ListResources": {"passedTo": ["cloudformation"], "roles": [ + {"member": "RoleArn", "passedTo": "cloudformation"} + ]}, + "cloudformation:RegisterType": {"passedTo": ["resources.cloudformation"], "roles": [ + {"member": "ExecutionRoleArn", "passedTo": "resources.cloudformation"}, + {"member": "LoggingConfig.LogRoleArn", "passedTo": "resources.cloudformation"} + ]}, + "cloudformation:RollbackStack": {"passedTo": ["cloudformation"], "roles": [ + {"member": "RoleARN", "passedTo": "cloudformation"} + ]}, + "cloudformation:UpdateResource": {"passedTo": ["cloudformation"], "roles": [ + {"member": "RoleArn", "passedTo": "cloudformation"} + ]}, + "cloudformation:UpdateStack": {"passedTo": ["cloudformation"], "byHand": "the stack's service role"}, + "cloudformation:UpdateStackSet": {"passedTo": ["cloudformation"], "byHand": "the administration role, by the StackSet's permission model"}, + "cloudtrail:CreateTrail": {"passedTo": ["cloudtrail"], "roles": [ + {"member": "CloudWatchLogsRoleArn", "passedTo": "cloudtrail"} + ]}, + "cloudtrail:EnableFederation": {"passedTo": ["cloudtrail"], "roles": [ + {"member": "FederationRoleArn", "passedTo": "cloudtrail"} + ]}, + "cloudtrail:StartImport": {"passedTo": ["cloudtrail"], "roles": [ + {"member": "ImportSource.S3.S3BucketAccessRoleArn", "passedTo": "cloudtrail"} + ]}, + "cloudtrail:UpdateTrail": {"passedTo": ["cloudtrail"], "roles": [ + {"member": "CloudWatchLogsRoleArn", "passedTo": "cloudtrail"} + ]}, + "cloudwatch:CreateDomainForOrganization": {"passedTo": ["cloudwatch"], "roles": [ + {"member": "domainAccessRoleArn", "passedTo": "cloudwatch"} + ]}, + "cloudwatch:CreateIntegration": {"passedTo": ["cloudwatch"], "roles": [ + {"member": "roleArn", "passedTo": "cloudwatch"} + ]}, + "cloudwatch:CreateSpace": {"passedTo": ["cloudwatch"], "roles": [ + {"member": "agentCoreEvaluationRoleArn", "passedTo": "cloudwatch"}, + {"member": "dataAccessRoleArn", "passedTo": "cloudwatch"} + ]}, + "cloudwatch:PutLogAlarm": {"passedTo": ["cloudwatch"], "roles": [ + {"member": "ActionLogLineRoleArn", "passedTo": "cloudwatch"}, + {"member": "ScheduledQueryConfiguration.ScheduledQueryRoleARN", "passedTo": "cloudwatch"} + ]}, + "cloudwatch:PutMetricStream": {"passedTo": ["streams.metrics.cloudwatch"], "roles": [ + {"member": "RoleArn", "passedTo": "streams.metrics.cloudwatch"} + ]}, + "cloudwatch:UpdateIntegration": {"passedTo": ["cloudwatch"], "roles": [ + {"member": "roleArn", "passedTo": "cloudwatch"} + ]}, + "cloudwatch:UpdateSpace": {"passedTo": ["cloudwatch"], "roles": [ + {"member": "agentCoreEvaluationRoleArn", "passedTo": "cloudwatch"} + ]}, + "codebuild:CreateFleet": {"passedTo": [], "roles": [ + {"member": "fleetServiceRole"} + ]}, + "codebuild:CreateProject": {"passedTo": ["codebuild"], "roles": [ + {"member": "buildBatchConfig.serviceRole", "passedTo": "codebuild"}, + {"member": "serviceRole", "passedTo": "codebuild"} + ]}, + "codebuild:StartBuild": {"passedTo": ["codebuild"], "roles": [ + {"member": "serviceRoleOverride", "passedTo": "codebuild", "byName": true} + ]}, + "codebuild:StartBuildBatch": {"passedTo": ["codebuild"], "roles": [ + {"member": "buildBatchConfigOverride.serviceRole", "passedTo": "codebuild"}, + {"member": "serviceRoleOverride", "passedTo": "codebuild", "byName": true} + ]}, + "codebuild:UpdateFleet": {"passedTo": [], "roles": [ + {"member": "fleetServiceRole"} + ]}, + "codebuild:UpdateProject": {"passedTo": ["codebuild"], "roles": [ + {"member": "buildBatchConfig.serviceRole", "passedTo": "codebuild"}, + {"member": "serviceRole", "passedTo": "codebuild"} + ]}, + "codebuild:UpdateProjectVisibility": {"passedTo": ["codebuild"], "roles": [ + {"member": "resourceAccessRole", "passedTo": "codebuild"} + ]}, + "codedeploy:CreateDeploymentGroup": {"passedTo": ["codedeploy"], "roles": [ + {"member": "serviceRoleArn", "passedTo": "codedeploy"} + ]}, + "codedeploy:UpdateDeploymentGroup": {"passedTo": ["codedeploy"], "roles": [ + {"member": "serviceRoleArn", "passedTo": "codedeploy"} + ]}, + "codepipeline:CreatePipeline": {"passedTo": ["cloudformation", "codebuild", "codepipeline"], "roles": [ + {"member": "pipeline.roleArn", "passedTo": "codepipeline"}, + {"member": "pipeline.stages[].beforeEntry.conditions[].rules[].roleArn", "passedTo": "codepipeline"}, + {"member": "pipeline.stages[].onFailure.conditions[].rules[].roleArn", "passedTo": "codepipeline"}, + {"member": "pipeline.stages[].onSuccess.conditions[].rules[].roleArn", "passedTo": "codepipeline"} + ]}, + "codepipeline:UpdatePipeline": {"passedTo": ["cloudformation", "codebuild", "codepipeline"], "roles": [ + {"member": "pipeline.roleArn", "passedTo": "codepipeline"}, + {"member": "pipeline.stages[].beforeEntry.conditions[].rules[].roleArn", "passedTo": "codepipeline"}, + {"member": "pipeline.stages[].onFailure.conditions[].rules[].roleArn", "passedTo": "codepipeline"}, + {"member": "pipeline.stages[].onSuccess.conditions[].rules[].roleArn", "passedTo": "codepipeline"} + ]}, + "cognito-identity:SetIdentityPoolRoles": {"passedTo": [], "roles": [ + {"member": "RoleMappings{}.RulesConfiguration.Rules[].RoleARN"}, + {"member": "Roles{}"} + ]}, + "cognito-idp:CreateGroup": {"passedTo": [], "roles": [ + {"member": "RoleArn"} + ]}, + "cognito-idp:CreateUserImportJob": {"passedTo": [], "roles": [ + {"member": "CloudWatchLogsRoleArn"} + ]}, + "cognito-idp:CreateUserPool": {"passedTo": [], "roles": [ + {"member": "SmsConfiguration.EumsSms.CallerArn"}, + {"member": "SmsConfiguration.SnsCallerArn"} + ]}, + "cognito-idp:CreateUserPoolClient": {"passedTo": [], "roles": [ + {"member": "AnalyticsConfiguration.RoleArn"} + ]}, + "cognito-idp:SetUserPoolMfaConfig": {"passedTo": [], "roles": [ + {"member": "SmsMfaConfiguration.SmsConfiguration.EumsSms.CallerArn"}, + {"member": "SmsMfaConfiguration.SmsConfiguration.SnsCallerArn"} + ]}, + "cognito-idp:UpdateGroup": {"passedTo": [], "roles": [ + {"member": "RoleArn"} + ]}, + "cognito-idp:UpdateUserPool": {"passedTo": [], "roles": [ + {"member": "SmsConfiguration.EumsSms.CallerArn"}, + {"member": "SmsConfiguration.SnsCallerArn"} + ]}, + "cognito-idp:UpdateUserPoolClient": {"passedTo": [], "roles": [ + {"member": "AnalyticsConfiguration.RoleArn"} + ]}, + "comprehend:CreateDocumentClassifier": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:CreateEndpoint": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:CreateEntityRecognizer": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:CreateFlywheel": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:ImportModel": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartDocumentClassificationJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartDominantLanguageDetectionJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartEntitiesDetectionJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartEventsDetectionJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartKeyPhrasesDetectionJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartPiiEntitiesDetectionJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartSentimentDetectionJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartTargetedSentimentDetectionJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:StartTopicsDetectionJob": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:UpdateEndpoint": {"passedTo": ["comprehend"], "roles": [ + {"member": "DesiredDataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "comprehend:UpdateFlywheel": {"passedTo": ["comprehend"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "comprehend"} + ]}, + "config:PutConfigurationAggregator": {"passedTo": ["config"], "roles": [ + {"member": "OrganizationAggregationSource.RoleArn", "passedTo": "config"} + ]}, + "config:PutConfigurationRecorder": {"passedTo": ["config"], "roles": [ + {"member": "ConfigurationRecorder.roleARN", "passedTo": "config"} + ]}, + "config:PutConformancePack": {"passedTo": ["ssm"], "notRead": "no member of the request names a role"}, + "config:PutOrganizationConformancePack": {"passedTo": ["ssm"], "notRead": "no member of the request names a role"}, + "config:PutRemediationConfigurations": {"passedTo": ["ssm"], "notRead": "the role is a parameter of the runbook it runs, not a member of the request"}, + "datasync:CreateLocationAzureBlob": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:CreateLocationEfs": {"passedTo": ["datasync"], "roles": [ + {"member": "FileSystemAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:CreateLocationFsxOntap": {"passedTo": ["datasync"], "roles": [ + {"member": "Protocol.SMB.CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:CreateLocationFsxWindows": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:CreateLocationHdfs": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:CreateLocationObjectStorage": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:CreateLocationS3": {"passedTo": ["datasync"], "roles": [ + {"member": "S3Config.BucketAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:CreateLocationSmb": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:CreateTask": {"passedTo": ["datasync"], "roles": [ + {"member": "ManifestConfig.Source.S3.BucketAccessRoleArn", "passedTo": "datasync"}, + {"member": "TaskReportConfig.Destination.S3.BucketAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:StartTaskExecution": {"passedTo": ["datasync"], "roles": [ + {"member": "ManifestConfig.Source.S3.BucketAccessRoleArn", "passedTo": "datasync"}, + {"member": "TaskReportConfig.Destination.S3.BucketAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateLocationAzureBlob": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateLocationEfs": {"passedTo": ["datasync"], "roles": [ + {"member": "FileSystemAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateLocationFsxOntap": {"passedTo": ["datasync"], "roles": [ + {"member": "Protocol.SMB.CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateLocationFsxWindows": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateLocationHdfs": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateLocationObjectStorage": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateLocationS3": {"passedTo": ["datasync"], "roles": [ + {"member": "S3Config.BucketAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateLocationSmb": {"passedTo": ["datasync"], "roles": [ + {"member": "CustomSecretConfig.SecretAccessRoleArn", "passedTo": "datasync"} + ]}, + "datasync:UpdateTask": {"passedTo": ["datasync"], "roles": [ + {"member": "ManifestConfig.Source.S3.BucketAccessRoleArn", "passedTo": "datasync"}, + {"member": "TaskReportConfig.Destination.S3.BucketAccessRoleArn", "passedTo": "datasync"} + ]}, + "dms:CreateDataMigration": {"passedTo": ["dms"], "roles": [ + {"member": "ServiceAccessRoleArn", "passedTo": "dms"} + ]}, + "dms:CreateDataProvider": {"passedTo": ["dms"], "roles": [ + {"member": "Settings.IbmDb2LuwSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.IbmDb2zOsSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.MariaDbSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.MicrosoftSqlServerSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.MySqlSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.OracleSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.OracleSettings.SecretsManagerOracleAsmAccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.OracleSettings.SecretsManagerSecurityDbEncryptionAccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.PostgreSqlSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.RedshiftSettings.S3AccessRoleArn", "passedTo": "dms"} + ]}, + "dms:CreateEndpoint": {"passedTo": ["dms"], "byHand": "the endpoint's role and the roles of the settings structures DMS stores"}, + "dms:CreateFleetAdvisorCollector": {"passedTo": ["dms"], "roles": [ + {"member": "ServiceAccessRoleArn", "passedTo": "dms"} + ]}, + "dms:CreateInstanceProfile": {"passedTo": ["dms"], "notRead": "no member of the request names a role"}, + "dms:CreateMigrationProject": {"passedTo": ["dms"], "roles": [ + {"member": "SchemaConversionApplicationAttributes.S3BucketRoleArn", "passedTo": "dms"}, + {"member": "SourceDataProviderDescriptors[].SecretsManagerAccessRoleArn", "passedTo": "dms"}, + {"member": "TargetDataProviderDescriptors[].SecretsManagerAccessRoleArn", "passedTo": "dms"} + ]}, + "dms:CreateReplicationInstance": {"passedTo": ["dms"], "byHand": "the role of the Kerberos settings"}, + "dms:ModifyDataMigration": {"passedTo": ["dms"], "roles": [ + {"member": "ServiceAccessRoleArn", "passedTo": "dms"} + ]}, + "dms:ModifyDataProvider": {"passedTo": ["dms"], "roles": [ + {"member": "Settings.IbmDb2LuwSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.IbmDb2zOsSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.MariaDbSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.MicrosoftSqlServerSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.MySqlSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.OracleSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.OracleSettings.SecretsManagerOracleAsmAccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.OracleSettings.SecretsManagerSecurityDbEncryptionAccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.PostgreSqlSettings.S3AccessRoleArn", "passedTo": "dms"}, + {"member": "Settings.RedshiftSettings.S3AccessRoleArn", "passedTo": "dms"} + ]}, + "dms:ModifyEndpoint": {"passedTo": ["dms"], "byHand": "the endpoint's role and the roles of the settings structures DMS stores"}, + "dms:ModifyInstanceProfile": {"passedTo": ["dms"], "notRead": "no member of the request names a role"}, + "dms:ModifyMigrationProject": {"passedTo": ["dms"], "roles": [ + {"member": "SchemaConversionApplicationAttributes.S3BucketRoleArn", "passedTo": "dms"}, + {"member": "SourceDataProviderDescriptors[].SecretsManagerAccessRoleArn", "passedTo": "dms"}, + {"member": "TargetDataProviderDescriptors[].SecretsManagerAccessRoleArn", "passedTo": "dms"} + ]}, + "dms:ModifyReplicationInstance": {"passedTo": ["dms"], "byHand": "the role of the Kerberos settings"}, + "dms:StartReplicationTaskAssessmentRun": {"passedTo": ["dms"], "roles": [ + {"member": "ServiceAccessRoleArn", "passedTo": "dms"} + ]}, + "dsql:CreateStream": {"passedTo": ["dsql"], "roles": [ + {"member": "targetDefinition.kinesis.roleArn", "passedTo": "dsql"} + ]}, + "ec2:AssociateIamInstanceProfile": {"passedTo": ["ec2"], "byHand": "the roles of the instance profile it names"}, + "ec2:CreateFlowLogs": {"passedTo": ["vpc-flow-logs"], "byHand": "the delivery role"}, + "ec2:CreateLaunchTemplate": {"passedTo": ["ec2"], "byHand": "the roles of the instance profile the template names"}, + "ec2:CreateLaunchTemplateVersion": {"passedTo": ["ec2"], "byHand": "the roles of the instance profile the template names"}, + "ec2:ReplaceIamInstanceProfileAssociation": {"passedTo": ["ec2"], "byHand": "the roles of the instance profile it names"}, + "ec2:RequestSpotFleet": {"passedTo": ["ec2"], "notRead": "the request names its roles in EC2's own protocol, one of them as an instance profile"}, + "ec2:RequestSpotInstances": {"passedTo": ["ec2"], "byHand": "the roles of the instance profile it names"}, + "ec2:RunInstances": {"passedTo": ["ec2"], "byHand": "the roles of the instance profile it names"}, + "ecr:CreatePullThroughCacheRule": {"passedTo": ["ecr"], "roles": [ + {"member": "customRoleArn", "passedTo": "ecr"} + ]}, + "ecr:CreateRepositoryCreationTemplate": {"passedTo": ["ecr"], "roles": [ + {"member": "customRoleArn", "passedTo": "ecr"} + ]}, + "ecr:UpdatePullThroughCacheRule": {"passedTo": ["ecr"], "roles": [ + {"member": "customRoleArn", "passedTo": "ecr"} + ]}, + "ecr:UpdateRepositoryCreationTemplate": {"passedTo": ["ecr"], "roles": [ + {"member": "customRoleArn", "passedTo": "ecr"} + ]}, + "ecs:CreateCapacityProvider": {"passedTo": ["ecs"], "byHand": "the infrastructure role, by name or ARN"}, + "ecs:CreateDaemon": {"passedTo": ["ecs-tasks"], "notRead": "the roles are the daemon task definition's, which only a lookup finds"}, + "ecs:CreateExpressGatewayService": {"passedTo": ["ecs", "ecs-tasks"], "roles": [ + {"member": "executionRoleArn", "passedTo": "ecs-tasks"}, + {"member": "infrastructureRoleArn", "passedTo": "ecs"}, + {"member": "taskRoleArn", "passedTo": "ecs-tasks"} + ]}, + "ecs:CreateGateway": {"passedTo": ["ecs"], "notRead": "botocore's model has no such operation"}, + "ecs:CreateService": {"passedTo": ["ecs", "ecs-tasks"], "byHand": "the task definition's roles and the service's infrastructure roles"}, + "ecs:CreateTaskSet": {"passedTo": ["ecs-tasks"], "byHand": "the task definition's roles"}, + "ecs:RegisterDaemonTaskDefinition": {"passedTo": ["ecs-tasks"], "roles": [ + {"member": "executionRoleArn", "passedTo": "ecs-tasks"}, + {"member": "taskRoleArn", "passedTo": "ecs-tasks", "byName": true} + ]}, + "ecs:RegisterTaskDefinition": {"passedTo": ["ecs-tasks"], "byHand": "the task and task execution roles, by name or ARN"}, + "ecs:RunTask": {"passedTo": ["ecs", "ecs-tasks"], "byHand": "the task definition's roles, their overrides and the volumes' infrastructure role"}, + "ecs:StartTask": {"passedTo": ["ecs", "ecs-tasks"], "byHand": "the task definition's roles, their overrides and the volumes' infrastructure role"}, + "ecs:UpdateCapacityProvider": {"passedTo": ["ecs"], "byHand": "the infrastructure role, by name or ARN"}, + "ecs:UpdateDaemon": {"passedTo": ["ecs-tasks"], "notRead": "the roles are the daemon task definition's, which only a lookup finds"}, + "ecs:UpdateExpressGatewayService": {"passedTo": ["ecs", "ecs-tasks"], "roles": [ + {"member": "executionRoleArn", "passedTo": "ecs-tasks"}, + {"member": "taskRoleArn", "passedTo": "ecs-tasks"} + ]}, + "ecs:UpdateGateway": {"passedTo": ["ecs"], "notRead": "botocore's model has no such operation"}, + "ecs:UpdateService": {"passedTo": ["ecs", "ecs-tasks"], "byHand": "the task definition's roles and the service's infrastructure roles"}, + "eks:CreateAccessEntry": {"passedTo": ["ec2"], "byHand": "the principal, for the node types alone"}, + "eks:CreateAddon": {"passedTo": ["eks"], "byHand": "the service account role and each Pod Identity association's role"}, + "eks:CreateCapability": {"passedTo": ["eks"], "roles": [ + {"member": "roleArn", "passedTo": "eks"} + ]}, + "eks:CreateCluster": {"passedTo": ["ec2", "eks"], "byHand": "the cluster role"}, + "eks:CreateFargateProfile": {"passedTo": ["eks"], "byHand": "the pod execution role"}, + "eks:CreateNodegroup": {"passedTo": ["eks"], "byHand": "the node role"}, + "eks:CreatePodIdentityAssociation": {"passedTo": ["pods.eks"], "byHand": "the association's role, not its target role"}, + "eks:RegisterCluster": {"passedTo": ["eks"], "roles": [ + {"member": "connectorConfig.roleArn", "passedTo": "eks"} + ]}, + "eks:UpdateAddon": {"passedTo": ["eks"], "byHand": "the service account role and each Pod Identity association's role"}, + "eks:UpdateCapability": {"passedTo": ["eks"], "roles": [ + {"member": "roleArn", "passedTo": "eks"} + ]}, + "eks:UpdateClusterConfig": {"passedTo": ["ec2", "eks"], "notRead": "the reference passes the node role to ec2 or eks and nothing says which"}, + "eks:UpdatePodIdentityAssociation": {"passedTo": ["pods.eks"], "byHand": "the association's role, not its target role"}, + "elasticmapreduce:CreateStudio": {"passedTo": [], "roles": [ + {"member": "ServiceRole"}, + {"member": "UserRole"} + ]}, + "elasticmapreduce:RunJobFlow": {"passedTo": ["application-autoscaling", "ec2", "elasticmapreduce"], "notRead": "JobFlowRole names an instance profile, and the reference passes the roles to three services without saying which goes where"}, + "elasticmapreduce:StartNotebookExecution": {"passedTo": [], "roles": [ + {"member": "ExecutionEngine.ExecutionRoleArn"}, + {"member": "ServiceRole", "byName": true} + ]}, + "elasticmapreduce:StartSession": {"passedTo": ["elasticmapreduce"], "roles": [ + {"member": "ExecutionRoleArn", "passedTo": "elasticmapreduce"} + ]}, + "elasticmapreduce:UpdateStudio": {"passedTo": [], "notRead": "no member of the request names a role"}, + "events:CreateEndpoint": {"passedTo": ["events"], "roles": [ + {"member": "RoleArn", "passedTo": "events"} + ]}, + "events:CreateSubscriber": {"passedTo": ["events"], "roles": [ + {"member": "InvokeConfiguration.RoleArn", "passedTo": "events"} + ]}, + "events:PutRule": {"passedTo": ["events"], "byHand": "the rule's role"}, + "events:PutTargets": {"passedTo": ["events"], "byHand": "each target's role"}, + "events:UpdateEndpoint": {"passedTo": ["events"], "roles": [ + {"member": "RoleArn", "passedTo": "events"} + ]}, + "events:UpdateSubscriber": {"passedTo": ["events"], "roles": [ + {"member": "InvokeConfiguration.RoleArn", "passedTo": "events"} + ]}, + "firehose:CreateDeliveryStream": {"passedTo": ["firehose"], "roles": [ + {"member": "AmazonOpenSearchServerlessDestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "AmazonOpenSearchServerlessDestinationConfiguration.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "AmazonOpenSearchServerlessDestinationConfiguration.VpcConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "AmazonopensearchserviceDestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "AmazonopensearchserviceDestinationConfiguration.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "AmazonopensearchserviceDestinationConfiguration.VpcConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "DatabaseSourceConfiguration.DatabaseSourceAuthenticationConfiguration.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "ElasticsearchDestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "ElasticsearchDestinationConfiguration.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "ElasticsearchDestinationConfiguration.VpcConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "ExtendedS3DestinationConfiguration.DataFormatConversionConfiguration.SchemaConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "ExtendedS3DestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "ExtendedS3DestinationConfiguration.S3BackupConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "HttpEndpointDestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "HttpEndpointDestinationConfiguration.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "HttpEndpointDestinationConfiguration.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "IcebergDestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "IcebergDestinationConfiguration.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "KinesisStreamSourceConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "MSKSourceConfiguration.AuthenticationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "RedshiftDestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "RedshiftDestinationConfiguration.S3BackupConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "RedshiftDestinationConfiguration.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "RedshiftDestinationConfiguration.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "S3DestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "SnowflakeDestinationConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "SnowflakeDestinationConfiguration.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "SnowflakeDestinationConfiguration.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "SplunkDestinationConfiguration.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "SplunkDestinationConfiguration.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"} + ]}, + "firehose:UpdateDestination": {"passedTo": ["firehose"], "roles": [ + {"member": "AmazonOpenSearchServerlessDestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "AmazonOpenSearchServerlessDestinationUpdate.S3Update.RoleARN", "passedTo": "firehose"}, + {"member": "AmazonopensearchserviceDestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "AmazonopensearchserviceDestinationUpdate.S3Update.RoleARN", "passedTo": "firehose"}, + {"member": "ElasticsearchDestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "ElasticsearchDestinationUpdate.S3Update.RoleARN", "passedTo": "firehose"}, + {"member": "ExtendedS3DestinationUpdate.DataFormatConversionConfiguration.SchemaConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "ExtendedS3DestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "ExtendedS3DestinationUpdate.S3BackupUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "HttpEndpointDestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "HttpEndpointDestinationUpdate.S3Update.RoleARN", "passedTo": "firehose"}, + {"member": "HttpEndpointDestinationUpdate.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "IcebergDestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "IcebergDestinationUpdate.S3Configuration.RoleARN", "passedTo": "firehose"}, + {"member": "RedshiftDestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "RedshiftDestinationUpdate.S3BackupUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "RedshiftDestinationUpdate.S3Update.RoleARN", "passedTo": "firehose"}, + {"member": "RedshiftDestinationUpdate.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "S3DestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "SnowflakeDestinationUpdate.RoleARN", "passedTo": "firehose"}, + {"member": "SnowflakeDestinationUpdate.S3Update.RoleARN", "passedTo": "firehose"}, + {"member": "SnowflakeDestinationUpdate.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"}, + {"member": "SplunkDestinationUpdate.S3Update.RoleARN", "passedTo": "firehose"}, + {"member": "SplunkDestinationUpdate.SecretsManagerConfiguration.RoleARN", "passedTo": "firehose"} + ]}, + "glue:CreateCatalog": {"passedTo": ["glue"], "roles": [ + {"member": "CatalogInput.CatalogProperties.DataLakeAccessProperties.DataTransferRole", "passedTo": "glue"}, + {"member": "CatalogInput.CatalogProperties.IcebergOptimizationProperties.RoleArn", "passedTo": "glue"} + ]}, + "glue:CreateColumnStatisticsTaskSettings": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue"} + ]}, + "glue:CreateConnection": {"passedTo": ["glue"], "roles": [ + {"member": "ConnectionInput.ConnectionProperties{ROLE_ARN}", "passedTo": "glue"} + ]}, + "glue:CreateCrawler": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue", "byName": true} + ]}, + "glue:CreateDevEndpoint": {"passedTo": ["glue"], "roles": [ + {"member": "RoleArn", "passedTo": "glue"} + ]}, + "glue:CreateIntegrationResourceProperty": {"passedTo": ["glue"], "roles": [ + {"member": "SourceProcessingProperties.RoleArn", "passedTo": "glue"}, + {"member": "TargetProcessingProperties.RoleArn", "passedTo": "glue"} + ]}, + "glue:CreateJob": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue", "byName": true} + ]}, + "glue:CreateMLTransform": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue", "byName": true} + ]}, + "glue:CreateSession": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue"} + ]}, + "glue:CreateTable": {"passedTo": ["glue"], "roles": [ + {"member": "TableInput.ViewDefinition.Definer", "passedTo": "glue"} + ]}, + "glue:CreateTableOptimizer": {"passedTo": ["glue"], "roles": [ + {"member": "TableOptimizerConfiguration.roleArn", "passedTo": "glue"} + ]}, + "glue:GetJob": {"passedTo": ["glue"], "notRead": "no member of the request names a role"}, + "glue:GetJobs": {"passedTo": ["glue"], "notRead": "no member of the request names a role"}, + "glue:PutDataCatalogEncryptionSettings": {"passedTo": ["glue"], "roles": [ + {"member": "DataCatalogEncryptionSettings.EncryptionAtRest.CatalogEncryptionServiceRole", "passedTo": "glue"} + ]}, + "glue:StartBlueprintRun": {"passedTo": ["glue"], "roles": [ + {"member": "RoleArn", "passedTo": "glue"} + ]}, + "glue:StartColumnStatisticsTaskRun": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue"} + ]}, + "glue:StartDataQualityRuleRecommendationRun": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue"} + ]}, + "glue:StartDataQualityRulesetEvaluationRun": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue"} + ]}, + "glue:TestConnection": {"passedTo": ["glue"], "roles": [ + {"member": "TestConnectionInput.ConnectionProperties{ROLE_ARN}", "passedTo": "glue"} + ]}, + "glue:UpdateCatalog": {"passedTo": ["glue"], "roles": [ + {"member": "CatalogInput.CatalogProperties.DataLakeAccessProperties.DataTransferRole", "passedTo": "glue"}, + {"member": "CatalogInput.CatalogProperties.IcebergOptimizationProperties.RoleArn", "passedTo": "glue"} + ]}, + "glue:UpdateColumnStatisticsTaskSettings": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue"} + ]}, + "glue:UpdateConnection": {"passedTo": ["glue"], "roles": [ + {"member": "ConnectionInput.ConnectionProperties{ROLE_ARN}", "passedTo": "glue"} + ]}, + "glue:UpdateCrawler": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue", "byName": true} + ]}, + "glue:UpdateIntegrationResourceProperty": {"passedTo": ["glue"], "roles": [ + {"member": "SourceProcessingProperties.RoleArn", "passedTo": "glue"}, + {"member": "TargetProcessingProperties.RoleArn", "passedTo": "glue"} + ]}, + "glue:UpdateJob": {"passedTo": ["glue"], "roles": [ + {"member": "JobUpdate.Role", "passedTo": "glue", "byName": true} + ]}, + "glue:UpdateMLTransform": {"passedTo": ["glue"], "roles": [ + {"member": "Role", "passedTo": "glue", "byName": true} + ]}, + "glue:UpdateTable": {"passedTo": ["glue"], "roles": [ + {"member": "TableInput.ViewDefinition.Definer", "passedTo": "glue"} + ]}, + "glue:UpdateTableOptimizer": {"passedTo": ["glue"], "roles": [ + {"member": "TableOptimizerConfiguration.roleArn", "passedTo": "glue"} + ]}, + "iam:AddRoleToInstanceProfile": {"passedTo": ["ec2"], "byHand": "the role it adds, on the ARN IAM holds it under"}, + "kinesis:CreateChannel": {"passedTo": ["kinesis"], "roles": [ + {"member": "ServiceExecutionRoleARN", "passedTo": "kinesis"} + ]}, + "kinesisanalytics:AddApplicationCloudWatchLoggingOption": {"passedTo": ["kinesisanalytics"], "roles": [ + {"member": "CloudWatchLoggingOption.RoleARN", "passedTo": "kinesisanalytics"} + ]}, + "kinesisanalytics:AddApplicationInput": {"passedTo": ["kinesisanalytics"], "roles": [ + {"member": "Input.InputProcessingConfiguration.InputLambdaProcessor.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Input.KinesisFirehoseInput.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Input.KinesisStreamsInput.RoleARN", "passedTo": "kinesisanalytics"} + ]}, + "kinesisanalytics:AddApplicationOutput": {"passedTo": ["kinesisanalytics"], "roles": [ + {"member": "Output.KinesisFirehoseOutput.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Output.KinesisStreamsOutput.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Output.LambdaOutput.RoleARN", "passedTo": "kinesisanalytics"} + ]}, + "kinesisanalytics:AddApplicationReferenceDataSource": {"passedTo": ["kinesisanalytics"], "roles": [ + {"member": "ReferenceDataSource.S3ReferenceDataSource.ReferenceRoleARN", "passedTo": "kinesisanalytics"} + ]}, + "kinesisanalytics:CreateApplication": {"passedTo": ["kinesisanalytics"], "roles": [ + {"member": "CloudWatchLoggingOptions[].RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Inputs[].InputProcessingConfiguration.InputLambdaProcessor.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Inputs[].KinesisFirehoseInput.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Inputs[].KinesisStreamsInput.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Outputs[].KinesisFirehoseOutput.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Outputs[].KinesisStreamsOutput.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "Outputs[].LambdaOutput.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "ServiceExecutionRole", "passedTo": "kinesisanalytics"} + ]}, + "kinesisanalytics:DiscoverInputSchema": {"passedTo": ["kinesisanalytics"], "roles": [ + {"member": "InputProcessingConfiguration.InputLambdaProcessor.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "S3Configuration.RoleARN", "passedTo": "kinesisanalytics"}, + {"member": "ServiceExecutionRole", "passedTo": "kinesisanalytics"} + ]}, + "kinesisanalytics:UpdateApplication": {"passedTo": ["kinesisanalytics"], "roles": [ + {"member": "ApplicationUpdate.CloudWatchLoggingOptionUpdates[].RoleARNUpdate", "passedTo": "kinesisanalytics"}, + {"member": "ApplicationUpdate.InputUpdates[].InputProcessingConfigurationUpdate.InputLambdaProcessorUpdate.RoleARNUpdate", "passedTo": "kinesisanalytics"}, + {"member": "ApplicationUpdate.InputUpdates[].KinesisFirehoseInputUpdate.RoleARNUpdate", "passedTo": "kinesisanalytics"}, + {"member": "ApplicationUpdate.InputUpdates[].KinesisStreamsInputUpdate.RoleARNUpdate", "passedTo": "kinesisanalytics"}, + {"member": "ApplicationUpdate.OutputUpdates[].KinesisFirehoseOutputUpdate.RoleARNUpdate", "passedTo": "kinesisanalytics"}, + {"member": "ApplicationUpdate.OutputUpdates[].KinesisStreamsOutputUpdate.RoleARNUpdate", "passedTo": "kinesisanalytics"}, + {"member": "ApplicationUpdate.OutputUpdates[].LambdaOutputUpdate.RoleARNUpdate", "passedTo": "kinesisanalytics"}, + {"member": "ApplicationUpdate.ReferenceDataSourceUpdates[].S3ReferenceDataSourceUpdate.ReferenceRoleARNUpdate", "passedTo": "kinesisanalytics"}, + {"member": "ServiceExecutionRoleUpdate", "passedTo": "kinesisanalytics"} + ]}, + "lambda:AddEventSource": {"passedTo": ["lambda"], "notRead": "botocore's model has no such operation"}, + "lambda:CreateCapacityProvider": {"passedTo": ["lambda"], "roles": [ + {"member": "PermissionsConfig.CapacityProviderOperatorRoleArn", "passedTo": "lambda"} + ]}, + "lambda:CreateFunction": {"passedTo": ["lambda"], "byHand": "the execution role"}, + "lambda:CreateMicrovmImage": {"passedTo": ["lambda"], "byHand": "the build role"}, + "lambda:CreateNetworkConnector": {"passedTo": ["lambda"], "byHand": "the operator role"}, + "lambda:CreateWebFunction": {"passedTo": ["lambda"], "byHand": "the execution role"}, + "lambda:CreateWebFunctionRevision": {"passedTo": ["lambda"], "byHand": "the execution role"}, + "lambda:RunMicrovm": {"passedTo": ["lambda"], "byHand": "the execution role"}, + "lambda:UpdateFunctionConfiguration": {"passedTo": ["lambda"], "byHand": "the execution role"}, + "lambda:UpdateMicrovmImage": {"passedTo": ["lambda"], "byHand": "the build role"}, + "lambda:UpdateNetworkConnector": {"passedTo": ["lambda"], "byHand": "the operator role"}, + "logs:CreateImportTask": {"passedTo": ["cloudtrail", "logs"], "notRead": "the reference passes the role to cloudtrail or logs and nothing says which"}, + "logs:CreateScheduledQuery": {"passedTo": ["logs"], "roles": [ + {"member": "destinationConfiguration.lookupTableConfiguration.roleArn", "passedTo": "logs"}, + {"member": "destinationConfiguration.s3Configuration.roleArn", "passedTo": "logs"}, + {"member": "executionRoleArn", "passedTo": "logs"} + ]}, + "logs:PutAccountPolicy": {"passedTo": ["logs"], "byHand": "the role a subscription filter policy's document names"}, + "logs:PutDestination": {"passedTo": ["logs"], "roles": [ + {"member": "roleArn", "passedTo": "logs"} + ]}, + "logs:PutSubscriptionFilter": {"passedTo": ["logs"], "roles": [ + {"member": "roleArn", "passedTo": "logs"} + ]}, + "logs:UpdateScheduledQuery": {"passedTo": ["logs"], "roles": [ + {"member": "destinationConfiguration.lookupTableConfiguration.roleArn", "passedTo": "logs"}, + {"member": "destinationConfiguration.s3Configuration.roleArn", "passedTo": "logs"}, + {"member": "executionRoleArn", "passedTo": "logs"} + ]}, + "pipes:CreatePipe": {"passedTo": ["pipes"], "byHand": "the pipe's role"}, + "pipes:UpdatePipe": {"passedTo": ["pipes"], "byHand": "the pipe's role"}, + "rds:AddRoleToDBCluster": {"passedTo": ["rds"], "byHand": "the role it adds"}, + "rds:AddRoleToDBInstance": {"passedTo": ["rds", "rds-preview"], "byHand": "the role it adds"}, + "rds:CreateBlueGreenDeployment": {"passedTo": ["rds"], "notRead": "no member of the request names a role"}, + "rds:CreateDBCluster": {"passedTo": ["rds", "rds-preview"], "byHand": "the directory, monitoring and associated roles"}, + "rds:CreateDBInstance": {"passedTo": ["rds", "rds-preview"], "byHand": "the directory and monitoring roles"}, + "rds:CreateDBInstanceReadReplica": {"passedTo": ["rds", "rds-preview"], "byHand": "the directory and monitoring roles"}, + "rds:CreateDBProxy": {"passedTo": ["rds"], "byHand": "the proxy's role"}, + "rds:ModifyDBCluster": {"passedTo": ["rds", "rds-preview"], "byHand": "the directory and monitoring roles"}, + "rds:ModifyDBInstance": {"passedTo": ["rds", "rds-preview"], "byHand": "the directory and monitoring roles"}, + "rds:ModifyDBProxy": {"passedTo": ["rds"], "byHand": "the proxy's role"}, + "rds:ModifyOptionGroup": {"passedTo": ["rds"], "byHand": "the role each option takes in its IAM_ROLE_ARN setting"}, + "rds:RemoveRoleFromDBCluster": {"passedTo": ["rds"], "byHand": "the role it removes"}, + "rds:RemoveRoleFromDBInstance": {"passedTo": ["rds"], "byHand": "the role it removes"}, + "rds:RestoreDBClusterFromS3": {"passedTo": ["rds", "rds-preview"], "roles": [ + {"member": "AssociatedRoles[DBClusterAssociatedRole].RoleArn", "passedTo": "rds"}, + {"member": "DomainIAMRoleName", "passedTo": "rds", "byName": true}, + {"member": "S3IngestionRoleArn", "passedTo": "rds"} + ]}, + "rds:RestoreDBClusterFromSnapshot": {"passedTo": ["rds"], "byHand": "the directory, monitoring and associated roles"}, + "rds:RestoreDBClusterToPointInTime": {"passedTo": ["rds"], "byHand": "the directory, monitoring and associated roles"}, + "rds:RestoreDBInstanceFromDBSnapshot": {"passedTo": ["rds", "rds-preview"], "byHand": "the directory role"}, + "rds:RestoreDBInstanceFromS3": {"passedTo": ["rds"], "roles": [ + {"member": "MonitoringRoleArn", "passedTo": "rds"}, + {"member": "S3IngestionRoleArn", "passedTo": "rds"} + ]}, + "rds:RestoreDBInstanceToPointInTime": {"passedTo": ["rds", "rds-preview"], "byHand": "the directory role"}, + "rds:StartExportTask": {"passedTo": ["rds"], "byHand": "the export role"}, + "redshift-serverless:CreateNamespace": {"passedTo": ["redshift-serverless"], "byHand": "the namespace's roles and its default"}, + "redshift-serverless:CreateScheduledAction": {"passedTo": ["redshift-serverless"], "byHand": "the scheduled action's role"}, + "redshift-serverless:UpdateLakehouseConfiguration": {"passedTo": ["redshift-serverless"], "notRead": "no member of the request names a role"}, + "redshift-serverless:UpdateNamespace": {"passedTo": ["redshift-serverless"], "byHand": "the namespace's roles and its default"}, + "redshift-serverless:UpdateScheduledAction": {"passedTo": ["redshift-serverless"], "byHand": "the scheduled action's role"}, + "redshift:CreateCluster": {"passedTo": ["redshift"], "byHand": "the roles it associates"}, + "redshift:CreateScheduledAction": {"passedTo": ["redshift"], "roles": [ + {"member": "IamRole", "passedTo": "redshift"} + ]}, + "redshift:ModifyClusterIamRoles": {"passedTo": ["redshift"], "byHand": "the roles it associates"}, + "redshift:ModifyLakehouseConfiguration": {"passedTo": ["redshift"], "notRead": "no member of the request names a role"}, + "redshift:ModifyScheduledAction": {"passedTo": ["redshift"], "roles": [ + {"member": "IamRole", "passedTo": "redshift"} + ]}, + "redshift:RestoreFromClusterSnapshot": {"passedTo": ["redshift"], "byHand": "the roles it associates"}, + "rekognition:CreateStreamProcessor": {"passedTo": ["rekognition"], "roles": [ + {"member": "RoleArn", "passedTo": "rekognition"} + ]}, + "rekognition:StartCelebrityRecognition": {"passedTo": ["rekognition"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "rekognition"} + ]}, + "rekognition:StartContentModeration": {"passedTo": ["rekognition"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "rekognition"} + ]}, + "rekognition:StartFaceDetection": {"passedTo": ["rekognition"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "rekognition"} + ]}, + "rekognition:StartFaceSearch": {"passedTo": ["rekognition"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "rekognition"} + ]}, + "rekognition:StartLabelDetection": {"passedTo": ["rekognition"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "rekognition"} + ]}, + "rekognition:StartSegmentDetection": {"passedTo": ["rekognition"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "rekognition"} + ]}, + "rekognition:StartTextDetection": {"passedTo": ["rekognition"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "rekognition"} + ]}, + "resource-groups:StartTagSyncTask": {"passedTo": ["resource-groups"], "roles": [ + {"member": "RoleArn", "passedTo": "resource-groups"} + ]}, + "s3:CreateAccessGrantsLocation": {"passedTo": [], "notRead": "the request body is XML, which PassedRoles does not read"}, + "s3:PutBucketReplication": {"passedTo": ["s3"], "notRead": "the request body is XML, which PassedRoles does not read"}, + "sagemaker:CreateAIBenchmarkJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateAIRecommendationJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateAlgorithm": {"passedTo": ["sagemaker"], "roles": [ + {"member": "ValidationSpecification.ValidationRole", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateAutoMLJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateAutoMLJobV2": {"passedTo": ["sagemaker"], "roles": [ + {"member": "AutoMLComputeConfig.EmrServerlessComputeConfig.ExecutionRoleARN", "passedTo": "sagemaker"}, + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateCluster": {"passedTo": ["sagemaker"], "roles": [ + {"member": "ClusterRole", "passedTo": "sagemaker"}, + {"member": "InstanceGroups[].ExecutionRole", "passedTo": "sagemaker"}, + {"member": "RestrictedInstanceGroups[].ExecutionRole", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateCompilationJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateDataQualityJobDefinition": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateDomain": {"passedTo": ["sagemaker"], "roles": [ + {"member": "DefaultSpaceSettings.ExecutionRole", "passedTo": "sagemaker"}, + {"member": "DefaultUserSettings.CanvasAppSettings.EmrServerlessSettings.ExecutionRoleArn", "passedTo": "sagemaker"}, + {"member": "DefaultUserSettings.CanvasAppSettings.GenerativeAiSettings.AmazonBedrockRoleArn", "passedTo": "sagemaker"}, + {"member": "DefaultUserSettings.CanvasAppSettings.TimeSeriesForecastingSettings.AmazonForecastRoleArn", "passedTo": "sagemaker"}, + {"member": "DefaultUserSettings.ExecutionRole", "passedTo": "sagemaker"}, + {"member": "DomainSettings.RStudioServerProDomainSettings.DomainExecutionRoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateEndpointConfig": {"passedTo": ["sagemaker"], "roles": [ + {"member": "ExecutionRoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateFeatureGroup": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateFlowDefinition": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateHyperParameterTuningJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "TrainingJobDefinition.RoleArn", "passedTo": "sagemaker"}, + {"member": "TrainingJobDefinitions[].RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateImage": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateInferenceExperiment": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateInferenceRecommendationsJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateJob": {"passedTo": ["job.sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "job.sagemaker"} + ]}, + "sagemaker:CreateLabelingJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateMlflowApp": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateMlflowTrackingServer": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateModel": {"passedTo": ["sagemaker"], "roles": [ + {"member": "ExecutionRoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateModelBiasJobDefinition": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateModelExplainabilityJobDefinition": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateModelPackage": {"passedTo": ["sagemaker"], "roles": [ + {"member": "ValidationSpecification.ValidationRole", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateModelQualityJobDefinition": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateMonitoringSchedule": {"passedTo": ["sagemaker"], "roles": [ + {"member": "MonitoringScheduleConfig.MonitoringJobDefinition.RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateNotebookInstance": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateOptimizationJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreatePartnerApp": {"passedTo": ["sagemaker"], "roles": [ + {"member": "ExecutionRoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreatePipeline": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateProcessingJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateProject": {"passedTo": ["sagemaker"], "roles": [ + {"member": "TemplateProviders[].CfnTemplateProvider.RoleARN", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateTrainingJob": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:CreateTrainingSession": {"passedTo": ["sagemaker", "training-session.sagemaker"], "notRead": "the reference passes the role to sagemaker or training-session.sagemaker and nothing says which"}, + "sagemaker:CreateTransformJob": {"passedTo": ["sagemaker"], "notRead": "no member of the request names a role"}, + "sagemaker:CreateUserProfile": {"passedTo": ["sagemaker"], "roles": [ + {"member": "UserSettings.CanvasAppSettings.EmrServerlessSettings.ExecutionRoleArn", "passedTo": "sagemaker"}, + {"member": "UserSettings.CanvasAppSettings.GenerativeAiSettings.AmazonBedrockRoleArn", "passedTo": "sagemaker"}, + {"member": "UserSettings.CanvasAppSettings.TimeSeriesForecastingSettings.AmazonForecastRoleArn", "passedTo": "sagemaker"}, + {"member": "UserSettings.ExecutionRole", "passedTo": "sagemaker"} + ]}, + "sagemaker:ImportHubContent": {"passedTo": ["sagemaker"], "notRead": "no member of the request names a role"}, + "sagemaker:RenderUiTemplate": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:UpdateCluster": {"passedTo": ["sagemaker"], "roles": [ + {"member": "ClusterRole", "passedTo": "sagemaker"}, + {"member": "InstanceGroups[].ExecutionRole", "passedTo": "sagemaker"}, + {"member": "RestrictedInstanceGroups[].ExecutionRole", "passedTo": "sagemaker"} + ]}, + "sagemaker:UpdateDomain": {"passedTo": ["sagemaker"], "roles": [ + {"member": "DefaultSpaceSettings.ExecutionRole", "passedTo": "sagemaker"}, + {"member": "DefaultUserSettings.CanvasAppSettings.EmrServerlessSettings.ExecutionRoleArn", "passedTo": "sagemaker"}, + {"member": "DefaultUserSettings.CanvasAppSettings.GenerativeAiSettings.AmazonBedrockRoleArn", "passedTo": "sagemaker"}, + {"member": "DefaultUserSettings.CanvasAppSettings.TimeSeriesForecastingSettings.AmazonForecastRoleArn", "passedTo": "sagemaker"}, + {"member": "DefaultUserSettings.ExecutionRole", "passedTo": "sagemaker"}, + {"member": "DomainSettingsForUpdate.RStudioServerProDomainSettingsForUpdate.DomainExecutionRoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:UpdateImage": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:UpdateMonitoringSchedule": {"passedTo": ["sagemaker"], "roles": [ + {"member": "MonitoringScheduleConfig.MonitoringJobDefinition.RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:UpdateNotebookInstance": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:UpdatePipeline": {"passedTo": ["sagemaker"], "roles": [ + {"member": "RoleArn", "passedTo": "sagemaker"} + ]}, + "sagemaker:UpdateUserProfile": {"passedTo": ["sagemaker"], "roles": [ + {"member": "UserSettings.CanvasAppSettings.EmrServerlessSettings.ExecutionRoleArn", "passedTo": "sagemaker"}, + {"member": "UserSettings.CanvasAppSettings.GenerativeAiSettings.AmazonBedrockRoleArn", "passedTo": "sagemaker"}, + {"member": "UserSettings.CanvasAppSettings.TimeSeriesForecastingSettings.AmazonForecastRoleArn", "passedTo": "sagemaker"}, + {"member": "UserSettings.ExecutionRole", "passedTo": "sagemaker"} + ]}, + "scheduler:CreateSchedule": {"passedTo": ["scheduler"], "byHand": "the target's role"}, + "scheduler:UpdateSchedule": {"passedTo": ["scheduler"], "byHand": "the target's role"}, + "secretsmanager:RotateSecret": {"passedTo": ["secretsmanager"], "roles": [ + {"member": "ExternalSecretRotationRoleArn", "passedTo": "secretsmanager"} + ]}, + "servicecatalog:CreateConstraint": {"passedTo": ["servicecatalog"], "byHand": "a launch constraint's role, from its parameters document"}, + "servicecatalog:CreateServiceAction": {"passedTo": ["servicecatalog"], "roles": [ + {"member": "Definition{AssumeRole}", "passedTo": "servicecatalog"} + ]}, + "servicecatalog:UpdateConstraint": {"passedTo": ["servicecatalog"], "byHand": "a launch constraint's role, by the type the constraint holds"}, + "servicecatalog:UpdateProvisionedProductProperties": {"passedTo": ["servicecatalog"], "roles": [ + {"member": "ProvisionedProductProperties{LAUNCH_ROLE}", "passedTo": "servicecatalog"} + ]}, + "servicecatalog:UpdateServiceAction": {"passedTo": ["servicecatalog"], "roles": [ + {"member": "Definition{AssumeRole}", "passedTo": "servicecatalog"} + ]}, + "ses:CreateConfigurationSetEventDestination": {"passedTo": ["ses"], "roles": [ + {"member": "EventDestination.KinesisFirehoseDestination.IAMRoleARN", "passedTo": "ses"}, + {"member": "EventDestination.KinesisFirehoseDestination.IamRoleArn", "passedTo": "ses"} + ]}, + "ses:CreateReceiptRule": {"passedTo": ["ses"], "roles": [ + {"member": "Rule.Actions[].ConnectAction.IAMRoleARN", "passedTo": "ses"}, + {"member": "Rule.Actions[].S3Action.IamRoleArn", "passedTo": "ses"} + ]}, + "ses:CreateRuleSet": {"passedTo": ["ses"], "roles": [ + {"member": "Rules[].Actions[].Bounce.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].DeliverToMailbox.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].DeliverToQBusiness.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].InvokeLambda.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].PublishToSns.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].Send.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].WriteToS3.RoleArn", "passedTo": "ses"} + ]}, + "ses:UpdateConfigurationSetEventDestination": {"passedTo": ["ses"], "roles": [ + {"member": "EventDestination.KinesisFirehoseDestination.IAMRoleARN", "passedTo": "ses"}, + {"member": "EventDestination.KinesisFirehoseDestination.IamRoleArn", "passedTo": "ses"} + ]}, + "ses:UpdateReceiptRule": {"passedTo": ["ses"], "roles": [ + {"member": "Rule.Actions[].ConnectAction.IAMRoleARN", "passedTo": "ses"}, + {"member": "Rule.Actions[].S3Action.IamRoleArn", "passedTo": "ses"} + ]}, + "ses:UpdateRuleSet": {"passedTo": ["ses"], "roles": [ + {"member": "Rules[].Actions[].Bounce.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].DeliverToMailbox.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].DeliverToQBusiness.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].InvokeLambda.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].PublishToSns.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].Send.RoleArn", "passedTo": "ses"}, + {"member": "Rules[].Actions[].WriteToS3.RoleArn", "passedTo": "ses"} + ]}, + "sns:CreatePlatformApplication": {"passedTo": ["sns"], "byHand": "the delivery status roles among its attributes"}, + "sns:CreateTopic": {"passedTo": ["sns"], "byHand": "the delivery status roles among its attributes"}, + "sns:SetPlatformApplicationAttributes": {"passedTo": ["sns"], "byHand": "the delivery status roles among its attributes"}, + "sns:SetSMSAttributes": {"passedTo": ["sns"], "byHand": "the delivery status role among its attributes"}, + "sns:SetSubscriptionAttributes": {"passedTo": ["sns"], "byHand": "the subscription role, when it is the attribute set"}, + "sns:SetTopicAttributes": {"passedTo": ["sns"], "byHand": "a delivery status role, when it is the attribute set"}, + "sns:Subscribe": {"passedTo": ["sns"], "byHand": "the subscription role among its attributes"}, + "ssm:CreateActivation": {"passedTo": ["ssm"], "roles": [ + {"member": "IamRole", "passedTo": "ssm", "byName": true} + ]}, + "ssm:CreateAssociation": {"passedTo": ["ssm"], "roles": [ + {"member": "AssociationDispatchAssumeRole", "passedTo": "ssm"} + ]}, + "ssm:CreateAssociationBatch": {"passedTo": ["ssm"], "roles": [ + {"member": "AssociationDispatchAssumeRole", "passedTo": "ssm"} + ]}, + "ssm:CreateCloudConnector": {"passedTo": ["ssm"], "roles": [ + {"member": "RoleArn", "passedTo": "ssm"} + ]}, + "ssm:CreateDocument": {"passedTo": ["justintimeaccess.ssm", "ssm"], "notRead": "no member of the request names a role"}, + "ssm:DescribeAutomationStepExecutions": {"passedTo": ["ssm"], "notRead": "no member of the request names a role"}, + "ssm:GetAutomationExecution": {"passedTo": ["ssm"], "notRead": "no member of the request names a role"}, + "ssm:RegisterTaskWithMaintenanceWindow": {"passedTo": ["ssm"], "roles": [ + {"member": "ServiceRoleArn", "passedTo": "ssm"}, + {"member": "TaskInvocationParameters.RunCommand.ServiceRoleArn", "passedTo": "ssm"} + ]}, + "ssm:SendCommand": {"passedTo": ["ssm"], "roles": [ + {"member": "ServiceRoleArn", "passedTo": "ssm"} + ]}, + "ssm:StartAutomationExecution": {"passedTo": ["ssm"], "notRead": "the role is a parameter of the runbook it runs, not a member of the request"}, + "ssm:StartChangeRequestExecution": {"passedTo": ["ssm"], "notRead": "the role is a parameter of the runbook it runs, not a member of the request"}, + "ssm:UpdateAssociation": {"passedTo": ["ssm"], "roles": [ + {"member": "AssociationDispatchAssumeRole", "passedTo": "ssm"} + ]}, + "ssm:UpdateDocument": {"passedTo": ["justintimeaccess.ssm", "ssm"], "notRead": "no member of the request names a role"}, + "ssm:UpdateMaintenanceWindowTask": {"passedTo": ["ssm"], "roles": [ + {"member": "ServiceRoleArn", "passedTo": "ssm"}, + {"member": "TaskInvocationParameters.RunCommand.ServiceRoleArn", "passedTo": "ssm"} + ]}, + "ssm:UpdateManagedInstanceRole": {"passedTo": ["ssm"], "roles": [ + {"member": "IamRole", "passedTo": "ssm", "byName": true} + ]}, + "ssm:UpdateServiceSetting": {"passedTo": ["ssm"], "notRead": "a role is only ever a setting's value, which the request names by SettingId"}, + "states:CreateStateMachine": {"passedTo": ["states"], "byHand": "the state machine's role"}, + "states:TestState": {"passedTo": ["states"], "roles": [ + {"member": "roleArn", "passedTo": "states"} + ]}, + "states:UpdateStateMachine": {"passedTo": ["states"], "byHand": "the state machine's role"}, + "swf:RegisterWorkflowType": {"passedTo": ["swf"], "roles": [ + {"member": "defaultLambdaRole", "passedTo": "swf"} + ]}, + "swf:RespondDecisionTaskCompleted": {"passedTo": ["swf"], "byHand": "the Lambda role of each decision that starts an execution, read from the attributes its decisionType names"}, + "swf:StartWorkflowExecution": {"passedTo": ["swf"], "roles": [ + {"member": "lambdaRole", "passedTo": "swf"} + ]}, + "textract:StartDocumentAnalysis": {"passedTo": ["textract"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "textract"} + ]}, + "textract:StartDocumentTextDetection": {"passedTo": ["textract"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "textract"} + ]}, + "textract:StartExpenseAnalysis": {"passedTo": ["textract"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "textract"} + ]}, + "textract:StartLendingAnalysis": {"passedTo": ["textract"], "roles": [ + {"member": "NotificationChannel.RoleArn", "passedTo": "textract"} + ]}, + "transcribe:CreateLanguageModel": {"passedTo": ["transcribe"], "roles": [ + {"member": "InputDataConfig.DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transcribe:CreateVocabulary": {"passedTo": ["transcribe"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transcribe:CreateVocabularyFilter": {"passedTo": ["transcribe"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transcribe:StartCallAnalyticsJob": {"passedTo": ["transcribe"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transcribe:StartMedicalScribeJob": {"passedTo": ["transcribe"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transcribe:StartTranscriptionJob": {"passedTo": ["transcribe"], "roles": [ + {"member": "JobExecutionSettings.DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transcribe:UpdateLanguageModel": {"passedTo": ["transcribe"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transcribe:UpdateVocabulary": {"passedTo": ["transcribe"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transcribe:UpdateVocabularyFilter": {"passedTo": ["transcribe"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "transcribe"} + ]}, + "transfer:CreateAccess": {"passedTo": ["transfer"], "roles": [ + {"member": "Role", "passedTo": "transfer"} + ]}, + "transfer:CreateAgreement": {"passedTo": ["transfer"], "roles": [ + {"member": "AccessRole", "passedTo": "transfer"} + ]}, + "transfer:CreateConnector": {"passedTo": ["transfer"], "roles": [ + {"member": "AccessRole", "passedTo": "transfer"}, + {"member": "LoggingRole", "passedTo": "transfer"} + ]}, + "transfer:CreateServer": {"passedTo": ["transfer"], "roles": [ + {"member": "IdentityProviderDetails.InvocationRole", "passedTo": "transfer"}, + {"member": "LoggingRole", "passedTo": "transfer"}, + {"member": "WorkflowDetails.OnPartialUpload[].ExecutionRole", "passedTo": "transfer"}, + {"member": "WorkflowDetails.OnUpload[].ExecutionRole", "passedTo": "transfer"} + ]}, + "transfer:CreateUser": {"passedTo": ["transfer"], "roles": [ + {"member": "Role", "passedTo": "transfer"} + ]}, + "transfer:CreateWebApp": {"passedTo": ["transfer"], "roles": [ + {"member": "IdentityProviderDetails.IdentityCenterConfig.Role", "passedTo": "transfer"} + ]}, + "transfer:UpdateAccess": {"passedTo": ["transfer"], "roles": [ + {"member": "Role", "passedTo": "transfer"} + ]}, + "transfer:UpdateAgreement": {"passedTo": ["transfer"], "roles": [ + {"member": "AccessRole", "passedTo": "transfer"} + ]}, + "transfer:UpdateConnector": {"passedTo": ["transfer"], "roles": [ + {"member": "AccessRole", "passedTo": "transfer"}, + {"member": "LoggingRole", "passedTo": "transfer"} + ]}, + "transfer:UpdateServer": {"passedTo": ["transfer"], "roles": [ + {"member": "IdentityProviderDetails.InvocationRole", "passedTo": "transfer"}, + {"member": "LoggingRole", "passedTo": "transfer"}, + {"member": "WorkflowDetails.OnPartialUpload[].ExecutionRole", "passedTo": "transfer"}, + {"member": "WorkflowDetails.OnUpload[].ExecutionRole", "passedTo": "transfer"} + ]}, + "transfer:UpdateUser": {"passedTo": ["transfer"], "roles": [ + {"member": "Role", "passedTo": "transfer"} + ]}, + "transfer:UpdateWebApp": {"passedTo": ["transfer"], "roles": [ + {"member": "IdentityProviderDetails.IdentityCenterConfig.Role", "passedTo": "transfer"} + ]}, + "translate:StartTextTranslationJob": {"passedTo": ["translate"], "roles": [ + {"member": "DataAccessRoleArn", "passedTo": "translate"} + ]} + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PassedRoleMembersTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PassedRoleMembersTest.java new file mode 100644 index 0000000000..c1367b8358 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/PassedRoleMembersTest.java @@ -0,0 +1,255 @@ +package io.github.hectorvent.floci.core.common; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import io.github.hectorvent.floci.core.common.PassedRoleMembers.Into; +import io.github.hectorvent.floci.core.common.PassedRoleMembers.Member; +import io.github.hectorvent.floci.core.common.PassedRoleMembers.Step; +import io.github.hectorvent.floci.core.common.PassedRoles.PassedRole; +import jakarta.ws.rs.container.ContainerRequestContext; +import jakarta.ws.rs.core.MediaType; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; + +import java.io.ByteArrayInputStream; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * The vendored table of where each operation's request names the roles it passes, and that + * {@link PassedRoles} reads every member it gives, from a JSON body and from Query form parameters. + */ +class PassedRoleMembersTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ROLE = "arn:aws:iam::111122223333:role/passed"; + private static final String NAMED = "named-role"; + private static final String HELD = "arn:aws:iam::111122223333:role/held/named-role"; + + /** IAM holds {@code named-role} under the path {@code /held/}; nothing else is there to look up. */ + private static final PassedRoles.Lookups LOOKUPS = new PassedRoles.Lookups() { + @Override + public List instanceProfileRoleArns(String profileName, String profileArn) { + return List.of(); + } + + @Override + public List taskDefinitionRoles(String reference) { + return List.of(); + } + + @Override + public Optional stackSetPermissionModel(String stackSetName) { + return Optional.empty(); + } + + @Override + public Optional launchTemplateInstanceProfile(String templateId, String templateName, String version) { + return Optional.empty(); + } + + @Override + public Optional launchConfigurationInstanceProfile(String instanceId) { + return Optional.empty(); + } + + @Override + public Optional instanceRefreshInstanceProfile(String groupName, String templateId, + String templateName, String version) { + return Optional.empty(); + } + + @Override + public String roleArn(String roleName) { + return "arn:aws:iam::111122223333:role/" + roleName; + } + + @Override + public Optional heldRoleArn(String roleName) { + return NAMED.equals(roleName) ? Optional.of(HELD) : Optional.empty(); + } + + @Override + public Optional serviceCatalogConstraintType(String constraintId) { + return Optional.empty(); + } + }; + + @Test + void theTableReadsTheOperationsOfEveryNamespaceItCoversOnce() { + PassedRoleMembers.Table table = PassedRoleMembers.table(); + assertFalse(table.members().isEmpty()); + for (String operation : table.members().keySet()) { + assertFalse(table.byHand().contains(operation) || table.notRead().contains(operation), operation); + assertTrue(table.namespaces().contains(operation.substring(0, operation.indexOf(':'))), operation); + } + assertFalse(table.byHand().stream().anyMatch(table.notRead()::contains)); + assertTrue(table.otherNamespaces().stream().noneMatch(table.namespaces()::contains)); + assertTrue(table.notCovered().stream().noneMatch(table.namespaces()::contains)); + } + + @Test + void aMemberPathIsReadAsItsSteps() { + Member list = member("Rule.Actions[].S3Action.IamRoleArn", "ses"); + assertEquals(List.of(new Step("Rule", Into.NONE, null), new Step("Actions", Into.LIST, ""), + new Step("S3Action", Into.NONE, null), new Step("IamRoleArn", Into.NONE, null)), list.steps()); + assertTrue(list.queryKeys().matcher("Rule.Actions.member.2.S3Action.IamRoleArn").matches()); + assertTrue(list.queryKeys().matcher("Rule.Actions.2.S3Action.IamRoleArn").matches()); + assertFalse(list.queryKeys().matcher("Rule.Actions.S3Action.IamRoleArn").matches()); + + Member named = member("AssociatedRoles[DBClusterAssociatedRole].RoleArn", "rds"); + assertTrue(named.queryKeys().matcher("AssociatedRoles.DBClusterAssociatedRole.1.RoleArn").matches()); + assertTrue(named.queryKeys().matcher("AssociatedRoles.member.1.RoleArn").matches()); + assertFalse(named.queryKeys().matcher("AssociatedRoles.Other.1.RoleArn").matches()); + + assertTrue(member("Roles{}", null).queryKeys().matcher("Roles.entry.3.value").matches()); + // One key of a map cannot be told apart in a form, whose keys and values are separate parameters. + Member key = member("Definition{AssumeRole}", "servicecatalog"); + assertEquals(new Step("Definition", Into.KEY, "AssumeRole"), key.steps().get(0)); + assertNull(key.queryKeys()); + } + + @Test + void aMalformedTableFailsToLoad() { + assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{}}")); + assertThrows(IllegalStateException.class, () -> parse("{\"operations\":{\"a:B\":{\"passedTo\":[]}}}")); + assertThrows(IllegalStateException.class, () -> parse( + "{\"operations\":{\"a:B\":{\"passedTo\":[],\"roles\":[{\"member\":\"A..B\"}]}}}")); + } + + /** + * Every operation the table says is read by hand has a case in {@link PassedRoles#byHand}, and no + * other operation of the table does, so neither shadows the other. + */ + @Test + void exactlyTheOperationsReadByHandHaveACaseOfTheirOwn() { + PassedRoleMembers.Table table = PassedRoleMembers.table(); + for (String operation : table.byHand()) { + assertNotNull(PassedRoles.byHand(operation, json("{}"), LOOKUPS), operation + " has no case of its own"); + } + Stream.concat(table.members().keySet().stream(), table.notRead().stream()).forEach(operation -> + assertNull(PassedRoles.byHand(operation, json("{}"), LOOKUPS), + operation + " is read by hand; say so in the generator's BY_HAND")); + } + + @TestFactory + Stream everyMemberOfTheTableIsReadFromAJsonBody() { + return PassedRoleMembers.table().members().entrySet().stream() + .flatMap(operation -> operation.getValue().stream().map(member -> DynamicTest.dynamicTest( + operation.getKey() + " " + member.path(), () -> assertEquals(List.of(expected(member)), + PassedRoles.of(operation.getKey(), json(body(member).toString()), LOOKUPS))))); + } + + @TestFactory + Stream everyMemberOfTheTableAQueryRequestCanCarryIsReadFromItsForm() { + return PassedRoleMembers.table().members().entrySet().stream() + .flatMap(operation -> operation.getValue().stream() + .filter(member -> member.queryKeys() != null) + .map(member -> DynamicTest.dynamicTest(operation.getKey() + " " + member.path(), + () -> assertEquals(List.of(expected(member)), + PassedRoles.of(operation.getKey(), form(formKey(member) + "=" + + URLEncoder.encode(value(member), StandardCharsets.UTF_8)), LOOKUPS))))); + } + + @TestFactory + Stream aMemberHoldingSomethingOtherThanARolePassesNothing() { + return PassedRoleMembers.table().members().entrySet().stream() + .flatMap(operation -> operation.getValue().stream().map(member -> DynamicTest.dynamicTest( + operation.getKey() + " " + member.path(), () -> assertEquals(List.of(), + PassedRoles.of(operation.getKey(), + json(body(member, "arn:aws:s3:::bucket").toString()), LOOKUPS))))); + } + + /** The role a request names at the member: by name where the member takes one, else by ARN. */ + private static String value(Member member) { + return member.byName() ? NAMED : ROLE; + } + + private static PassedRole expected(Member member) { + return new PassedRole(member.byName() ? HELD : ROLE, + member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo())); + } + + private static JsonNode body(Member member) { + return body(member, value(member)); + } + + private static JsonNode body(Member member, String value) { + JsonNode node = TextNode.valueOf(value); + List steps = member.steps(); + for (int i = steps.size() - 1; i >= 0; i--) { + Step step = steps.get(i); + JsonNode inner = switch (step.into()) { + case NONE -> node; + case LIST -> MAPPER.createArrayNode().add(node); + case MAP -> MAPPER.createObjectNode().set("any", node); + case KEY -> MAPPER.createObjectNode().set(step.key(), node); + }; + ObjectNode outer = MAPPER.createObjectNode(); + outer.set(step.name(), inner); + node = outer; + } + return node; + } + + /** The member's form key, a list's first element in the generic form and a map's first value. */ + private static String formKey(Member member) { + List parts = new ArrayList<>(); + for (Step step : member.steps()) { + parts.add(step.name()); + if (step.into() == Into.LIST) { + parts.add("member.1"); + } else if (step.into() == Into.MAP) { + parts.add("entry.1.value"); + } + } + return String.join(".", parts); + } + + private static Member member(String path, String passedTo) { + String role = passedTo == null ? "{\"member\":\"" + path + "\"}" + : "{\"member\":\"" + path + "\",\"passedTo\":\"" + passedTo + "\"}"; + try { + return parse("{\"operations\":{\"a:B\":{\"passedTo\":[],\"roles\":[" + role + "]}}}") + .members().get("a:B").get(0); + } catch (Exception e) { + throw new AssertionError(e); + } + } + + private static PassedRoleMembers.Table parse(String document) throws Exception { + return PassedRoleMembers.parse(new ByteArrayInputStream(document.getBytes(StandardCharsets.UTF_8))); + } + + private static ContainerRequestContext json(String body) { + return request("application/x-amz-json-1.1", body); + } + + private static ContainerRequestContext form(String body) { + return request("application/x-www-form-urlencoded", body); + } + + private static ContainerRequestContext request(String mediaType, String body) { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + ContainerRequestContext request = mock(ContainerRequestContext.class); + when(request.getMediaType()).thenReturn(MediaType.valueOf(mediaType)); + when(request.getEntityStream()).thenAnswer(invocation -> new ByteArrayInputStream(bytes)); + return request; + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PassedRoleNamespacesIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PassedRoleNamespacesIntegrationTest.java new file mode 100644 index 0000000000..cc2e545f7b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/PassedRoleNamespacesIntegrationTest.java @@ -0,0 +1,35 @@ +package io.github.hectorvent.floci.core.common; + +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.util.Set; +import java.util.TreeSet; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Every IAM namespace Floci serves whose operations the Service Reference lists with {@code iam:PassRole} is + * one the vendored table of passed roles reads, or one it names as not read yet, so a service Floci adds is + * not left passing roles unchecked. + */ +@QuarkusTest +class PassedRoleNamespacesIntegrationTest { + + @Inject + ResolvedServiceCatalog catalog; + + @Test + void everyNamespaceFlociServesThatPassesARoleIsReadOrNamedAsNotReadYet() { + Set served = new TreeSet<>(); + for (ServiceDescriptor descriptor : catalog.all()) { + for (String scope : descriptor.credentialScopes()) { + served.add(catalog.canonicalCredentialScope(scope)); + } + } + Set unread = new TreeSet<>(served); + unread.retainAll(PassedRoleMembers.table().otherNamespaces()); + assertEquals(Set.of(), unread, "add these to NAMESPACES or NOT_COVERED in tools/aws/regen_iam_passed_roles.py"); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java index 7869300c59..572cabd239 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/PassedRolesTest.java @@ -43,7 +43,8 @@ class PassedRolesTest { * instance {@code i-arn} runs with that other profile, and the group {@code g} launches from * {@code lt-web} once a refresh names only a version, or from {@code arn-template} at the group's * version 2 once a refresh names that template alone. IAM holds the role {@code app-role} under the - * path {@code /app/}. + * path {@code /app/}. Service Catalog holds a launch constraint {@code cons-launch} and a notification + * constraint {@code cons-notify}. */ private static final PassedRoles.Lookups LOOKUPS = new PassedRoles.Lookups() { @Override @@ -103,6 +104,16 @@ class PassedRolesTest { public Optional heldRoleArn(String roleName) { return "app-role".equals(roleName) ? Optional.of(ROLES + "app/app-role") : Optional.empty(); } + + @Override + public Optional serviceCatalogConstraintType(String constraintId) { + return switch (constraintId) { + case "cons-launch" -> Optional.of("LAUNCH"); + case "cons-lowercase" -> Optional.of("launch"); + case "cons-notify" -> Optional.of("NOTIFICATION"); + default -> Optional.empty(); + }; + } }; @Test @@ -495,6 +506,197 @@ class PassedRolesTest { } } + @Test + void ssmPassesAnAssociationsDispatchRoleAndACommandsNotificationRoleToSsm() { + String ssm = "ssm.amazonaws.com"; + // An Automation runbook's assume role is a parameter the runbook names, and a target location's + // execution role is one in each target account: neither is read. + String association = "{\"Name\":\"doc\",\"AssociationDispatchAssumeRole\":\"" + ROLES + "dispatch\"," + + "\"Parameters\":{\"AutomationAssumeRole\":[\"" + ROLES + "automation\"]}," + + "\"TargetLocations\":[{\"ExecutionRoleName\":\"execution\"}]}"; + for (String action : new String[] {"ssm:CreateAssociation", "ssm:UpdateAssociation"}) { + assertEquals(List.of(passed("dispatch", ssm)), PassedRoles.of(action, json(association), LOOKUPS), action); + assertEquals(List.of(), PassedRoles.of(action, json("{\"Name\":\"doc\"}"), LOOKUPS), action); + } + assertEquals(List.of(passed("notifications", ssm)), PassedRoles.of("ssm:SendCommand", + json("{\"DocumentName\":\"AWS-RunShellScript\",\"ServiceRoleArn\":\"" + ROLES + "notifications\"," + + "\"NotificationConfig\":{\"NotificationArn\":\"arn:aws:sns:us-east-1:111122223333:t\"}}"), + LOOKUPS)); + // A document's request names no role, and a role is only ever a setting's value. + assertEquals(List.of(), PassedRoles.of("ssm:CreateDocument", + json("{\"Name\":\"d\",\"Content\":\"{\\\"assumeRole\\\":\\\"" + ROLES + "runbook\\\"}\"}"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("ssm:UpdateServiceSetting", + json("{\"SettingId\":\"/ssm/managed-instance/default-ec2-instance-management-role\"," + + "\"SettingValue\":\"service-role/AWSSystemsManagerDefaultEC2InstanceManagementRole\"}"), + LOOKUPS)); + } + + @Test + void serviceCatalogPassesTheLaunchRoleAConstraintAnActionOrAProvisionedProductNames() { + String catalog = "servicecatalog.amazonaws.com"; + assertEquals(List.of(passed("launch", catalog)), PassedRoles.of("servicecatalog:CreateConstraint", + json(constraint("LAUNCH", "{\\\"RoleArn\\\":\\\"" + ROLES + "launch\\\"}")), LOOKUPS)); + // A local role name carries no path: the ARN IAM holds the role under, or else the one the name gives. + assertEquals(List.of(new PassedRole(ROLES + "app/app-role", catalog)), PassedRoles.of( + "servicecatalog:CreateConstraint", + json(constraint("LAUNCH", "{\\\"LocalRoleName\\\":\\\"app-role\\\"}")), LOOKUPS)); + assertEquals(List.of(passed("gone", catalog)), PassedRoles.of("servicecatalog:CreateConstraint", + json(constraint("LAUNCH", "{\\\"LocalRoleName\\\":\\\"gone\\\"}")), LOOKUPS)); + // Only a launch constraint names a launch role, and only in a JSON document. + assertEquals(List.of(), PassedRoles.of("servicecatalog:CreateConstraint", + json(constraint("NOTIFICATION", "{\\\"RoleArn\\\":\\\"" + ROLES + "launch\\\"}")), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("servicecatalog:CreateConstraint", + json(constraint("LAUNCH", "RoleArn=" + ROLES + "launch")), LOOKUPS)); + // Floci keeps a constraint's type as given, so a launch constraint is one in any case. + assertEquals(List.of(passed("launch", catalog)), PassedRoles.of("servicecatalog:CreateConstraint", + json(constraint("launch", "{\\\"RoleArn\\\":\\\"" + ROLES + "launch\\\"}")), LOOKUPS)); + + // An update names no type, so it goes by the constraint's own. + String parameters = "\"Parameters\":\"{\\\"RoleArn\\\":\\\"" + ROLES + "launch\\\"}\""; + assertEquals(List.of(passed("launch", catalog)), PassedRoles.of("servicecatalog:UpdateConstraint", + json("{\"Id\":\"cons-launch\"," + parameters + "}"), LOOKUPS)); + assertEquals(List.of(passed("launch", catalog)), PassedRoles.of("servicecatalog:UpdateConstraint", + json("{\"Id\":\"cons-lowercase\"," + parameters + "}"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("servicecatalog:UpdateConstraint", + json("{\"Id\":\"cons-notify\"," + parameters + "}"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("servicecatalog:UpdateConstraint", + json("{\"Id\":\"cons-missing\"," + parameters + "}"), LOOKUPS)); + + for (String action : new String[] {"servicecatalog:CreateServiceAction", "servicecatalog:UpdateServiceAction"}) { + assertEquals(List.of(passed("action", catalog)), PassedRoles.of(action, + json("{\"Definition\":{\"Name\":\"AWS-RestartEC2Instance\",\"AssumeRole\":\"" + ROLES + + "action\"}}"), LOOKUPS), action); + // LAUNCH_ROLE reuses the provisioned product's launch role, which passes nothing new. + assertEquals(List.of(), PassedRoles.of(action, + json("{\"Definition\":{\"AssumeRole\":\"LAUNCH_ROLE\"}}"), LOOKUPS), action); + } + assertEquals(List.of(passed("launch", catalog)), PassedRoles.of( + "servicecatalog:UpdateProvisionedProductProperties", + json("{\"ProvisionedProductProperties\":{\"LAUNCH_ROLE\":\"" + ROLES + "launch\"," + + "\"OWNER\":\"" + ROLES + "owner\"}}"), LOOKUPS)); + } + + @Test + void secretsManagerBudgetsAndSwfPassTheRolesTheirRequestsName() { + assertEquals(List.of(passed("rotation", "secretsmanager.amazonaws.com")), PassedRoles.of( + "secretsmanager:RotateSecret", json("{\"SecretId\":\"s\",\"ExternalSecretRotationRoleArn\":\"" + + ROLES + "rotation\",\"RotationLambdaARN\":\"arn:aws:lambda:us-east-1:111122223333:" + + "function:rotate\"}"), LOOKUPS)); + // The roles an IAM budget action attaches its policy to are what it acts on, not roles it passes. + String budgetAction = "{\"ExecutionRoleArn\":\"" + ROLES + "execution\",\"Definition\":{\"IamActionDefinition\":" + + "{\"PolicyArn\":\"arn:aws:iam::111122223333:policy/deny\",\"Roles\":[\"" + ROLES + "target\"]}}}"; + for (String action : new String[] {"budgets:CreateBudgetAction", "budgets:UpdateBudgetAction"}) { + assertEquals(List.of(passed("execution", "budgets.amazonaws.com")), + PassedRoles.of(action, json(budgetAction), LOOKUPS), action); + } + + String swf = "swf.amazonaws.com"; + assertEquals(List.of(passed("default", swf)), PassedRoles.of("swf:RegisterWorkflowType", + json("{\"name\":\"w\",\"defaultLambdaRole\":\"" + ROLES + "default\"}"), LOOKUPS)); + assertEquals(List.of(passed("execution", swf)), PassedRoles.of("swf:StartWorkflowExecution", + json("{\"workflowId\":\"w\",\"lambdaRole\":\"" + ROLES + "execution\"}"), LOOKUPS)); + // Each decision is read from the attributes its type names, as the SWF handler reads it. + assertEquals(List.of(passed("next", swf), passed("child", swf)), PassedRoles.of( + "swf:RespondDecisionTaskCompleted", json("{\"taskToken\":\"t\",\"decisions\":[" + + "{\"decisionType\":\"ContinueAsNewWorkflowExecution\"," + + "\"continueAsNewWorkflowExecutionDecisionAttributes\":{\"lambdaRole\":\"" + ROLES + "next\"}}," + + "{\"decisionType\":\"ScheduleLambdaFunction\"," + + "\"scheduleLambdaFunctionDecisionAttributes\":{\"id\":\"f\",\"name\":\"f\"}}," + + "{\"decisionType\":\"StartChildWorkflowExecution\"," + + "\"startChildWorkflowExecutionDecisionAttributes\":{\"lambdaRole\":\"" + ROLES + "child\"}," + + "\"continueAsNewWorkflowExecutionDecisionAttributes\":{\"lambdaRole\":\"" + ROLES + "unread\"}}]}"), + LOOKUPS)); + } + + @Test + void snsPassesTheRolesItsAttributesNameToSns() { + String sns = "sns.amazonaws.com"; + // Read as the Query handler reads the map: up to the first entry with no key, a key's last value. + assertEquals(List.of(passed("lambda-success", sns), passed("sqs-failure", sns)), PassedRoles.of("sns:CreateTopic", + form("Name=t&Attributes.entry.1.key=LambdaSuccessFeedbackRoleArn&Attributes.entry.1.value=" + ROLES + + "first&Attributes.entry.2.key=DisplayName&Attributes.entry.2.value=" + ROLES + "display" + + "&Attributes.entry.3.key=SQSFailureFeedbackRoleArn&Attributes.entry.3.value=" + ROLES + + "sqs-failure&Attributes.entry.4.key=LambdaSuccessFeedbackRoleArn&Attributes.entry.4.value=" + + ROLES + "lambda-success&Attributes.entry.6.key=HTTPSuccessFeedbackRoleArn" + + "&Attributes.entry.6.value=" + ROLES + "after-gap"), LOOKUPS)); + assertEquals(List.of(passed("firehose", sns)), PassedRoles.of("sns:CreateTopic", + json("{\"Name\":\"t\",\"Attributes\":{\"FirehoseFailureFeedbackRoleArn\":\"" + ROLES + + "firehose\",\"Policy\":\"{}\"}}"), LOOKUPS)); + assertEquals(List.of(passed("http", sns)), PassedRoles.of("sns:SetTopicAttributes", + form("TopicArn=t&AttributeName=HTTPSuccessFeedbackRoleArn&AttributeValue=" + ROLES + "http"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("sns:SetTopicAttributes", + form("TopicArn=t&AttributeName=DisplayName&AttributeValue=" + ROLES + "http"), LOOKUPS)); + // A role attribute with no value names no role; SNS answers the request. + assertEquals(List.of(), PassedRoles.of("sns:SetTopicAttributes", + form("TopicArn=t&AttributeName=HTTPSuccessFeedbackRoleArn"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("sns:SetTopicAttributes", + json("{\"TopicArn\":\"t\",\"AttributeName\":\"HTTPSuccessFeedbackRoleArn\"}"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("sns:SetSubscriptionAttributes", + form("SubscriptionArn=s&AttributeName=SubscriptionRoleArn"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("sns:SetSubscriptionAttributes", + json("{\"SubscriptionArn\":\"s\",\"AttributeName\":\"SubscriptionRoleArn\",\"AttributeValue\":null}"), + LOOKUPS)); + // A subscription's role is its own attribute, not a topic's. + assertEquals(List.of(passed("subscription", sns)), PassedRoles.of("sns:Subscribe", + form("TopicArn=t&Protocol=firehose&Attributes.entry.1.key=SubscriptionRoleArn&Attributes.entry.1.value=" + + ROLES + "subscription"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("sns:Subscribe", + form("TopicArn=t&Attributes.entry.1.key=LambdaSuccessFeedbackRoleArn&Attributes.entry.1.value=" + + ROLES + "topic"), LOOKUPS)); + assertEquals(List.of(passed("subscription", sns)), PassedRoles.of("sns:SetSubscriptionAttributes", + json("{\"SubscriptionArn\":\"s\",\"AttributeName\":\"SubscriptionRoleArn\",\"AttributeValue\":\"" + + ROLES + "subscription\"}"), LOOKUPS)); + for (String action : new String[] {"sns:CreatePlatformApplication", "sns:SetPlatformApplicationAttributes"}) { + assertEquals(List.of(passed("platform", sns)), PassedRoles.of(action, + form("Name=a&Attributes.entry.1.key=FailureFeedbackRoleArn&Attributes.entry.1.value=" + ROLES + + "platform"), LOOKUPS), action); + } + assertEquals(List.of(passed("sms", sns)), PassedRoles.of("sns:SetSMSAttributes", + form("attributes.entry.1.key=DeliveryStatusIAMRole&attributes.entry.1.value=" + ROLES + "sms"), LOOKUPS)); + } + + @Test + void aLogsSubscriptionFilterPolicyPassesTheRoleItsDocumentNamesToLogs() { + String document = "\"{\\\"DestinationArn\\\":\\\"arn:aws:kinesis:us-east-1:111122223333:stream/s\\\"," + + "\\\"RoleArn\\\":\\\"" + ROLES + "delivery\\\"}\""; + assertEquals(List.of(passed("delivery", "logs.amazonaws.com")), PassedRoles.of("logs:PutAccountPolicy", + json("{\"policyName\":\"p\",\"policyType\":\"SUBSCRIPTION_FILTER_POLICY\",\"policyDocument\":" + + document + "}"), LOOKUPS)); + // Another type of policy names no role, and a document that is not JSON names none either. + assertEquals(List.of(), PassedRoles.of("logs:PutAccountPolicy", + json("{\"policyName\":\"p\",\"policyType\":\"FIELD_INDEX_POLICY\",\"policyDocument\":" + + document + "}"), LOOKUPS)); + assertEquals(List.of(), PassedRoles.of("logs:PutAccountPolicy", + json("{\"policyName\":\"p\",\"policyType\":\"SUBSCRIPTION_FILTER_POLICY\",\"policyDocument\":" + + "\"RoleArn=" + ROLES + "delivery\"}"), LOOKUPS)); + } + + @Test + void theTableReadsARoleInAQueryListAByNameMemberAMapAndOneWithNoNamedService() { + // SES's receipt rule actions in either list form the Query protocol sends. + assertEquals(List.of(passed("connect", "ses.amazonaws.com"), passed("s3", "ses.amazonaws.com")), + PassedRoles.of("ses:CreateReceiptRule", form("RuleSetName=r&Rule.Name=n" + + "&Rule.Actions.member.1.S3Action.IamRoleArn=" + ROLES + "s3" + + "&Rule.Actions.2.ConnectAction.IAMRoleARN=" + ROLES + "connect"), LOOKUPS)); + // Glue takes a job's role by name, which is the role IAM holds under it, path included. + assertEquals(List.of(new PassedRole(ROLES + "app/app-role", "glue.amazonaws.com")), + PassedRoles.of("glue:CreateJob", json("{\"Name\":\"j\",\"Role\":\"app-role\"}"), LOOKUPS)); + assertEquals(List.of(passed("gone", "glue.amazonaws.com")), + PassedRoles.of("glue:CreateJob", json("{\"Name\":\"j\",\"Role\":\"gone\"}"), LOOKUPS)); + // An identity pool's roles are the values of a map, which the Service Reference passes to no service. + assertEquals(List.of(new PassedRole(ROLES + "authenticated", null)), PassedRoles.of( + "cognito-identity:SetIdentityPoolRoles", json("{\"IdentityPoolId\":\"p\",\"Roles\":{\"authenticated\":\"" + + ROLES + "authenticated\"}}"), LOOKUPS)); + // A member taking only an ARN passes nothing for a name. + assertEquals(List.of(), PassedRoles.of("codebuild:CreateProject", + json("{\"name\":\"p\",\"serviceRole\":\"app-role\"}"), LOOKUPS)); + } + + private static String constraint(String type, String parameters) { + return "{\"PortfolioId\":\"port\",\"ProductId\":\"prod\",\"Type\":\"" + type + "\",\"Parameters\":\"" + + parameters + "\"}"; + } + private static PassedRole passed(String roleName, String service) { return new PassedRole(ROLES + roleName, service); } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java index e2dd20ba38..59defc61f3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPassRoleEnforcementIntegrationTest.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.net.URI; import java.util.LinkedHashMap; import java.util.Map; +import java.util.UUID; import java.util.zip.GZIPOutputStream; import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; @@ -57,6 +58,8 @@ class IamPassRoleEnforcementIntegrationTest { private static final String REDSHIFT_SERVERLESS = "redshift-serverless.amazonaws.com"; private static final String RDS = "rds.amazonaws.com"; private static final String DMS = "dms.amazonaws.com"; + private static final String SSM = "ssm.amazonaws.com"; + private static final String SERVICE_CATALOG = "servicecatalog.amazonaws.com"; private static final String SERVICE_LINKED_ROLES = "arn:aws:iam::" + ACCOUNT + ":role/aws-service-role/autoscaling.amazonaws.com/"; private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); @@ -1119,6 +1122,353 @@ class IamPassRoleEnforcementIntegrationTest { "{\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\"}}}"); } + @Test + void anSsmAssociationAndACommandNeedPassRoleOnTheRolesTheyNameForSsm() { + String role = role("ssm-dispatch"); + User user = user("passrole-ssm"); + String association = "{\"Name\":\"passrole-missing-document\",\"InstanceId\":\"i-0123456789abcdef0\"," + + "\"AssociationDispatchAssumeRole\":\"" + role + "\"}"; + String update = "{\"AssociationId\":\"" + UUID.randomUUID() + "\",\"AssociationDispatchAssumeRole\":\"" + + role + "\"}"; + // The command names no instance, so SSM refuses it once it is authorized. + String command = "{\"DocumentName\":\"AWS-RunShellScript\",\"ServiceRoleArn\":\"" + role + "\"}"; + String actions = allow("ssm:CreateAssociation", "*") + "," + allow("ssm:UpdateAssociation", "*") + "," + + allow("ssm:SendCommand", "*"); + + // A grant to pass the role to Lambda does not cover SSM. + user.policy(actions + "," + passRole(role, LAMBDA)); + deniedJson(ssm(user, "CreateAssociation").body(association).post("/").then()); + deniedJson(ssm(user, "UpdateAssociation").body(update).post("/").then()); + deniedJson(ssm(user, "SendCommand").body(command).post("/").then()); + + user.policy(actions + "," + passRole(role, SSM)); + ssm(user, "CreateAssociation").body(association).post("/").then() + .statusCode(400).body(containsString("InvalidDocument")); + ssm(user, "UpdateAssociation").body(update).post("/").then() + .statusCode(400).body(containsString("AssociationDoesNotExist")); + ssm(user, "SendCommand").body(command).post("/").then() + .statusCode(400).body(containsString("InvalidInstanceId")); + } + + @Test + void aServiceCatalogLaunchRoleNeedsPassRoleForServiceCatalog() { + String role = role("catalog-launch"); + User user = user("passrole-catalog"); + String portfolio = catalogAdmin("CreatePortfolio", "{\"DisplayName\":\"passrole-" + suffix() + + "\",\"ProviderName\":\"floci\"}").extract().path("PortfolioDetail.Id"); + cleanup.register(() -> deleteFromCatalog("DeletePortfolio", portfolio)); + String product = catalogAdmin("CreateProduct", "{\"Name\":\"passrole-" + suffix() + "\",\"Owner\":\"floci\"," + + "\"ProvisioningArtifactParameters\":[{\"Name\":\"v1\"}]}") + .extract().path("ProductViewDetail.ProductViewSummary.Id"); + cleanup.register(() -> deleteFromCatalog("DeleteProduct", product)); + String launch = catalogAdmin("CreateConstraint", constraint(portfolio, product, "LAUNCH", "{}")) + .extract().path("ConstraintDetail.ConstraintId"); + String notification = catalogAdmin("CreateConstraint", constraint(portfolio, product, "NOTIFICATION", + "{\\\"NotificationArns\\\":[]}")).extract().path("ConstraintDetail.ConstraintId"); + // Floci keeps a constraint's type as given, so one typed in lowercase is a launch constraint too. + String lowercase = catalogAdmin("CreateConstraint", constraint(portfolio, product, "launch", "{}")) + .extract().path("ConstraintDetail.ConstraintId"); + cleanup.register(() -> deleteFromCatalog("DeleteConstraint", launch)); + cleanup.register(() -> deleteFromCatalog("DeleteConstraint", notification)); + cleanup.register(() -> deleteFromCatalog("DeleteConstraint", lowercase)); + String launchRole = "{\\\"RoleArn\\\":\\\"" + role + "\\\"}"; + String create = constraint(portfolio, product, "LAUNCH", launchRole); + String updateLaunch = "{\"Id\":\"" + launch + "\",\"Parameters\":\"" + launchRole + "\"}"; + String updateNotification = "{\"Id\":\"" + notification + "\",\"Parameters\":\"" + launchRole + "\"}"; + String createLowercase = constraint(portfolio, product, "launch", launchRole); + String updateLowercase = "{\"Id\":\"" + lowercase + "\",\"Parameters\":\"" + launchRole + "\"}"; + String serviceAction = "{\"Name\":\"passrole-" + suffix() + "\",\"DefinitionType\":\"SSM_AUTOMATION\"," + + "\"Definition\":{\"Name\":\"AWS-RestartEC2Instance\",\"Version\":\"1\",\"AssumeRole\":\"" + + role + "\"},\"IdempotencyToken\":\"" + suffix() + "\"}"; + String properties = "{\"ProvisionedProductId\":\"pp-passrolemissing\",\"IdempotencyToken\":\"" + suffix() + + "\",\"ProvisionedProductProperties\":{\"LAUNCH_ROLE\":\"" + role + "\"}}"; + String actions = allow("servicecatalog:*", "*"); + + // A grant to pass the role to SSM does not cover Service Catalog. + user.policy(actions + "," + passRole(role, SSM)); + deniedJson(catalog(user, "CreateConstraint").body(create).post("/").then()); + deniedJson(catalog(user, "UpdateConstraint").body(updateLaunch).post("/").then()); + deniedJson(catalog(user, "CreateConstraint").body(createLowercase).post("/").then()); + deniedJson(catalog(user, "UpdateConstraint").body(updateLowercase).post("/").then()); + deniedJson(catalog(user, "CreateServiceAction").body(serviceAction).post("/").then()); + deniedJson(catalog(user, "UpdateProvisionedProductProperties").body(properties).post("/").then()); + // The update goes by the constraint's own type: a notification constraint takes no launch role. + catalog(user, "UpdateConstraint").body(updateNotification).post("/").then().statusCode(200); + + user.policy(actions + "," + passRole(role, SERVICE_CATALOG)); + String created = catalog(user, "CreateConstraint").body(create).post("/").then().statusCode(200) + .extract().path("ConstraintDetail.ConstraintId"); + cleanup.register(() -> deleteFromCatalog("DeleteConstraint", created)); + catalog(user, "UpdateConstraint").body(updateLaunch).post("/").then().statusCode(200); + String action = catalog(user, "CreateServiceAction").body(serviceAction).post("/").then().statusCode(200) + .extract().path("ServiceActionDetail.ServiceActionSummary.Id"); + cleanup.register(() -> deleteFromCatalog("DeleteServiceAction", action)); + catalog(user, "UpdateProvisionedProductProperties").body(properties).post("/").then() + .statusCode(400).body(containsString("ResourceNotFoundException")); + } + + @Test + void aServiceCatalogLocalRoleNameNeedsPassRoleOnTheArnIamHoldsItUnder() { + String held = role("/catalog/", "catalog-local"); + String pathless = "arn:aws:iam::" + ACCOUNT + ":role/" + roleName(held); + User user = user("passrole-catalog-local"); + String update = "{\"Id\":\"cons-passrolemissing\",\"Parameters\":\"{\\\"LocalRoleName\\\":\\\"" + + roleName(held) + "\\\"}\"}"; + String create = constraint("port-passrolemissing", "prod-passrolemissing", "LAUNCH", + "{\\\"LocalRoleName\\\":\\\"" + roleName(held) + "\\\"}"); + + // The name carries no path, but the role it names is the one IAM holds under /catalog/. + user.policy(allow("servicecatalog:CreateConstraint", "*") + "," + passRole(pathless, SERVICE_CATALOG)); + deniedJson(catalog(user, "CreateConstraint").body(create).post("/").then()); + user.policy(allow("servicecatalog:CreateConstraint", "*") + "," + passRole(held, SERVICE_CATALOG)); + catalog(user, "CreateConstraint").body(create).post("/").then() + .statusCode(400).body(containsString("ResourceNotFoundException")); + + // A constraint Floci does not hold has no type to read a launch role by, and Service Catalog reports it. + user.policy(allow("servicecatalog:UpdateConstraint", "*")); + catalog(user, "UpdateConstraint").body(update).post("/").then() + .statusCode(400).body(containsString("ResourceNotFoundException")); + } + + @Test + void aRotationRoleABudgetActionsRoleAndAWorkflowsLambdaRoleNeedPassRoleForTheirService() { + String role = role("service-role"); + User user = user("passrole-mixed"); + String rotate = "{\"SecretId\":\"passrole-missing-secret\",\"ExternalSecretRotationRoleArn\":\"" + role + "\"}"; + String budgetAction = ("{\"AccountId\":\"%s\",\"BudgetName\":\"passrole-missing\",\"NotificationType\":\"ACTUAL\"," + + "\"ActionType\":\"APPLY_IAM_POLICY\",\"ActionThreshold\":{\"ActionThresholdValue\":80," + + "\"ActionThresholdType\":\"PERCENTAGE\"},\"Definition\":{\"IamActionDefinition\":{\"PolicyArn\":" + + "\"arn:aws:iam::%s:policy/passrole-deny\",\"Roles\":[\"target\"]}},\"ExecutionRoleArn\":\"%s\"," + + "\"ApprovalModel\":\"AUTOMATIC\",\"Subscribers\":[{\"SubscriptionType\":\"EMAIL\"," + + "\"Address\":\"ops@example.com\"}]}").formatted(ACCOUNT, ACCOUNT, role); + String workflowType = "{\"domain\":\"passrole-missing\",\"name\":\"w\",\"version\":\"1\"," + + "\"defaultLambdaRole\":\"" + role + "\"}"; + String execution = "{\"domain\":\"passrole-missing\",\"workflowId\":\"w\",\"workflowType\":" + + "{\"name\":\"w\",\"version\":\"1\"},\"lambdaRole\":\"" + role + "\"}"; + String decisions = "{\"taskToken\":\"passrole-missing\",\"decisions\":[{\"decisionType\":" + + "\"StartChildWorkflowExecution\",\"startChildWorkflowExecutionDecisionAttributes\":" + + "{\"workflowType\":{\"name\":\"w\",\"version\":\"1\"},\"workflowId\":\"child\"," + + "\"lambdaRole\":\"" + role + "\"}}]}"; + String actions = allow("secretsmanager:RotateSecret", "*") + "," + allow("budgets:CreateBudgetAction", "*") + + "," + allow("swf:*", "*"); + + // Each grant is for another service's principal. + user.policy(actions + "," + passRole(role, "budgets.amazonaws.com") + "," + passRole(role, SSM)); + deniedJson(user.json("secretsmanager", "secretsmanager.RotateSecret").body(rotate).post("/").then()); + user.policy(actions + "," + passRole(role, "secretsmanager.amazonaws.com") + "," + passRole(role, SSM)); + deniedJson(user.json("budgets", "AWSBudgetServiceGateway.CreateBudgetAction").body(budgetAction).post("/") + .then()); + user.policy(actions + "," + passRole(role, "secretsmanager.amazonaws.com") + "," + + passRole(role, "budgets.amazonaws.com")); + deniedJson(swf(user, "RegisterWorkflowType").body(workflowType).post("/").then()); + deniedJson(swf(user, "StartWorkflowExecution").body(execution).post("/").then()); + deniedJson(swf(user, "RespondDecisionTaskCompleted").body(decisions).post("/").then()); + + // With all three, each request reaches its service, which has nothing of that name. + user.policy(actions + "," + passRole(role, "secretsmanager.amazonaws.com") + "," + + passRole(role, "budgets.amazonaws.com") + "," + passRole(role, "swf.amazonaws.com")); + user.json("secretsmanager", "secretsmanager.RotateSecret").body(rotate).post("/").then() + .statusCode(400).body(containsString("ResourceNotFoundException")); + user.json("budgets", "AWSBudgetServiceGateway.CreateBudgetAction").body(budgetAction).post("/").then() + .statusCode(400).body(containsString("NotFoundException")); + swf(user, "RegisterWorkflowType").body(workflowType).post("/").then() + .statusCode(400).body(containsString("UnknownResourceFault")); + swf(user, "StartWorkflowExecution").body(execution).post("/").then() + .statusCode(400).body(containsString("UnknownResourceFault")); + swf(user, "RespondDecisionTaskCompleted").body(decisions).post("/").then() + .statusCode(400).body(containsString("Unknown or expired task token")); + } + + @Test + void anSnsTopicsDeliveryStatusRoleNeedsPassRoleForSns() { + String role = role("sns-feedback"); + User user = user("passrole-sns"); + String topic = "passrole-topic-" + suffix(); + String topicArn = "arn:aws:sns:us-east-1:" + ACCOUNT + ":" + topic; + String actions = allow("sns:CreateTopic", "*") + "," + allow("sns:SetTopicAttributes", "*"); + + user.policy(actions + "," + passRole(role, LAMBDA)); + denied(user.query("sns", "CreateTopic").formParam("Name", topic) + .formParam("Attributes.entry.1.key", "LambdaFailureFeedbackRoleArn") + .formParam("Attributes.entry.1.value", role).post("/").then()); + denied(user.query("sns", "SetTopicAttributes").formParam("TopicArn", topicArn) + .formParam("AttributeName", "SQSSuccessFeedbackRoleArn").formParam("AttributeValue", role) + .post("/").then()); + + user.policy(actions + "," + passRole(role, "sns.amazonaws.com")); + user.query("sns", "CreateTopic").formParam("Name", topic) + .formParam("Attributes.entry.1.key", "LambdaFailureFeedbackRoleArn") + .formParam("Attributes.entry.1.value", role).post("/").then().statusCode(200); + cleanup.register(() -> admin("sns").formParam("Action", "DeleteTopic").formParam("TopicArn", topicArn).post("/")); + user.query("sns", "SetTopicAttributes").formParam("TopicArn", topicArn) + .formParam("AttributeName", "SQSSuccessFeedbackRoleArn").formParam("AttributeValue", role) + .post("/").then().statusCode(200); + + // A role attribute with no value names no role, so SNS answers it: a topic takes it, and a Firehose + // subscription refuses it. + user.policy(actions + "," + allow("sns:SetSubscriptionAttributes", "*")); + user.query("sns", "SetTopicAttributes").formParam("TopicArn", topicArn) + .formParam("AttributeName", "SQSSuccessFeedbackRoleArn").post("/").then().statusCode(200); + String subscription = admin("sns").formParam("Action", "Subscribe").formParam("TopicArn", topicArn) + .formParam("Protocol", "firehose") + .formParam("Endpoint", "arn:aws:firehose:us-east-1:" + ACCOUNT + ":deliverystream/passrole") + .formParam("Attributes.entry.1.key", "SubscriptionRoleArn") + .formParam("Attributes.entry.1.value", role).post("/").then().statusCode(200) + .extract().xmlPath().getString("SubscribeResponse.SubscribeResult.SubscriptionArn"); + user.query("sns", "SetSubscriptionAttributes").formParam("SubscriptionArn", subscription) + .formParam("AttributeName", "SubscriptionRoleArn").post("/").then().statusCode(400) + .body(containsString("SubscriptionRoleArn must be a valid IAM role ARN")); + } + + @Test + void aReceiptRulesRoleAndAMetricStreamsRoleInAQueryRequestNeedPassRoleForTheirService() { + String role = role("query-roles"); + User user = user("passrole-query"); + String stream = "passrole-stream-" + suffix(); + String actions = allow("ses:CreateReceiptRule", "*") + "," + allow("cloudwatch:PutMetricStream", "*"); + + user.policy(actions + "," + passRole(role, LAMBDA)); + denied(receiptRule(user, role).post("/").then()); + denied(metricStream(user, stream, role).post("/").then()); + + user.policy(actions + "," + passRole(role, "ses.amazonaws.com") + "," + + passRole(role, "streams.metrics.cloudwatch.amazonaws.com")); + receiptRule(user, role).post("/").then().statusCode(400).body(containsString("RuleSetDoesNotExist")); + metricStream(user, stream, role).post("/").then().statusCode(200); + cleanup.register(() -> admin("monitoring").formParam("Action", "DeleteMetricStream").formParam("Name", stream) + .post("/")); + } + + @Test + void aBuildProjectsServiceRoleAndADeliveryStreamsRoleNeedPassRoleForTheirService() { + String role = role("json-roles"); + User user = user("passrole-json"); + String project = "passrole-project-" + suffix(); + String deliveryStream = "passrole-delivery-" + suffix(); + String createProject = ("{\"name\":\"%s\",\"source\":{\"type\":\"NO_SOURCE\",\"buildspec\":\"version: 0.2\"}," + + "\"artifacts\":{\"type\":\"NO_ARTIFACTS\"},\"environment\":{\"type\":\"LINUX_CONTAINER\"," + + "\"image\":\"aws/codebuild/standard:7.0\",\"computeType\":\"BUILD_GENERAL1_SMALL\"}," + + "\"serviceRole\":\"%s\"}").formatted(project, role); + String createStream = ("{\"DeliveryStreamName\":\"%s\",\"ExtendedS3DestinationConfiguration\":" + + "{\"RoleARN\":\"%s\",\"BucketARN\":\"arn:aws:s3:::passrole-bucket\"}}").formatted(deliveryStream, role); + String actions = allow("codebuild:CreateProject", "*") + "," + allow("firehose:CreateDeliveryStream", "*"); + + user.policy(actions + "," + passRole(role, LAMBDA)); + deniedJson(user.json("codebuild", "CodeBuild_20161006.CreateProject").body(createProject).post("/").then()); + deniedJson(user.json("firehose", "Firehose_20150804.CreateDeliveryStream").body(createStream).post("/").then()); + + user.policy(actions + "," + passRole(role, "codebuild.amazonaws.com") + "," + + passRole(role, "firehose.amazonaws.com")); + user.json("codebuild", "CodeBuild_20161006.CreateProject").body(createProject).post("/").then().statusCode(200); + cleanup.register(() -> admin("codebuild").header("X-Amz-Target", "CodeBuild_20161006.DeleteProject") + .contentType("application/x-amz-json-1.1").body("{\"name\":\"" + project + "\"}").post("/")); + user.json("firehose", "Firehose_20150804.CreateDeliveryStream").body(createStream).post("/").then() + .statusCode(200); + cleanup.register(() -> admin("firehose").header("X-Amz-Target", "Firehose_20150804.DeleteDeliveryStream") + .contentType("application/x-amz-json-1.1").body("{\"DeliveryStreamName\":\"" + deliveryStream + "\"}") + .post("/")); + } + + @Test + void aGlueJobsRoleNamedByNameNeedsPassRoleOnTheArnIamHoldsItUnder() { + String role = role("/glue/", "glue-job"); + String name = roleName(role); + User user = user("passrole-glue"); + String job = "passrole-job-" + suffix(); + String createJob = ("{\"Name\":\"%s\",\"Role\":\"%s\",\"Command\":{\"Name\":\"glueetl\"," + + "\"ScriptLocation\":\"s3://passrole-bucket/job.py\"}}").formatted(job, name); + + // The name carries no path; the role it names is the one IAM holds under /glue/. + user.policy(allow("glue:CreateJob", "*") + "," + + passRole("arn:aws:iam::" + ACCOUNT + ":role/" + name, "glue.amazonaws.com")); + deniedJson(user.json("glue", "AWSGlue.CreateJob").body(createJob).post("/").then()); + + user.policy(allow("glue:CreateJob", "*") + "," + passRole(role, "glue.amazonaws.com")); + user.json("glue", "AWSGlue.CreateJob").body(createJob).post("/").then().statusCode(200); + cleanup.register(() -> admin("glue").header("X-Amz-Target", "AWSGlue.DeleteJob") + .contentType("application/x-amz-json-1.1").body("{\"JobName\":\"" + job + "\"}").post("/")); + } + + @Test + void aCognitoGroupsRoleIsPassedToNoNamedService() { + String role = role("cognito-group"); + User user = user("passrole-cognito"); + String group = "{\"UserPoolId\":\"us-east-1_passrolemissing\",\"GroupName\":\"g\",\"RoleArn\":\"" + role + "\"}"; + + // The Service Reference names no service for a group's role, so a grant naming one does not match. + user.policy(allow("cognito-idp:CreateGroup", "*") + "," + passRole(role, "cognito-idp.amazonaws.com")); + deniedJson(user.json("cognito-idp", "AWSCognitoIdentityProviderService.CreateGroup").body(group).post("/") + .then()); + + user.policy(allow("cognito-idp:CreateGroup", "*") + "," + allow("iam:PassRole", role)); + user.json("cognito-idp", "AWSCognitoIdentityProviderService.CreateGroup").body(group).post("/").then() + .statusCode(400).body(containsString("ResourceNotFoundException")); + } + + @Test + void aSubscriptionFilterPolicysRoleNeedsPassRoleForLogs() { + String role = role("logs-delivery"); + User user = user("passrole-logs"); + String policy = "passrole-policy-" + suffix(); + String body = ("{\"policyName\":\"%s\",\"policyType\":\"SUBSCRIPTION_FILTER_POLICY\",\"policyDocument\":" + + "\"{\\\"DestinationArn\\\":\\\"arn:aws:kinesis:us-east-1:%s:stream/passrole\\\"," + + "\\\"RoleArn\\\":\\\"%s\\\"}\"}").formatted(policy, ACCOUNT, role); + + // A subscription filter policy also needs logs:PutSubscriptionFilter, which Floci checks too. + String actions = allow("logs:PutAccountPolicy", "*") + "," + allow("logs:PutSubscriptionFilter", "*"); + user.policy(actions + "," + passRole(role, LAMBDA)); + deniedJson(user.json("logs", "Logs_20140328.PutAccountPolicy").body(body).post("/").then()); + + user.policy(actions + "," + passRole(role, "logs.amazonaws.com")); + user.json("logs", "Logs_20140328.PutAccountPolicy").body(body).post("/").then().statusCode(200); + cleanup.register(() -> admin("logs").header("X-Amz-Target", "Logs_20140328.DeleteAccountPolicy") + .contentType("application/x-amz-json-1.1") + .body("{\"policyName\":\"" + policy + "\",\"policyType\":\"SUBSCRIPTION_FILTER_POLICY\"}").post("/")); + } + + private static RequestSpecification receiptRule(User user, String role) { + return user.query("ses", "CreateReceiptRule").formParam("RuleSetName", "passrole-missing") + .formParam("Rule.Name", "r").formParam("Rule.Enabled", "true") + .formParam("Rule.Actions.member.1.S3Action.BucketName", "passrole-bucket") + .formParam("Rule.Actions.member.1.S3Action.IamRoleArn", role); + } + + private static RequestSpecification metricStream(User user, String name, String role) { + return user.query("monitoring", "PutMetricStream").formParam("Name", name) + .formParam("FirehoseArn", "arn:aws:firehose:us-east-1:" + ACCOUNT + ":deliverystream/passrole") + .formParam("RoleArn", role).formParam("OutputFormat", "json"); + } + + private static RequestSpecification ssm(User user, String operation) { + return user.json("ssm", "AmazonSSM." + operation); + } + + private static RequestSpecification catalog(User user, String operation) { + return user.json("servicecatalog", "AWS242ServiceCatalogService." + operation); + } + + private static ValidatableResponse catalogAdmin(String operation, String body) { + return admin("servicecatalog").header("X-Amz-Target", "AWS242ServiceCatalogService." + operation) + .contentType("application/x-amz-json-1.1").body(body).post("/").then().statusCode(200); + } + + private static void deleteFromCatalog(String operation, String id) { + admin("servicecatalog").header("X-Amz-Target", "AWS242ServiceCatalogService." + operation) + .contentType("application/x-amz-json-1.1").body("{\"Id\":\"" + id + "\"}").post("/"); + } + + /** A CreateConstraint body; {@code parameters} is the document, its quotes escaped for the JSON string it sits in. */ + private static String constraint(String portfolio, String product, String type, String parameters) { + return "{\"PortfolioId\":\"" + portfolio + "\",\"ProductId\":\"" + product + "\",\"Type\":\"" + type + + "\",\"Parameters\":\"" + parameters + "\",\"IdempotencyToken\":\"" + suffix() + "\"}"; + } + + /** SWF speaks JSON 1.0. */ + private static RequestSpecification swf(User user, String operation) { + return given().header("Authorization", auth(user.accessKeyId(), "swf")) + .header("X-Amz-Target", "SimpleWorkflowService." + operation).contentType("application/x-amz-json-1.0"); + } + private static String roleName(String roleArn) { return roleArn.substring(roleArn.lastIndexOf('/') + 1); } @@ -1272,6 +1622,10 @@ class IamPassRoleEnforcementIntegrationTest { .contentType("application/cbor").accept("application/cbor"); } + RequestSpecification query(String service, String action) { + return given().header("Authorization", auth(accessKeyId, service)).formParam("Action", action); + } + RequestSpecification cfn(String action) { return given().header("Authorization", auth(accessKeyId, "cloudformation")).formParam("Action", action); } diff --git a/tools/aws/regen_iam_passed_roles.py b/tools/aws/regen_iam_passed_roles.py new file mode 100644 index 0000000000..489bae8185 --- /dev/null +++ b/tools/aws/regen_iam_passed_roles.py @@ -0,0 +1,874 @@ +#!/usr/bin/env python3 +"""Regenerate src/main/resources/aws/iam-passed-roles.json from AWS's Service Reference and botocore. + +A request that passes a role to a service also needs `iam:PassRole` on that role. The IAM user guide: +"To pass a role (and its permissions) to an AWS service, a user must have permissions to pass the +role to the service." `PassedRoles` finds the roles a request passes, and this file tells it where +each operation's request carries them. It comes from two sources, each answering what the other +cannot: + +- AWS's Service Reference, which lists `iam:PassRole` among an operation's `AuthorizedActions`, with + the services the role goes to as `iam:PassedToService`, but does not say which request member + names the role: + + https://servicereference.us-east-1.amazonaws.com/ (the index of services) + https://servicereference.us-east-1.amazonaws.com/v1//.json + +- botocore's model of each SDK client the reference lists the operation for (Apache-2.0, + https://github.com/boto/botocore, the pinned release), which gives the request's members but + not which of them AWS checks. + +A member of the operation's request is read as a role it passes when its name ends in `Role`, +`RoleArn`, `RoleName`, the plural of one, or one of those followed by `Update` or `Override` +(`RoleARNUpdate`, `serviceRoleOverride`), and it is a string or a list of strings without an enum. +That leaves out `RoleSessionName` and `AmbiguousRoleResolution`, which name no role. A member whose +own documentation says it takes a role by name as well as by ARN is marked `byName`, and Floci +resolves the name in the request's account, as the services do. What the rule gets wrong for an +operation is corrected here, each with its reason: a role member it does not see (`EXTRA_MEMBERS`), +a member it sees that passes no role (`EXCLUDED_MEMBERS`), and which service a member's role goes to +when the reference names several (`MEMBER_SERVICES`). + +Only the namespaces in `NAMESPACES` are read, and in them every operation the reference lists with +`iam:PassRole`, whether Floci serves it or not, so an operation Floci adds is checked from the +start. Each of those operations ends up in exactly one of three places, and generation fails on an +operation that would end up in none: + +- `roles`: the members it reads, each with the service its role is passed to. +- `byHand`: operations `PassedRoles` reads itself, because their roles are not a request member: an + instance profile's roles, a task definition's, a launch template's, or one that depends on the + resource the request names. `PassedRolesCoverageTest` holds the two lists to each other. +- `notRead`: operations whose request names no role this table can read, each with its reason. + +The Service Reference is live rather than a pinned dependency, so a fresh generation is not +byte-identical. The two gates split along the sources: + +- `--check` is offline and needs the pinned botocore. The file must be well-formed, and every + operation's members must be exactly what the rule and the corrections give from botocore for the + models the file names, so a hand-edited member fails. +- `--verify` is online and stdlib-only. Every operation the file carries must still list + `iam:PassRole`, to the same services, for the same SDK clients. An operation AWS has added is + reported without failing: until the next sync it passes roles unchecked, which is where it was + before this file existed. + +Run from anywhere in the repo: + python3 tools/aws/regen_iam_passed_roles.py # rewrite the vendored file in place + python3 tools/aws/regen_iam_passed_roles.py --check # offline: members match botocore + python3 tools/aws/regen_iam_passed_roles.py --verify # online: operations match AWS + python3 tools/aws/regen_iam_passed_roles.py --source-dir

# read saved .json files +""" +from __future__ import annotations + +import argparse +import json +import re +import sys +from datetime import datetime, timezone +from pathlib import Path + +from regen_iam_authorized_actions import fetch_references +from regen_partitions import resolve_botocore_data +from regen_query_services import latest_model_dir, load_model + +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-passed-roles.json" + +PASSED_TO_SERVICE = "iam:PassedToService" +SERVICE_SUFFIX = ".amazonaws.com" + +# The IAM namespaces whose operations this file reads: those Floci serves over the JSON and Query +# protocols and Smithy RPC v2 CBOR, and the REST ones whose routes Floci authorizes by operation. +NAMESPACES = ( + "application-autoscaling", "athena", "autoscaling", "budgets", "cloudformation", "cloudtrail", + "cloudwatch", "codebuild", "codedeploy", "codepipeline", "cognito-identity", "cognito-idp", + "comprehend", "config", "datasync", "dms", "dsql", "ec2", "ecr", "ecs", "eks", "elasticmapreduce", + "events", "firehose", "glue", "iam", "kinesis", "kinesisanalytics", "lambda", "logs", "pipes", + "rds", "redshift", "redshift-serverless", "rekognition", "resource-groups", "s3", "sagemaker", "scheduler", + "secretsmanager", "servicecatalog", "ses", "sns", "ssm", "states", "swf", "textract", + "transcribe", "transfer", "translate", +) + +# Namespaces Floci serves whose operations list iam:PassRole but are not read here yet, each with +# why. `PassedRolesCoverageTest` fails for a namespace Floci serves that is in neither list. +NOT_COVERED = { + "apigateway": "authorized by HTTP method, so no request is checked as one of these operations", + "access-analyzer": "REST routes no rule maps yet", + "airflow": "REST routes no rule maps yet", + "appconfig": "REST routes no rule maps yet", + "appsync": "REST routes no rule maps yet", + "aps": "REST routes no rule maps yet", + "aws-marketplace": "REST routes no rule maps yet", + "backup": "REST routes no rule maps yet", + "batch": "REST routes no rule maps yet", + "bedrock": "REST routes no rule maps yet", + "bedrock-agentcore": "REST routes no rule maps yet", + "cloudfront": "REST routes no rule maps yet", + "dlm": "REST routes no rule maps yet", + "elasticfilesystem": "REST routes no rule maps yet", + "emr-serverless": "REST routes no rule maps yet", + "es": "REST routes no rule maps yet", + "fis": "REST routes no rule maps yet", + "guardduty": "REST routes no rule maps yet", + "iot": "REST routes no rule maps yet", + "kafka": "REST routes no rule maps yet", + "macie2": "REST routes no rule maps yet", + "mq": "REST routes no rule maps yet", + "rum": "REST routes no rule maps yet", + "s3tables": "REST routes no rule maps yet", +} + +# A member that names a role: Role, RoleArn, RoleName, their plurals, and an Update or Override of one. +ROLE_MEMBER_RE = re.compile(r"role(arn|name)?s?(update|override)?$", re.IGNORECASE) +# A member named for a role's name rather than its ARN. +ROLE_NAME_MEMBER_RE = re.compile(r"rolenames?$", re.IGNORECASE) +# Documentation saying the member takes a role's name: "The name or Amazon Resource Name (ARN) of the +# IAM role", "The short name or full Amazon Resource Name (ARN)", "The IAM role or Amazon Resource +# Name (ARN) of an IAM role", "The name of a service role". +BY_NAME_DOC_RE = re.compile(r"\bname or (the |its )?(full )?(ARN|Amazon Resource Name)\b" + r"|\bshort name or\b|\b(ARN|Amazon Resource Name)( \(ARN\))? or (the )?name\b" + r"|\brole or (the )?(ARN|Amazon Resource Name)\b" + r"|(? dict[str, dict]: + """Every operation of every namespace that lists iam:PassRole, with the services the role goes + to, as `` without `.amazonaws.com`, and the SDK clients it is listed for.""" + found: dict[str, dict] = {} + for document in documents: + namespace = document.get("Name") + if not isinstance(namespace, str) or not NAMESPACE_RE.match(namespace): + raise ValueError(f"{namespace!r} is not usable as an IAM namespace") + for operation in document.get("Operations", []): + name = operation.get("Name") if isinstance(operation, dict) else None + if not isinstance(name, str): + raise ValueError(f"{namespace}: operation entry without a usable 'Name': {operation!r}") + authorized = operation.get("AuthorizedActions") or [] + if not isinstance(authorized, list) or not all(isinstance(entry, dict) for entry in authorized): + raise ValueError(f"{namespace}:{name}: 'AuthorizedActions' is not a list of objects") + passes = [entry for entry in authorized + if entry.get("Service") == "iam" and entry.get("Name") == "PassRole"] + if not passes: + continue + services: set[str] = set() + for entry in passes: + context = entry.get("Context") or {} + if not isinstance(context, dict): + raise ValueError(f"{namespace}:{name}: iam:PassRole 'Context' is not an object") + for service in context.get(PASSED_TO_SERVICE, []): + if not isinstance(service, str) or not service.endswith(SERVICE_SUFFIX): + raise ValueError(f"{namespace}:{name}: {service!r} is not a service principal") + services.add(service[:-len(SERVICE_SUFFIX)]) + clients = sorted({sdk["Name"] for sdk in operation.get("SDK") or [] + if isinstance(sdk, dict) and sdk.get("Package") == "Boto3" + and isinstance(sdk.get("Name"), str)}) + key = f"{namespace}:{name}" + entry = found.setdefault(key, {"passedTo": set(), "clients": set()}) + entry["passedTo"] |= services + entry["clients"] |= set(clients) + return {key: {"passedTo": sorted(value["passedTo"]), "clients": sorted(value["clients"])} + for key, value in sorted(found.items())} + + +# --------------------------------------------------------------------------- # +# botocore: which members of the request name a role +# --------------------------------------------------------------------------- # +def _documentation(member: dict, shape: dict) -> str: + text = member.get("documentation") or shape.get("documentation") or "" + return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", text)) + + +def _is_role_member(name: str, model: dict, shape_name: str) -> bool: + return bool(ROLE_MEMBER_RE.search(name)) and _leaf(model, shape_name) is not None + + +def _leaf(model: dict, shape_name: str) -> dict | None: + """The string shape a member holds itself, as each element of a list or each value of a map; None + when it holds anything else, or an enum, which names no role.""" + shape = model["shapes"][shape_name] + if shape["type"] == "list": + shape = model["shapes"][shape["member"]["shape"]] + elif shape["type"] == "map": + shape = model["shapes"][shape["value"]["shape"]] + return shape if shape["type"] == "string" and "enum" not in shape else None + + +def _step(shape: dict) -> str: + """The path step into a list's elements or a map's values, and nothing for any other shape.""" + if shape["type"] == "list": + return "[" + shape["member"].get("locationName", "") + "]" + return "{}" if shape["type"] == "map" else "" + + +def _takes_name(name: str, member: dict, model: dict) -> bool: + """Whether the member takes a role by name: it is named for one, or its documentation says it takes + one, unless its pattern only admits an ARN.""" + shape = _leaf(model, member["shape"]) + if shape.get("pattern", "").lstrip("^").startswith("arn:"): + return False + return bool(ROLE_NAME_MEMBER_RE.search(name) or BY_NAME_DOC_RE.search(_documentation(member, shape))) + + +def readable(model: dict) -> bool: + """Whether the model's requests come as form parameters or a JSON or CBOR body.""" + metadata = model["metadata"] + return bool(READ_PROTOCOLS & set(metadata.get("protocols") or [metadata.get("protocol")])) + + +def role_members(model: dict, operation: str) -> dict[str, bool]: + """The members of the operation's request the rule reads, as vendored paths, each with whether + it takes a role by name.""" + spec = model["operations"].get(operation) + if spec is None or "input" not in spec or not readable(model): + return {} + root = model["shapes"][spec["input"]["shape"]] + payload = root.get("payload") + found: dict[str, bool] = {} + + def walk(shape_name: str, prefix: str, top: bool, seen: frozenset) -> None: + if shape_name in seen: + return + shape = model["shapes"][shape_name] + seen = seen | {shape_name} + if shape["type"] == "list": + walk(shape["member"]["shape"], prefix + _step(shape), False, seen) + elif shape["type"] == "map": + walk(shape["value"]["shape"], prefix + _step(shape), False, seen) + elif shape["type"] == "structure": + for name, member in shape.get("members", {}).items(): + if top and member.get("location") not in BODY_LOCATIONS: + continue + serialized = member.get("locationName", name) + path = f"{prefix}.{serialized}" if prefix else serialized + if _is_role_member(name, model, member["shape"]): + leaf = path + _step(model["shapes"][member["shape"]]) + by_name = _takes_name(name, member, model) + found[leaf] = found.get(leaf, False) or by_name + else: + walk(member["shape"], path, False, seen) + + if payload is not None: + member = root["members"][payload] + walk(member["shape"], "", False, frozenset()) + else: + walk(spec["input"]["shape"], "", True, frozenset()) + return found + + +PATH_STEP_RE = re.compile(r"^(?P[A-Za-z][A-Za-z0-9_]*)(?:\[(?P[A-Za-z0-9_]*)\]|\{(?P[A-Za-z0-9_]*)\})?$") + + +def member_exists(model: dict, operation: str, path: str) -> bool: + """Whether the operation's request has a string member at `path`, a `{KEY}` step naming a key + the map's key enum lists when it has one.""" + spec = model["operations"].get(operation) + if spec is None or "input" not in spec or not readable(model): + return False + shape = model["shapes"][spec["input"]["shape"]] + for step in path.split("."): + match = PATH_STEP_RE.match(step) + if match is None or shape["type"] != "structure": + return False + found = [member for name, member in shape.get("members", {}).items() + if member.get("locationName", name) == match["name"]] + if not found: + return False + shape = model["shapes"][found[0]["shape"]] + if match["list"] is not None: + if shape["type"] != "list": + return False + shape = model["shapes"][shape["member"]["shape"]] + elif match["key"] is not None: + if shape["type"] != "map": + return False + keys = model["shapes"][shape["key"]["shape"]].get("enum") + if match["key"] and keys is not None and match["key"] not in keys: + return False + shape = model["shapes"][shape["value"]["shape"]] + return shape["type"] == "string" + + +def load_models(data: Path, clients: set[str]) -> dict[str, dict]: + return {client: load_model(latest_model_dir(data, client)) + for client in sorted(clients) if (data / client).is_dir()} + + +# --------------------------------------------------------------------------- # +# The vendored document +# --------------------------------------------------------------------------- # +def namespace_of(operation: str) -> str: + return operation.split(":", 1)[0] + + +def _overrides_for(table: dict, operation: str) -> dict: + merged = dict(table.get(namespace_of(operation) + ":*", {})) + merged.update(table.get(operation, {})) + return merged + + +def entry_for(operation: str, passed_to: list[str], models: dict[str, dict]) -> dict: + """What the file says for one operation, from its services and the models of its namespace.""" + if operation in BY_HAND: + return {"passedTo": passed_to, "byHand": BY_HAND[operation]} + if operation in NOT_READ: + return {"passedTo": passed_to, "notRead": NOT_READ[operation]} + name = operation.split(":", 1)[1] + members: dict[str, bool] = {} + for model in models.values(): + for path, by_name in role_members(model, name).items(): + members[path] = members.get(path, False) or by_name + excluded = _overrides_for(EXCLUDED_MEMBERS, operation) + for path in excluded: + members.pop(path, None) + for path, (by_name, _reason) in _overrides_for(EXTRA_MEMBERS, operation).items(): + if not any(member_exists(model, name, path) for model in models.values()): + raise ValueError(f"{operation}: EXTRA_MEMBERS names {path}, which its request does not have") + members[path] = by_name + if not members: + raise ValueError(f"{operation}: no request member names a role; read it by hand (BY_HAND), " + f"name the member (EXTRA_MEMBERS) or say why it is not read (NOT_READ)") + services = _overrides_for(MEMBER_SERVICES, operation) + roles = [] + for path in sorted(members): + role: dict = {"member": path} + if path in services or "*" in services: + role["passedTo"] = services.get(path, services.get("*")) + elif len(passed_to) == 1: + role["passedTo"] = passed_to[0] + elif passed_to: + raise ValueError(f"{operation}: the role at {path} can go to any of {passed_to}; " + f"say which in MEMBER_SERVICES") + if members[path]: + role["byName"] = True + roles.append(role) + return {"passedTo": passed_to, "roles": roles} + + +def build(documents: list[dict], provenance: str, data: Path, botocore: str) -> dict: + upstream = passed_role_operations(documents) + covered = {operation: value for operation, value in upstream.items() + if namespace_of(operation) in NAMESPACES} + _check_overrides(covered) + namespaces: dict[str, list[str]] = {} + for namespace in sorted(NAMESPACES): + clients = sorted({client for operation, value in covered.items() + if namespace_of(operation) == namespace for client in value["clients"]}) + namespaces[namespace] = clients + operations = {} + unread = [] + for operation, value in covered.items(): + models = load_models(data, set(namespaces[namespace_of(operation)])) + try: + operations[operation] = entry_for(operation, value["passedTo"], models) + except ValueError as e: + unread.append(str(e)) + unread += _unmatched_corrections(covered, namespaces, data) + if unread: + raise ValueError("\n".join(unread)) + elsewhere = sorted({namespace_of(operation) for operation in upstream} - set(NAMESPACES)) + return { + "_source": { + "generator": "tools/aws/regen_iam_passed_roles.py", + "reference": provenance, + "botocore": botocore, + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "make iam-passed-roles-check re-derives every member from botocore; " + "make iam-passed-roles-verify checks every operation against AWS.", + }, + "namespaces": namespaces, + "notCovered": dict(sorted(NOT_COVERED.items())), + "otherNamespaces": [namespace for namespace in elsewhere if namespace not in NOT_COVERED], + "operations": operations, + } + + +def _unmatched_corrections(covered: dict[str, dict], namespaces: dict[str, list[str]], data: Path) -> list[str]: + """An exclusion or a member's service that no operation it applies to has, so none outlives its member.""" + found: dict[str, set[str]] = {} + for operation in covered: + if operation in BY_HAND or operation in NOT_READ: + continue + name = operation.split(":", 1)[1] + for model in load_models(data, set(namespaces[namespace_of(operation)])).values(): + found.setdefault(operation, set()).update(role_members(model, name)) + problems = [] + for table_name, table in (("EXCLUDED_MEMBERS", EXCLUDED_MEMBERS), ("MEMBER_SERVICES", MEMBER_SERVICES)): + for key, paths in table.items(): + scope = [operation for operation in found + if operation == key or (key.endswith(":*") and namespace_of(operation) == namespace_of(key))] + for path in paths: + if path != "*" and not any(path in found[operation] for operation in scope): + problems.append(f"{table_name} names {path} for {key}, which no operation there has") + return problems + + +def _check_overrides(covered: dict[str, dict]) -> None: + """Every correction names an operation the reference lists with iam:PassRole, so none outlives it.""" + stale = [] + for table_name, table in (("BY_HAND", BY_HAND), ("NOT_READ", NOT_READ), + ("EXCLUDED_MEMBERS", EXCLUDED_MEMBERS), ("EXTRA_MEMBERS", EXTRA_MEMBERS), + ("MEMBER_SERVICES", MEMBER_SERVICES)): + for key in table: + if key.endswith(":*"): + if namespace_of(key) not in NAMESPACES: + stale.append(f"{table_name} names {key}, a namespace this file does not read") + elif key not in covered: + stale.append(f"{table_name} names {key}, which the reference does not list with iam:PassRole") + overlap = set(BY_HAND) & set(NOT_READ) + stale += [f"{operation} is both read by hand and not read" for operation in sorted(overlap)] + if stale: + raise ValueError("; ".join(stale)) + + +def render(document: dict) -> str: + """The document with one operation to a line and one role to a line under it.""" + lines = ["{"] + for key in ("_source", "namespaces", "notCovered", "otherNamespaces"): + lines.append(f' "{key}": {json.dumps(document[key])},') + lines.append(' "operations": {') + operations = list(document["operations"].items()) + for index, (operation, entry) in enumerate(operations): + tail = "," if index < len(operations) - 1 else "" + head = {key: value for key, value in entry.items() if key != "roles"} + if "roles" not in entry: + lines.append(f" {json.dumps(operation)}: {json.dumps(head)}{tail}") + continue + opening = json.dumps(head)[:-1] + ', "roles": [' + lines.append(f" {json.dumps(operation)}: {opening}") + roles = entry["roles"] + for role_index, role in enumerate(roles): + lines.append(f" {json.dumps(role)}{',' if role_index < len(roles) - 1 else ''}") + lines.append(f" ]}}{tail}") + lines += [" }", "}"] + return "\n".join(lines) + "\n" + + +# --------------------------------------------------------------------------- # +# Gates +# --------------------------------------------------------------------------- # +def validate(document: dict) -> list[str]: + """Problems that make the vendored file unusable, rather than out of date.""" + problems: list[str] = [] + namespaces = document.get("namespaces") + operations = document.get("operations") + if not isinstance(namespaces, dict) or not namespaces: + return ["namespaces is missing or empty"] + if not isinstance(operations, dict) or not operations: + return ["operations is missing or empty"] + if list(namespaces) != sorted(namespaces): + problems.append("namespaces is not sorted") + if list(operations) != sorted(operations): + problems.append("operations is not sorted") + for operation, entry in operations.items(): + if not OPERATION_RE.match(operation) or namespace_of(operation) not in namespaces: + problems.append(f"{operation!r} is not an operation of a namespace the file reads") + continue + kinds = [kind for kind in ("roles", "byHand", "notRead") if kind in entry] + if len(kinds) != 1: + problems.append(f"{operation} is not exactly one of roles, byHand and notRead") + continue + passed_to = entry.get("passedTo") + if not isinstance(passed_to, list) or not all(isinstance(s, str) and SERVICE_RE.match(s) for s in passed_to): + problems.append(f"{operation} has no usable passedTo") + continue + if kinds[0] != "roles": + if not isinstance(entry[kinds[0]], str) or not entry[kinds[0]]: + problems.append(f"{operation} gives no reason for {kinds[0]}") + continue + roles = entry["roles"] + if not isinstance(roles, list) or not roles: + problems.append(f"{operation} reads no role") + continue + for role in roles: + path = role.get("member") if isinstance(role, dict) else None + if not isinstance(path, str) or not MEMBER_PATH_RE.match(path): + problems.append(f"{operation} reads {role!r}, which is no member path") + continue + service = role.get("passedTo") + if service is None and passed_to: + problems.append(f"{operation}: the role at {path} goes to no service") + if service is not None and service not in passed_to: + problems.append(f"{operation}: the role at {path} goes to {service}, which the reference " + f"does not name") + if set(role) - {"member", "passedTo", "byName"} or role.get("byName", True) is not True: + problems.append(f"{operation}: the role at {path} carries an unknown field") + return problems + + +def derive(document: dict, data: Path) -> list[str]: + """Where the members the file gives differ from what botocore gives for the models it names.""" + problems: list[str] = [] + for operation, entry in document["operations"].items(): + models = load_models(data, set(document["namespaces"][namespace_of(operation)])) + try: + expected = entry_for(operation, entry["passedTo"], models) + except ValueError as e: + problems.append(str(e)) + continue + if expected != entry: + problems.append(f"{operation}: the file has {json.dumps(entry)}, botocore gives {json.dumps(expected)}") + return problems + + +def verify_against(vendored: dict, upstream: dict[str, dict]) -> tuple[list[str], list[str]]: + """What the file claims and AWS does not, and the operations AWS has added since.""" + untrue: list[str] = [] + for operation, entry in vendored["operations"].items(): + actual = upstream.get(operation) + if actual is None: + untrue.append(f"AWS no longer lists iam:PassRole for {operation}") + elif actual["passedTo"] != entry["passedTo"]: + untrue.append(f"AWS passes {operation}'s role to {actual['passedTo']}, not {entry['passedTo']}") + elif not set(actual["clients"]) <= set(vendored["namespaces"][namespace_of(operation)]): + untrue.append(f"AWS lists {operation} for {actual['clients']}, which the file does not read") + added = sorted(operation for operation in upstream + if namespace_of(operation) in vendored["namespaces"] and operation not in vendored["operations"]) + return untrue, added + + +def _shown(path: Path) -> Path: + try: + return path.resolve().relative_to(REPO_ROOT) + except ValueError: + return path + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--check", action="store_true", help="offline: members match the pinned botocore") + parser.add_argument("--verify", action="store_true", help="online: operations match AWS") + parser.add_argument("--source-dir", type=Path, default=None, + help="read saved .json reference files instead of fetching them") + parser.add_argument("--botocore-data", type=Path, default=None, help="botocore data directory") + parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS) + args = parser.parse_args(argv) + + if args.check or args.verify: + if not args.output.exists(): + print(f"error: {args.output} does not exist", file=sys.stderr) + return 1 + document = json.loads(args.output.read_text(encoding="utf-8")) + problems = validate(document) + if not problems and args.check: + data, _ = resolve_botocore_data(args.botocore_data) + problems = derive(document, data) + for problem in problems: + print(f"error: {problem}", file=sys.stderr) + if problems: + return 1 + entries = len(document["operations"]) + if args.check: + print(f"{_shown(args.output)} matches botocore ({entries} operations over " + f"{len(document['namespaces'])} namespaces)") + return 0 + try: + documents, provenance = fetch_references(args.source_dir) + upstream = passed_role_operations(documents) + except (OSError, ValueError) as e: + print(f"error: could not read the Service Reference ({e})", file=sys.stderr) + return 2 + untrue, added = verify_against(document, upstream) + for claim in untrue: + print(f"error: {claim}", file=sys.stderr) + if untrue: + print(f"error: {len(untrue)} vendored operation(s) do not hold upstream.", file=sys.stderr) + return 1 + if added: + print(f"{_shown(args.output)}: all {entries} operations verified. AWS has since added " + f"{len(added)}, so the file is incomplete but not wrong (run without --verify to refresh): " + f"{', '.join(added[:10])}{'...' if len(added) > 10 else ''}") + else: + print(f"{_shown(args.output)}: all {entries} operations verified against {provenance}, " + f"nothing added upstream.") + return 0 + + data, botocore = resolve_botocore_data(args.botocore_data) + try: + documents, provenance = fetch_references(args.source_dir) + document = build(documents, provenance, data, botocore) + except (OSError, ValueError) as e: + print(f"error: {e}", file=sys.stderr) + return 2 + problems = validate(document) + for problem in problems: + print(f"error: {problem}", file=sys.stderr) + if problems: + return 1 + args.output.write_text(render(document), encoding="utf-8") + print(f"wrote {_shown(args.output)} ({len(document['operations'])} operations over " + f"{len(document['namespaces'])} namespaces, from {provenance})") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/aws/test_regen_iam_passed_roles.py b/tools/aws/test_regen_iam_passed_roles.py new file mode 100644 index 0000000000..f1d14fcf9d --- /dev/null +++ b/tools/aws/test_regen_iam_passed_roles.py @@ -0,0 +1,314 @@ +"""Tests for regen_iam_passed_roles. + +Run with: pytest tools/aws -q (or: make iam-passed-roles-test) +""" +from __future__ import annotations + +import json + +import pytest + +import regen_iam_passed_roles as r + + +def reference(namespace: str, operations: dict[str, list[str] | None], clients: dict[str, list[str]] | None = None) -> dict: + """A Service Reference document. Each operation maps to the services it passes a role to, or to None + when it lists no iam:PassRole; `clients` gives an operation's SDK clients, the namespace by default.""" + entries = [] + for name, services in operations.items(): + authorized = [{"Service": namespace, "Name": name}] + if services is not None: + authorized.append({"Service": "iam", "Name": "PassRole", + "Context": {"iam:PassedToService": [s + ".amazonaws.com" for s in services]}}) + sdk = [{"Name": c, "Method": name, "Package": "Boto3"} for c in (clients or {}).get(name, [namespace])] + entries.append({"Name": name, "AuthorizedActions": authorized, "SDK": sdk}) + return {"Name": namespace, "Operations": entries} + + +def model(operations: dict[str, dict], shapes: dict[str, dict], protocol: str = "json") -> dict: + """A botocore model whose operations take the input shape each names.""" + return {"metadata": {"protocol": protocol}, + "operations": {name: {"input": {"shape": shape}} for name, shape in operations.items()}, + "shapes": {"String": {"type": "string"}, **shapes}} + + +def structure(**members) -> dict: + return {"type": "structure", "members": {name: ({"shape": spec} if isinstance(spec, str) else spec) + for name, spec in members.items()}} + + +@pytest.fixture +def corrections(monkeypatch): + """No corrections at all, so a test sees the rule alone and sets what it needs.""" + for name in ("BY_HAND", "NOT_READ", "EXCLUDED_MEMBERS", "EXTRA_MEMBERS", "MEMBER_SERVICES"): + monkeypatch.setattr(r, name, {}) + monkeypatch.setattr(r, "NAMESPACES", ("svc",)) + return monkeypatch + + +# --------------------------------------------------------------------------- # +# The Service Reference +# --------------------------------------------------------------------------- # +def test_only_operations_listing_pass_role_are_kept_with_their_services_and_clients(): + found = r.passed_role_operations([reference("svc", {"CreateThing": ["svc", "other"], "GetThing": None}, + {"CreateThing": ["svc", "svcv2"]})]) + assert found == {"svc:CreateThing": {"passedTo": ["other", "svc"], "clients": ["svc", "svcv2"]}} + + +def test_a_pass_role_with_no_service_passes_to_none(): + document = reference("svc", {"CreateGroup": []}) + assert r.passed_role_operations([document])["svc:CreateGroup"]["passedTo"] == [] + + +def test_a_passed_to_service_that_is_no_principal_is_a_malformed_response(): + document = reference("svc", {"CreateThing": ["svc"]}) + document["Operations"][0]["AuthorizedActions"][1]["Context"]["iam:PassedToService"] = ["svc"] + with pytest.raises(ValueError, match="service principal"): + r.passed_role_operations([document]) + + +def test_an_unusable_namespace_is_rejected(): + with pytest.raises(ValueError, match="not usable"): + r.passed_role_operations([{"Name": "Not A Namespace", "Operations": []}]) + + +# --------------------------------------------------------------------------- # +# botocore: the members that name a role +# --------------------------------------------------------------------------- # +def test_a_member_is_a_role_by_its_name_when_it_holds_a_string(): + m = model({"Op": "In"}, { + "In": structure(Role="String", ServiceRoleArn="String", IamRoleName="String", IamRoles="Roles", + RoleARNUpdate="String", serviceRoleOverride="String", RoleSessionName="String", + AmbiguousRoleResolution="String", RoleCount="Integer", Name="String"), + "Roles": {"type": "list", "member": {"shape": "String"}}, + "Integer": {"type": "integer"}, + }) + assert r.role_members(m, "Op") == {"Role": False, "ServiceRoleArn": False, "IamRoleName": True, + "IamRoles[]": False, "RoleARNUpdate": False, "serviceRoleOverride": False} + + +def test_an_enum_names_no_role(): + m = model({"Op": "In"}, {"In": structure(role="RoleType"), "RoleType": {"type": "string", "enum": ["ADMIN"]}}) + assert r.role_members(m, "Op") == {} + + +def test_nested_lists_maps_and_named_list_members_are_written_as_steps(): + m = model({"Op": "In"}, { + "In": structure(Rule="Rule", Roles="RoleMap", Associated="Associated"), + "Rule": structure(Actions="Actions"), + "Actions": {"type": "list", "member": {"shape": "Action"}}, + "Action": structure(S3Action="S3Action"), + "S3Action": structure(IamRoleArn="String"), + "RoleMap": {"type": "map", "key": {"shape": "String"}, "value": {"shape": "String"}}, + "Associated": {"type": "list", "member": {"shape": "Assoc", "locationName": "AssociatedRole"}}, + "Assoc": structure(RoleArn="String"), + }, protocol="query") + assert r.role_members(m, "Op") == {"Rule.Actions[].S3Action.IamRoleArn": False, "Roles{}": False, + "Associated[AssociatedRole].RoleArn": False} + + +def test_a_member_serialized_under_another_name_is_written_under_it(): + m = model({"Op": "In"}, {"In": structure(RoleArn={"shape": "String", "locationName": "roleArn"})}) + assert r.role_members(m, "Op") == {"roleArn": False} + + +def test_a_member_bound_to_the_uri_a_header_or_the_query_string_is_not_read(): + m = model({"Op": "In"}, {"In": structure(RoleArn={"shape": "String", "location": "uri"}, + BodyRoleArn="String")}, protocol="rest-json") + assert r.role_members(m, "Op") == {"BodyRoleArn": False} + + +def test_a_payload_member_is_the_body(): + m = model({"Op": "In"}, {"In": {"type": "structure", "payload": "Config", + "members": {"Config": {"shape": "Config"}}}, + "Config": structure(RoleArn="String")}, protocol="rest-json") + assert r.role_members(m, "Op") == {"RoleArn": False} + + +@pytest.mark.parametrize("documentation", [ + "The name or Amazon Resource Name (ARN) of the IAM role associated with this job.", + "The short name or full Amazon Resource Name (ARN) of the IAM role.", + "The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler.", + "The name of a service role for this build.", +]) +def test_documentation_saying_a_member_takes_a_name_marks_it_by_name(documentation): + m = model({"Op": "In"}, {"In": structure(Role={"shape": "String", "documentation": documentation})}) + assert r.role_members(m, "Op") == {"Role": True} + + +def test_an_amazon_resource_name_alone_takes_no_name(): + m = model({"Op": "In"}, {"In": structure(RoleArn={"shape": "String", "documentation": + "The Amazon Resource Name of the IAM role assumed."})}) + assert r.role_members(m, "Op") == {"RoleArn": False} + + +def test_a_pattern_that_only_admits_an_arn_takes_no_name(): + m = model({"Op": "In"}, {"In": structure(ExecutionRoleArn={"shape": "RoleArn", "documentation": + "The name of the IAM execution role."}), + "RoleArn": {"type": "string", "pattern": "arn:.+:iam::[0-9]{12}:role/.+"}}) + assert r.role_members(m, "Op") == {"ExecutionRoleArn": False} + + +@pytest.mark.parametrize("protocol", ["ec2", "rest-xml"]) +def test_a_model_whose_requests_are_not_read_has_no_members(protocol): + m = model({"Op": "In"}, {"In": structure(RoleArn="String")}, protocol=protocol) + assert r.role_members(m, "Op") == {} + + +def test_a_member_path_with_a_map_key_exists_only_for_a_key_the_enum_lists(): + m = model({"Op": "In"}, {"In": structure(Definition="Definition"), + "Definition": {"type": "map", "key": {"shape": "Key"}, "value": {"shape": "String"}}, + "Key": {"type": "string", "enum": ["Name", "AssumeRole"]}}) + assert r.member_exists(m, "Op", "Definition{AssumeRole}") + assert not r.member_exists(m, "Op", "Definition{Missing}") + assert not r.member_exists(m, "Op", "Definition[]") + assert not r.member_exists(m, "Op", "Other") + + +# --------------------------------------------------------------------------- # +# One operation's entry +# --------------------------------------------------------------------------- # +SIMPLE = {"svc": model({"CreateThing": "In"}, {"In": structure(RoleArn="String", Roles="RoleList"), + "RoleList": {"type": "list", "member": {"shape": "String"}}})} + + +def test_each_member_goes_to_the_one_service_the_reference_names(corrections): + assert r.entry_for("svc:CreateThing", ["svc"], SIMPLE) == { + "passedTo": ["svc"], + "roles": [{"member": "RoleArn", "passedTo": "svc"}, {"member": "Roles[]", "passedTo": "svc"}]} + + +def test_a_role_passed_to_no_named_service_carries_none(corrections): + assert r.entry_for("svc:CreateThing", [], SIMPLE)["roles"][0] == {"member": "RoleArn"} + + +def test_several_services_need_a_member_service(corrections): + with pytest.raises(ValueError, match="MEMBER_SERVICES"): + r.entry_for("svc:CreateThing", ["svc", "other"], SIMPLE) + corrections.setattr(r, "MEMBER_SERVICES", {"svc:*": {"*": "other"}}) + assert {role["passedTo"] for role in r.entry_for("svc:CreateThing", ["svc", "other"], SIMPLE)["roles"]} == {"other"} + + +def test_hand_and_unread_operations_carry_their_reason_and_no_members(corrections): + corrections.setattr(r, "BY_HAND", {"svc:CreateThing": "an instance profile's roles"}) + assert r.entry_for("svc:CreateThing", ["svc"], SIMPLE) == {"passedTo": ["svc"], + "byHand": "an instance profile's roles"} + corrections.setattr(r, "BY_HAND", {}) + corrections.setattr(r, "NOT_READ", {"svc:CreateThing": "no member of the request names a role"}) + assert r.entry_for("svc:CreateThing", ["svc"], SIMPLE)["notRead"] == "no member of the request names a role" + + +def test_an_exclusion_drops_a_member_and_an_extra_one_adds_it(corrections): + corrections.setattr(r, "EXCLUDED_MEMBERS", {"svc:*": {"Roles[]": "roles a policy is attached to"}}) + corrections.setattr(r, "EXTRA_MEMBERS", {"svc:CreateThing": {"RoleArn": (True, "takes a name")}}) + assert r.entry_for("svc:CreateThing", ["svc"], SIMPLE)["roles"] == [ + {"member": "RoleArn", "passedTo": "svc", "byName": True}] + + +def test_an_extra_member_the_request_does_not_have_fails(corrections): + corrections.setattr(r, "EXTRA_MEMBERS", {"svc:CreateThing": {"Missing.RoleArn": (False, "a typo")}}) + with pytest.raises(ValueError, match="does not have"): + r.entry_for("svc:CreateThing", ["svc"], SIMPLE) + + +def test_an_operation_naming_no_role_must_say_why(corrections): + empty = {"svc": model({"CreateThing": "In"}, {"In": structure(Name="String")})} + with pytest.raises(ValueError, match="NOT_READ"): + r.entry_for("svc:CreateThing", ["svc"], empty) + + +# --------------------------------------------------------------------------- # +# The whole document +# --------------------------------------------------------------------------- # +def write_models(root, models: dict[str, dict]): + for name, value in models.items(): + directory = root / name / "2020-01-01" + directory.mkdir(parents=True) + (directory / "service-2.json").write_text(json.dumps(value), encoding="utf-8") + + +def test_a_built_document_validates_and_matches_botocore(corrections, tmp_path): + write_models(tmp_path, SIMPLE) + document = r.build([reference("svc", {"CreateThing": ["svc"]}), reference("elsewhere", {"Op": ["x"]})], + "test", tmp_path, "botocore test") + assert r.validate(document) == [] + assert r.derive(document, tmp_path) == [] + assert document["namespaces"] == {"svc": ["svc"]} + assert document["otherNamespaces"] == ["elsewhere"] + assert json.loads(r.render(document)) == document + + +def test_a_hand_edited_member_does_not_match_botocore(corrections, tmp_path): + write_models(tmp_path, SIMPLE) + document = r.build([reference("svc", {"CreateThing": ["svc"]})], "test", tmp_path, "botocore test") + document["operations"]["svc:CreateThing"]["roles"].append({"member": "Other", "passedTo": "svc"}) + assert r.validate(document) == [] + assert len(r.derive(document, tmp_path)) == 1 + + +def test_a_correction_naming_an_operation_the_reference_does_not_list_fails(corrections, tmp_path): + write_models(tmp_path, SIMPLE) + corrections.setattr(r, "NOT_READ", {"svc:Gone": "no member of the request names a role"}) + with pytest.raises(ValueError, match="svc:Gone"): + r.build([reference("svc", {"CreateThing": ["svc"]})], "test", tmp_path, "botocore test") + + +def test_an_exclusion_no_operation_has_fails(corrections, tmp_path): + write_models(tmp_path, SIMPLE) + corrections.setattr(r, "EXCLUDED_MEMBERS", {"svc:*": {"Missing": "no longer there"}}) + with pytest.raises(ValueError, match="no operation there has"): + r.build([reference("svc", {"CreateThing": ["svc"]})], "test", tmp_path, "botocore test") + + +def good_document() -> dict: + return {"namespaces": {"svc": ["svc"]}, "operations": { + "svc:A": {"passedTo": ["svc"], "roles": [{"member": "Rule.Actions[].RoleArn", "passedTo": "svc"}]}, + "svc:B": {"passedTo": ["svc"], "byHand": "an instance profile's roles"}, + "svc:C": {"passedTo": [], "notRead": "no member of the request names a role"}}} + + +def test_a_well_formed_document_validates(): + assert r.validate(good_document()) == [] + + +@pytest.mark.parametrize("change, problem", [ + (lambda d: d["operations"]["svc:A"].update(byHand="x"), "exactly one"), + (lambda d: d["operations"]["svc:A"]["roles"][0].update(member="Rule..RoleArn"), "no member path"), + (lambda d: d["operations"]["svc:A"]["roles"][0].update(passedTo="other"), "does not name"), + (lambda d: d["operations"]["svc:A"]["roles"][0].pop("passedTo"), "goes to no service"), + (lambda d: d["operations"]["svc:A"]["roles"][0].update(byName=False), "unknown field"), + (lambda d: d["operations"].update({"other:D": {"passedTo": [], "notRead": "x"}}), "namespace the file reads"), +]) +def test_a_malformed_document_is_rejected(change, problem): + document = good_document() + change(document) + assert any(problem in p for p in r.validate(document)), r.validate(document) + + +def test_verify_fails_on_a_claim_aws_does_not_make_and_reports_an_added_operation(): + vendored = good_document() + upstream = {"svc:A": {"passedTo": ["svc"], "clients": ["svc"]}, + "svc:B": {"passedTo": ["other"], "clients": ["svc"]}, + "svc:D": {"passedTo": ["svc"], "clients": ["svc"]}, + "elsewhere:E": {"passedTo": ["x"], "clients": ["elsewhere"]}} + untrue, added = r.verify_against(vendored, upstream) + assert len(untrue) == 2 and any("svc:B" in u for u in untrue) and any("svc:C" in u for u in untrue) + assert added == ["svc:D"] + + +def test_verify_fails_when_aws_lists_an_operation_for_a_client_the_file_does_not_read(): + untrue, _ = r.verify_against(good_document(), { + "svc:A": {"passedTo": ["svc"], "clients": ["svc", "svcv2"]}, + "svc:B": {"passedTo": ["svc"], "clients": ["svc"]}, + "svc:C": {"passedTo": [], "clients": ["svc"]}}) + assert untrue == ["AWS lists svc:A for ['svc', 'svcv2'], which the file does not read"] + + +def test_the_vendored_file_is_well_formed(): + document = json.loads(r.OUTPUT.read_text(encoding="utf-8")) + assert r.validate(document) == [] + assert document["operations"]["athena:CreateWorkGroup"]["roles"] == [ + {"member": "Configuration.ExecutionRole", "passedTo": "athena"}] + assert document["operations"]["budgets:CreateBudgetAction"]["roles"] == [ + {"member": "ExecutionRoleArn", "passedTo": "budgets"}] + assert document["operations"]["ec2:RunInstances"].get("byHand")