mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(iam): check iam:PassRole from a table generated from the Service Reference (#6422)
Under IAM enforcement a request that names a role is checked for iam:PassRole only where PassedRoles has a case for its operation, so most of the operations AWS's Service Reference lists with iam:PassRole went through without it: a caller allowed to create a CodeBuild project, a Firehose stream, a Glue job or an SSM association could hand it any role in the account. Adding a case per operation took one pull request per few services. The Service Reference names, for each operation, the services its role goes to, but not the request member that names it; botocore's models give the members. tools/aws/regen_iam_passed_roles.py joins the two into src/main/resources/aws/iam-passed-roles.json: every operation listing iam:PassRole in the namespaces Floci serves over JSON, Query and Smithy RPC v2 CBOR, and in the REST services whose routes are authorized as operations, each either read from the table, read by hand in PassedRoles, or not read with a reason. Generation fails on an operation in none of the three. A member names a role when its name ends in Role, RoleArn or RoleName (a plural, or one followed by Update or Override) and it holds a string or a list or map of them, not an enum. A member whose documentation says it takes a role by name is checked on the ARN IAM holds the role under. A role the Service Reference passes to no named service, as it does Cognito's, is checked with no iam:PassedToService. The generator records its corrections with their reasons: members that pass no role (the roles a Budgets action attaches a policy to, a CodePipeline action's role, which the pipeline's role assumes, SSM target accounts' execution roles, the roles a Glue job's generated nodes assume with STS, Firehose's Snowflake role), members the rule does not see (a Cognito user pool's SMS caller roles, a Glue connection's ROLE_ARN property and a view's definer, Service Catalog's AssumeRole and LAUNCH_ROLE keys), and which service a member's role goes to where the reference names several. PassedRoles reads a table member from a JSON or CBOR body, or from Query form parameters in either list form. Its own cases now return null for an operation they do not read, and the table covers the rest. New cases read SNS's role attributes (a topic's delivery status roles, a platform application's, a Firehose subscription's and the SMS one, as the SNS handlers read the map; an attribute with no value names none), a CloudWatch Logs subscription filter policy's RoleArn, a Service Catalog launch constraint's role, by the type Service Catalog holds for the constraint on an update and in any case, since Floci keeps the type as given, and an SWF decision's Lambda role from the attributes its type names. Not read: requests that name no role, roles that are a runbook's parameter, operations whose roles go to several services without the reference saying which member goes where (EMR RunJobFlow, EKS UpdateClusterConfig, CloudWatch Logs CreateImportTask, SageMaker CreateTrainingSession), XML bodies (S3 PutBucketReplication), EC2's RequestSpotFleet, and REST services whose routes no rule maps yet. make iam-passed-roles-check, part of aws-data-check, re-derives every member from the pinned botocore; make iam-passed-roles-verify, part of iam-data-verify, checks every operation against AWS; the IAM data drift workflow now also runs on a change to the table or its generator. PassedRoleNamespacesIntegrationTest fails for a namespace Floci serves that the table neither reads nor names as not read yet.
This commit is contained in:
1 parent
cc1ce89ac0
commit
1276a8857f
15 files changed
+3646
-23
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
+57
-6
@@ -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
|
||||
`<ENDPOINT>SuccessFeedbackRoleArn` and `<ENDPOINT>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/<service>/operation/<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
|
||||
|
||||
@@ -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<String> heldRoleArn(String roleName) {
|
||||
return iamService.findRole(accountId, roleName).map(IamRole::getArn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> serviceCatalogConstraintType(String constraintId) {
|
||||
return firstFound(lookup -> lookup.serviceCatalogConstraintType(constraintId));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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}.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<Step> 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<String, List<Member>> members, Set<String> byHand, Set<String> notRead,
|
||||
Set<String> namespaces, Set<String> notCovered, Set<String> 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<Member> 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<String, List<Member>> members = new LinkedHashMap<>();
|
||||
Set<String> byHand = new LinkedHashSet<>();
|
||||
Set<String> 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<Member> 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<Step> 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<Step> 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());
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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 <ENDPOINT>SuccessFeedbackRoleArn} and
|
||||
* {@code <ENDPOINT>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."
|
||||
*
|
||||
* <p>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<String> SNS_TOPIC_ROLES = Set.of(
|
||||
"ApplicationSuccessFeedbackRoleArn", "ApplicationFailureFeedbackRoleArn",
|
||||
"FirehoseSuccessFeedbackRoleArn", "FirehoseFailureFeedbackRoleArn",
|
||||
"HTTPSuccessFeedbackRoleArn", "HTTPFailureFeedbackRoleArn",
|
||||
"LambdaSuccessFeedbackRoleArn", "LambdaFailureFeedbackRoleArn",
|
||||
"SQSSuccessFeedbackRoleArn", "SQSFailureFeedbackRoleArn");
|
||||
private static final Set<String> SNS_SUBSCRIPTION_ROLES = Set.of("SubscriptionRoleArn");
|
||||
private static final Set<String> SNS_PLATFORM_ROLES = Set.of("SuccessFeedbackRoleArn", "FailureFeedbackRoleArn");
|
||||
private static final Set<String> 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<String, String> SWF_EXECUTION_DECISIONS = Map.of(
|
||||
"ContinueAsNewWorkflowExecution", "continueAsNewWorkflowExecutionDecisionAttributes",
|
||||
"StartChildWorkflowExecution", "startChildWorkflowExecutionDecisionAttributes");
|
||||
|
||||
/** The RDS operations whose request takes a {@code MonitoringRoleArn}. */
|
||||
private static final Set<String> 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<String> heldRoleArn(String roleName);
|
||||
|
||||
/** The type of the Service Catalog constraint {@code constraintId}; empty when there is none. */
|
||||
Optional<String> 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<PassedRole> of(String action, ContainerRequestContext ctx, Lookups lookups) {
|
||||
List<PassedRole> 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<PassedRole> 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<PassedRole> fromTable(List<PassedRoleMembers.Member> members, ContainerRequestContext ctx,
|
||||
Lookups lookups) {
|
||||
if (members == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
JsonNode body = form.isEmpty() ? jsonBody(ctx) : null;
|
||||
List<PassedRole> passed = new ArrayList<>();
|
||||
for (PassedRoleMembers.Member member : members) {
|
||||
List<String> 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<PassedRoleMembers.Step> steps, int index, List<String> 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<String> heldOrNamedRoles(List<String> roles, Lookups lookups) {
|
||||
List<String> 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<PassedRole> snsAttributeRoles(ContainerRequestContext ctx, String map, Set<String> roleAttributes) {
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
Map<String, String> 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<String> 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<PassedRole> snsAttributeRole(ContainerRequestContext ctx, Set<String> roleAttributes) {
|
||||
Map<String, String> 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<PassedRole> 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<PassedRole> 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<String> 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<PassedRole> swfDecisionRoles(JsonNode body) {
|
||||
JsonNode decisions = body == null ? null : body.get("decisions");
|
||||
if (decisions == null || !decisions.isArray()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> 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.
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<String> serviceCatalogConstraintType(String constraintId) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -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<String> 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();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<String> instanceProfileRoleArns(String profileName, String profileArn) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> taskDefinitionRoles(String reference) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> stackSetPermissionModel(String stackSetName) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> launchTemplateInstanceProfile(String templateId, String templateName, String version) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> launchConfigurationInstanceProfile(String instanceId) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> 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<String> heldRoleArn(String roleName) {
|
||||
return NAMED.equals(roleName) ? Optional.of(HELD) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> 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<DynamicTest> 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<DynamicTest> 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<DynamicTest> 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<Step> 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<String> 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;
|
||||
}
|
||||
}
|
||||
+35
@@ -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<String> served = new TreeSet<>();
|
||||
for (ServiceDescriptor descriptor : catalog.all()) {
|
||||
for (String scope : descriptor.credentialScopes()) {
|
||||
served.add(catalog.canonicalCredentialScope(scope));
|
||||
}
|
||||
}
|
||||
Set<String> unread = new TreeSet<>(served);
|
||||
unread.retainAll(PassedRoleMembers.table().otherNamespaces());
|
||||
assertEquals(Set.of(), unread, "add these to NAMESPACES or NOT_COVERED in tools/aws/regen_iam_passed_roles.py");
|
||||
}
|
||||
}
|
||||
@@ -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<String> heldRoleArn(String roleName) {
|
||||
return "app-role".equals(roleName) ? Optional.of(ROLES + "app/app-role") : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> 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);
|
||||
}
|
||||
|
||||
+354
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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/<svc>/<svc>.json
|
||||
|
||||
- botocore's model of each SDK client the reference lists the operation for (Apache-2.0,
|
||||
https://github.com/boto/botocore, the pinned release), which gives the request's members 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 <dir> # read saved <svc>.json files
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from regen_iam_authorized_actions import 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"|(?<!Resource )\bname of (the |a |an )?(\S+ ){0,5}role\b",
|
||||
re.IGNORECASE)
|
||||
# The protocols whose requests PassedRoles reads: form parameters, or a JSON or CBOR body.
|
||||
READ_PROTOCOLS = {"json", "query", "rest-json", "smithy-rpc-v2-cbor"}
|
||||
# How a vendored member path is written: dotted segments, a list step as `[]` or `[Name]` when its
|
||||
# shape names its members, a map step as `{}` for every value or `{KEY}` for one key's.
|
||||
MEMBER_PATH_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*(\[[A-Za-z0-9_]*\]|\{[A-Za-z0-9_]*\})?"
|
||||
r"(\.[A-Za-z][A-Za-z0-9_]*(\[[A-Za-z0-9_]*\]|\{[A-Za-z0-9_]*\})?)*$")
|
||||
NAMESPACE_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
|
||||
OPERATION_RE = re.compile(r"^[a-z0-9-]+:[A-Za-z][A-Za-z0-9]{0,127}$")
|
||||
SERVICE_RE = re.compile(r"^[a-z0-9][a-z0-9.-]*$")
|
||||
|
||||
BODY_LOCATIONS = (None, "")
|
||||
|
||||
# Operations PassedRoles reads itself, and what it reads.
|
||||
BY_HAND = {
|
||||
"autoscaling:CreateAutoScalingGroup": "the roles of each launch template's instance profile, and the "
|
||||
"service-linked and lifecycle hook roles",
|
||||
"autoscaling:CreateLaunchConfiguration": "the roles of the instance profile it names or takes from an "
|
||||
"instance",
|
||||
"autoscaling:PutLifecycleHook": "the hook's role",
|
||||
"autoscaling:UpdateAutoScalingGroup": "the roles of each launch template's instance profile, and the "
|
||||
"service-linked and lifecycle hook roles",
|
||||
"application-autoscaling:RegisterScalableTarget": "the scalable target's role",
|
||||
"cloudformation:ContinueUpdateRollback": "the stack's service role",
|
||||
"cloudformation:CreateChangeSet": "the stack's service role",
|
||||
"cloudformation:CreateStack": "the stack's service role",
|
||||
"cloudformation:CreateStackSet": "the administration role, named or the default one",
|
||||
"cloudformation:DeleteStack": "the stack's service role",
|
||||
"cloudformation:UpdateStack": "the stack's service role",
|
||||
"cloudformation:UpdateStackSet": "the administration role, by the StackSet's permission model",
|
||||
"dms:CreateEndpoint": "the endpoint's role and the roles of the settings structures DMS stores",
|
||||
"dms:CreateReplicationInstance": "the role of the Kerberos settings",
|
||||
"dms:ModifyEndpoint": "the endpoint's role and the roles of the settings structures DMS stores",
|
||||
"dms:ModifyReplicationInstance": "the role of the Kerberos settings",
|
||||
"ec2:AssociateIamInstanceProfile": "the roles of the instance profile it names",
|
||||
"ec2:CreateFlowLogs": "the delivery role",
|
||||
"ec2:CreateLaunchTemplate": "the roles of the instance profile the template names",
|
||||
"ec2:CreateLaunchTemplateVersion": "the roles of the instance profile the template names",
|
||||
"ec2:ReplaceIamInstanceProfileAssociation": "the roles of the instance profile it names",
|
||||
"ec2:RequestSpotInstances": "the roles of the instance profile it names",
|
||||
"ec2:RunInstances": "the roles of the instance profile it names",
|
||||
"ecs:CreateCapacityProvider": "the infrastructure role, by name or ARN",
|
||||
"ecs:CreateService": "the task definition's roles and the service's infrastructure roles",
|
||||
"ecs:CreateTaskSet": "the task definition's roles",
|
||||
"ecs:RegisterTaskDefinition": "the task and task execution roles, by name or ARN",
|
||||
"ecs:RunTask": "the task definition's roles, their overrides and the volumes' infrastructure role",
|
||||
"ecs:StartTask": "the task definition's roles, their overrides and the volumes' infrastructure role",
|
||||
"ecs:UpdateCapacityProvider": "the infrastructure role, by name or ARN",
|
||||
"ecs:UpdateService": "the task definition's roles and the service's infrastructure roles",
|
||||
"eks:CreateAccessEntry": "the principal, for the node types alone",
|
||||
"eks:CreateAddon": "the service account role and each Pod Identity association's role",
|
||||
"eks:CreateCluster": "the cluster role",
|
||||
"eks:CreateFargateProfile": "the pod execution role",
|
||||
"eks:CreateNodegroup": "the node role",
|
||||
"eks:CreatePodIdentityAssociation": "the association's role, not its target role",
|
||||
"eks:UpdateAddon": "the service account role and each Pod Identity association's role",
|
||||
"eks:UpdatePodIdentityAssociation": "the association's role, not its target role",
|
||||
"events:PutRule": "the rule's role",
|
||||
"events:PutTargets": "each target's role",
|
||||
"iam:AddRoleToInstanceProfile": "the role it adds, on the ARN IAM holds it under",
|
||||
"lambda:CreateFunction": "the execution role",
|
||||
"lambda:CreateMicrovmImage": "the build role",
|
||||
"lambda:CreateNetworkConnector": "the operator role",
|
||||
"lambda:CreateWebFunction": "the execution role",
|
||||
"lambda:CreateWebFunctionRevision": "the execution role",
|
||||
"lambda:RunMicrovm": "the execution role",
|
||||
"lambda:UpdateFunctionConfiguration": "the execution role",
|
||||
"lambda:UpdateMicrovmImage": "the build role",
|
||||
"lambda:UpdateNetworkConnector": "the operator role",
|
||||
"pipes:CreatePipe": "the pipe's role",
|
||||
"pipes:UpdatePipe": "the pipe's role",
|
||||
"rds:AddRoleToDBCluster": "the role it adds",
|
||||
"rds:AddRoleToDBInstance": "the role it adds",
|
||||
"rds:CreateDBCluster": "the directory, monitoring and associated roles",
|
||||
"rds:CreateDBInstance": "the directory and monitoring roles",
|
||||
"rds:CreateDBInstanceReadReplica": "the directory and monitoring roles",
|
||||
"rds:CreateDBProxy": "the proxy's role",
|
||||
"rds:ModifyDBCluster": "the directory and monitoring roles",
|
||||
"rds:ModifyDBInstance": "the directory and monitoring roles",
|
||||
"rds:ModifyDBProxy": "the proxy's role",
|
||||
"rds:ModifyOptionGroup": "the role each option takes in its IAM_ROLE_ARN setting",
|
||||
"rds:RemoveRoleFromDBCluster": "the role it removes",
|
||||
"rds:RemoveRoleFromDBInstance": "the role it removes",
|
||||
"rds:RestoreDBClusterFromSnapshot": "the directory, monitoring and associated roles",
|
||||
"rds:RestoreDBClusterToPointInTime": "the directory, monitoring and associated roles",
|
||||
"rds:RestoreDBInstanceFromDBSnapshot": "the directory role",
|
||||
"rds:RestoreDBInstanceToPointInTime": "the directory role",
|
||||
"rds:StartExportTask": "the export role",
|
||||
"redshift:CreateCluster": "the roles it associates",
|
||||
"redshift:ModifyClusterIamRoles": "the roles it associates",
|
||||
"redshift:RestoreFromClusterSnapshot": "the roles it associates",
|
||||
"redshift-serverless:CreateNamespace": "the namespace's roles and its default",
|
||||
"redshift-serverless:CreateScheduledAction": "the scheduled action's role",
|
||||
"redshift-serverless:UpdateNamespace": "the namespace's roles and its default",
|
||||
"redshift-serverless:UpdateScheduledAction": "the scheduled action's role",
|
||||
"scheduler:CreateSchedule": "the target's role",
|
||||
"scheduler:UpdateSchedule": "the target's role",
|
||||
"states:CreateStateMachine": "the state machine's role",
|
||||
"states:UpdateStateMachine": "the state machine's role",
|
||||
}
|
||||
|
||||
BY_HAND.update({
|
||||
"logs:PutAccountPolicy": "the role a subscription filter policy's document names",
|
||||
"servicecatalog:CreateConstraint": "a launch constraint's role, from its parameters document",
|
||||
"servicecatalog:UpdateConstraint": "a launch constraint's role, by the type the constraint holds",
|
||||
"sns:CreatePlatformApplication": "the delivery status roles among its attributes",
|
||||
"sns:CreateTopic": "the delivery status roles among its attributes",
|
||||
"sns:SetPlatformApplicationAttributes": "the delivery status roles among its attributes",
|
||||
"sns:SetSMSAttributes": "the delivery status role among its attributes",
|
||||
"sns:SetSubscriptionAttributes": "the subscription role, when it is the attribute set",
|
||||
"sns:SetTopicAttributes": "a delivery status role, when it is the attribute set",
|
||||
"sns:Subscribe": "the subscription role among its attributes",
|
||||
"swf:RespondDecisionTaskCompleted": "the Lambda role of each decision that starts an execution, read from "
|
||||
"the attributes its decisionType names",
|
||||
})
|
||||
|
||||
NO_ROLE_MEMBER = "no member of the request names a role"
|
||||
RUNBOOK_PARAMETER = "the role is a parameter of the runbook it runs, not a member of the request"
|
||||
XML_BODY = "the request body is XML, which PassedRoles does not read"
|
||||
|
||||
# Operations whose request names no role this file can read.
|
||||
NOT_READ = {
|
||||
"config:PutConformancePack": NO_ROLE_MEMBER,
|
||||
"config:PutOrganizationConformancePack": NO_ROLE_MEMBER,
|
||||
"config:PutRemediationConfigurations": RUNBOOK_PARAMETER,
|
||||
"dms:CreateInstanceProfile": NO_ROLE_MEMBER,
|
||||
"dms:ModifyInstanceProfile": NO_ROLE_MEMBER,
|
||||
"ec2:RequestSpotFleet": "the request names its roles in EC2's own protocol, one of them as an instance profile",
|
||||
"ecs:CreateDaemon": "the roles are the daemon task definition's, which only a lookup finds",
|
||||
"ecs:CreateGateway": "botocore's model has no such operation",
|
||||
"ecs:UpdateDaemon": "the roles are the daemon task definition's, which only a lookup finds",
|
||||
"ecs:UpdateGateway": "botocore's model has no such operation",
|
||||
"eks:UpdateClusterConfig": "the reference passes the node role to ec2 or eks and nothing says which",
|
||||
"elasticmapreduce:RunJobFlow": "JobFlowRole names an instance profile, and the reference passes the roles "
|
||||
"to three services without saying which goes where",
|
||||
"elasticmapreduce:UpdateStudio": NO_ROLE_MEMBER,
|
||||
"glue:GetJob": NO_ROLE_MEMBER,
|
||||
"glue:GetJobs": NO_ROLE_MEMBER,
|
||||
"lambda:AddEventSource": "botocore's model has no such operation",
|
||||
"logs:CreateImportTask": "the reference passes the role to cloudtrail or logs and nothing says which",
|
||||
"rds:CreateBlueGreenDeployment": NO_ROLE_MEMBER,
|
||||
"s3:CreateAccessGrantsLocation": XML_BODY,
|
||||
"s3:PutBucketReplication": XML_BODY,
|
||||
"redshift:ModifyLakehouseConfiguration": NO_ROLE_MEMBER,
|
||||
"redshift-serverless:UpdateLakehouseConfiguration": NO_ROLE_MEMBER,
|
||||
"sagemaker:CreateTrainingSession": "the reference passes the role to sagemaker or training-session.sagemaker "
|
||||
"and nothing says which",
|
||||
"sagemaker:CreateTransformJob": NO_ROLE_MEMBER,
|
||||
"sagemaker:ImportHubContent": NO_ROLE_MEMBER,
|
||||
"ssm:CreateDocument": NO_ROLE_MEMBER,
|
||||
"ssm:DescribeAutomationStepExecutions": NO_ROLE_MEMBER,
|
||||
"ssm:GetAutomationExecution": NO_ROLE_MEMBER,
|
||||
"ssm:StartAutomationExecution": RUNBOOK_PARAMETER,
|
||||
"ssm:StartChangeRequestExecution": RUNBOOK_PARAMETER,
|
||||
"ssm:UpdateDocument": NO_ROLE_MEMBER,
|
||||
"ssm:UpdateServiceSetting": "a role is only ever a setting's value, which the request names by SettingId",
|
||||
}
|
||||
|
||||
# A member the rule reads that passes no role, by operation, or by namespace for all its operations.
|
||||
EXCLUDED_MEMBERS = {
|
||||
# "A list of roles to be attached": the roles the action attaches a policy to.
|
||||
"budgets:*": {"Definition.IamActionDefinition.Roles[]": "the roles the action attaches a policy to"},
|
||||
# "This is assumed through the roleArn for the pipeline": the pipeline's role assumes it.
|
||||
"codepipeline:*": {"pipeline.stages[].actions[].roleArn": "assumed with the pipeline's role, not passed"},
|
||||
# "The Snowflake role you wish to configure".
|
||||
"firehose:*": {
|
||||
"SnowflakeDestinationConfiguration.SnowflakeRoleConfiguration.SnowflakeRole": "a Snowflake role",
|
||||
"SnowflakeDestinationUpdate.SnowflakeRoleConfiguration.SnowflakeRole": "a Snowflake role",
|
||||
},
|
||||
# Glue's code-generated job nodes: "the role to assume using AWS Security Token Service (AWS STS)" for
|
||||
# a Kinesis source and "the Amazon Web Services Security Token Service (STS) role to assume" for a
|
||||
# DynamoDB one, which the job's own role assumes, and the role a Redshift node's temporary directory
|
||||
# is read and written with, which the Redshift cluster holds.
|
||||
"glue:*": {
|
||||
prefix + node: reason
|
||||
for prefix in ("CodeGenConfigurationNodes{}.", "JobUpdate.CodeGenConfigurationNodes{}.")
|
||||
for node, reason in (
|
||||
("CatalogKinesisSource.StreamingOptions.RoleArn", "assumed with STS by the job's role"),
|
||||
("DirectKinesisSource.StreamingOptions.RoleArn", "assumed with STS by the job's role"),
|
||||
("DynamoDBELTConnectorSource.ConnectionOptions.DynamodbStsRoleArn", "assumed with STS by the job's role"),
|
||||
("RedshiftSource.TmpDirIAMRole", "a role the Redshift cluster holds"),
|
||||
("RedshiftTarget.TmpDirIAMRole", "a role the Redshift cluster holds"),
|
||||
)
|
||||
},
|
||||
# "The IAM role attached to your Redshift cluster that Amazon SageMaker uses to generate datasets":
|
||||
# a role the cluster already holds. "The Amazon Resource Name (ARN) of the SageMaker model registry
|
||||
# account": a role in another account.
|
||||
"sagemaker:*": {
|
||||
"ProcessingInputs[].DatasetDefinition.RedshiftDatasetDefinition.ClusterRoleArn":
|
||||
"a role the Redshift cluster already holds",
|
||||
"DefaultUserSettings.CanvasAppSettings.ModelRegisterSettings.CrossAccountModelRegisterRoleArn":
|
||||
"a role in the model registry's account",
|
||||
"UserSettings.CanvasAppSettings.ModelRegisterSettings.CrossAccountModelRegisterRoleArn":
|
||||
"a role in the model registry's account",
|
||||
# "the IAM roles that the execution role of SageMaker can assume", and those "used by the Amazon
|
||||
# EMR cluster instances or job execution environments".
|
||||
**{prefix + "JupyterLabAppSettings.EmrSettings." + member: reason
|
||||
for prefix in ("DefaultSpaceSettings.", "DefaultUserSettings.", "UserSettings.")
|
||||
for member, reason in (("AssumableRoleArns[]", "assumed by the execution role"),
|
||||
("ExecutionRoleArns[]", "the EMR clusters' own roles"))},
|
||||
# "The name of the in-app role within the SageMaker Partner AI App".
|
||||
"ApplicationConfig.RoleGroupAssignments[].RoleName": "an in-app role, not an IAM one",
|
||||
},
|
||||
# The Automation execution role of each target account, which the run assumes there.
|
||||
"ssm:*": {
|
||||
"TargetLocations[].ExecutionRoleName": "a role in each target account",
|
||||
"Entries[].TargetLocations[].ExecutionRoleName": "a role in each target account",
|
||||
},
|
||||
}
|
||||
|
||||
# A member naming a role that the rule does not see: (byName, why it names one).
|
||||
_SNS_CALLER = ("SnsCallerArn", "\"the ARN of the IAM role in your Amazon Web Services account that Amazon Cognito "
|
||||
"will use to send SMS messages\"")
|
||||
_EUMS_CALLER = ("CallerArn", "\"The ARN of the IAM role that Amazon Cognito assumes to send SMS messages\"")
|
||||
# Glue's API reference: "ROLE_ARN - The role to be used for running queries."
|
||||
_GLUE_CONNECTION_ROLE = (False, "the ROLE_ARN connection property, \"The role to be used for running queries\"")
|
||||
# Lake Formation's view prerequisites: the role that defines a view needs "The iam:PassRole permission
|
||||
# for AWS Glue and Lake Formation".
|
||||
_GLUE_VIEW_DEFINER = (False, "the role that defines the view")
|
||||
EXTRA_MEMBERS = {
|
||||
"cognito-idp:CreateUserPool": {
|
||||
"SmsConfiguration." + _SNS_CALLER[0]: (False, _SNS_CALLER[1]),
|
||||
"SmsConfiguration.EumsSms." + _EUMS_CALLER[0]: (False, _EUMS_CALLER[1]),
|
||||
},
|
||||
"cognito-idp:UpdateUserPool": {
|
||||
"SmsConfiguration." + _SNS_CALLER[0]: (False, _SNS_CALLER[1]),
|
||||
"SmsConfiguration.EumsSms." + _EUMS_CALLER[0]: (False, _EUMS_CALLER[1]),
|
||||
},
|
||||
"cognito-idp:SetUserPoolMfaConfig": {
|
||||
"SmsMfaConfiguration.SmsConfiguration." + _SNS_CALLER[0]: (False, _SNS_CALLER[1]),
|
||||
"SmsMfaConfiguration.SmsConfiguration.EumsSms." + _EUMS_CALLER[0]: (False, _EUMS_CALLER[1]),
|
||||
},
|
||||
"glue:CreateConnection": {"ConnectionInput.ConnectionProperties{ROLE_ARN}": _GLUE_CONNECTION_ROLE},
|
||||
"glue:UpdateConnection": {"ConnectionInput.ConnectionProperties{ROLE_ARN}": _GLUE_CONNECTION_ROLE},
|
||||
"glue:TestConnection": {"TestConnectionInput.ConnectionProperties{ROLE_ARN}": _GLUE_CONNECTION_ROLE},
|
||||
"glue:CreateTable": {"TableInput.ViewDefinition.Definer": _GLUE_VIEW_DEFINER},
|
||||
"glue:UpdateTable": {"TableInput.ViewDefinition.Definer": _GLUE_VIEW_DEFINER},
|
||||
# Keys the model's own enums give the maps: ServiceActionDefinitionKey's AssumeRole and
|
||||
# PropertyKey's LAUNCH_ROLE.
|
||||
"servicecatalog:CreateServiceAction": {"Definition{AssumeRole}": (False, "the role the action runs as")},
|
||||
"servicecatalog:UpdateServiceAction": {"Definition{AssumeRole}": (False, "the role the action runs as")},
|
||||
"servicecatalog:UpdateProvisionedProductProperties": {
|
||||
"ProvisionedProductProperties{LAUNCH_ROLE}": (False, "the role the product is launched with"),
|
||||
},
|
||||
}
|
||||
|
||||
# The service a member's role goes to, for an operation the reference lists with several; "*" for
|
||||
# every member.
|
||||
ECS_INFRASTRUCTURE = "ecs"
|
||||
ECS_TASKS = "ecs-tasks"
|
||||
MEMBER_SERVICES = {
|
||||
# "The Amazon Resource Name (ARN) for CodePipeline to use", and "The pipeline role ARN associated
|
||||
# with the rule".
|
||||
"codepipeline:*": {
|
||||
"pipeline.roleArn": "codepipeline",
|
||||
"pipeline.stages[].beforeEntry.conditions[].rules[].roleArn": "codepipeline",
|
||||
"pipeline.stages[].onFailure.conditions[].rules[].roleArn": "codepipeline",
|
||||
"pipeline.stages[].onSuccess.conditions[].rules[].roleArn": "codepipeline",
|
||||
},
|
||||
# ECS infrastructure roles go to ecs, task and task execution roles to ecs-tasks, as PassedRoles'
|
||||
# ECS cases pass them.
|
||||
"ecs:*": {
|
||||
"executionRoleArn": ECS_TASKS,
|
||||
"taskRoleArn": ECS_TASKS,
|
||||
"infrastructureRoleArn": ECS_INFRASTRUCTURE,
|
||||
},
|
||||
# rds-preview is the principal of RDS's preview environment; PassedRoles' RDS cases pass to rds.
|
||||
"rds:*": {"*": "rds"},
|
||||
}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# The Service Reference: which operations pass a role, to which services
|
||||
# --------------------------------------------------------------------------- #
|
||||
def passed_role_operations(documents: list[dict]) -> dict[str, dict]:
|
||||
"""Every operation of every namespace that lists iam:PassRole, with the services the role goes
|
||||
to, as `<service>` 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<name>[A-Za-z][A-Za-z0-9_]*)(?:\[(?P<list>[A-Za-z0-9_]*)\]|\{(?P<key>[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 <service>.json reference files instead of fetching them")
|
||||
parser.add_argument("--botocore-data", type=Path, default=None, help="botocore data directory")
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.check or args.verify:
|
||||
if not args.output.exists():
|
||||
print(f"error: {args.output} does not exist", file=sys.stderr)
|
||||
return 1
|
||||
document = json.loads(args.output.read_text(encoding="utf-8"))
|
||||
problems = validate(document)
|
||||
if not problems and args.check:
|
||||
data, _ = resolve_botocore_data(args.botocore_data)
|
||||
problems = derive(document, data)
|
||||
for problem in problems:
|
||||
print(f"error: {problem}", file=sys.stderr)
|
||||
if problems:
|
||||
return 1
|
||||
entries = len(document["operations"])
|
||||
if args.check:
|
||||
print(f"{_shown(args.output)} matches botocore ({entries} operations over "
|
||||
f"{len(document['namespaces'])} namespaces)")
|
||||
return 0
|
||||
try:
|
||||
documents, provenance = fetch_references(args.source_dir)
|
||||
upstream = 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())
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user