fix(iam): check iam:PassRole on the roles an EMR RunJobFlow request names (#9587)

AWS's Service Reference lists iam:PassRole for RunJobFlow, passing its
roles to application-autoscaling.amazonaws.com, ec2.amazonaws.com and
elasticmapreduce.amazonaws.com without saying which member's role goes
where, and JobFlowRole names an instance profile rather than a role.
The passed-roles table left the operation unread, so a caller allowed
elasticmapreduce:RunJobFlow could launch a cluster with any service role
and any instance profile.

A new vendored source, tools/aws/sources/emr-roles.json, written by its
own script from the EMR API reference, management guide and AWS CLI
reference, gives each member's role. The guide's page of each role names
its default role ("The default role name is EMR_EC2_DefaultRole"), and
the full access policy it gives users passes each default role to one
service ("iam:PassedToService": "ec2.amazonaws.com*"). The API reference
calls JobFlowRole an instance profile ("Also called instance profile and
Amazon EC2 role"), and the CLI reference's create-cluster examples give
the roles by name (--service-role EMR_DefaultRole). The steps' runtime
role, StepExecutionRoleArn, is not passed: "You can control access to
the runtime role with the condition key elasticmapreduce:ExecutionRoleArn."

The generator reads the source through ROLE_SOURCES, as it reads EKS's,
now taking a documented iam:PassedToService over a trust policy, a member
by name or as an instance profile where the source says so, and leaving
out a member whose role a condition key controls. RunJobFlow moves out of
notRead: ServiceRole to elasticmapreduce.amazonaws.com and AutoScalingRole
to application-autoscaling.amazonaws.com, each by name or ARN, and the
roles of the instance profile JobFlowRole names, by name or ARN, to
ec2.amazonaws.com, found with the instance-profile lookup RunInstances
already uses. A profile IAM does not hold passes no role, as Floci's EMR
already reads JobFlowRole. An instance-profile member is not read for a
call with no request of its own, which has no such lookup.

The instance profile is now found one way everywhere it is used
(IamService.instanceProfileNamed): by its name, or by its own ARN, path
and account included. IAM's passed-role check, EMR's step role and an
EC2 instance's credentials each read it their own way, and EMR kept only
the name after an ARN's last slash. A JobFlowRole ARN of another account
or path then found no role to check but ran the steps as the local
profile's role.

A member's JSON value is now read as the text a handler reads it as, a
number or a Boolean included, as the request resources and condition
keys already read a body's values. The passed-roles reader took strings
alone, while EMR takes "JobFlowRole":123456 as the profile 123456, so a
role named by a number went unchecked.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-11-27 08:11:04 -04:00
1 parent ee35a50413
commit 1a91dbda76
19 files changed
+725 -58

No files matched your search

+3
View File
@@ -55,6 +55,9 @@ on:
- 'tools/aws/sources/eks-roles.json'
- 'tools/aws/fetch_eks_roles.py'
- 'tools/aws/test_fetch_eks_roles.py'
- 'tools/aws/sources/emr-roles.json'
- 'tools/aws/fetch_emr_roles.py'
- 'tools/aws/test_fetch_emr_roles.py'
- 'src/main/resources/aws/iam-passed-network-connectors.json'
- 'tools/aws/regen_iam_passed_network_connectors.py'
- 'tools/aws/test_regen_iam_passed_network_connectors.py'
+2 -1
View File
@@ -623,7 +623,8 @@ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.js
tools/aws/fetch_s3_required_actions.py tools/aws/test_fetch_s3_required_actions.py
IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \
tools/aws/test_regen_iam_passed_roles.py tools/aws/sources/eks-roles.json tools/aws/fetch_eks_roles.py \
tools/aws/test_fetch_eks_roles.py
tools/aws/test_fetch_eks_roles.py tools/aws/sources/emr-roles.json tools/aws/fetch_emr_roles.py \
tools/aws/test_fetch_emr_roles.py
IAM_PASSED_NETWORK_CONNECTORS_PATHS := src/main/resources/aws/iam-passed-network-connectors.json \
tools/aws/regen_iam_passed_network_connectors.py $(IAM_PASSED_ROLES_GENERATOR) \
tools/aws/test_regen_iam_passed_network_connectors.py
+18 -4
View File
@@ -3090,6 +3090,19 @@ role each passes:
entry with type EC2_LINUX or EC2_WINDOWS, the IAM principal creating the access entry must have
the iam:PassRole permission." `CreateCapability`, `UpdateCapability` and `RegisterCluster`, which
Floci does not serve, are checked from the table below.
- **EMR:** `RunJobFlow` passes `ServiceRole` to `elasticmapreduce.amazonaws.com`, `AutoScalingRole`
to `application-autoscaling.amazonaws.com`, each by its name or its ARN, and the roles of the
instance profile `JobFlowRole` names, by its name or its ARN, to `ec2.amazonaws.com`, all read from
the table below. The Service Reference passes its roles to the three services without saying which
member's goes where, so a vendored source, `tools/aws/sources/emr-roles.json`, written by
`tools/aws/fetch_emr_roles.py` from the EMR API reference, management guide and the AWS CLI
reference, gives each member's role: the guide's page of each role names its default role ("The
default role name is EMR_EC2_DefaultRole"), the full access policy it gives users passes each
default role to one service (`"iam:PassedToService": "ec2.amazonaws.com*"`), the API reference
calls `JobFlowRole` an instance profile ("Also called instance profile and Amazon EC2 role"), and
the CLI reference's examples give the roles by name (`--service-role EMR_DefaultRole`). The steps'
runtime role, `StepExecutionRoleArn`, is not passed: "You can control access to the runtime role
with the condition key elasticmapreduce:ExecutionRoleArn."
- **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
@@ -3157,7 +3170,9 @@ botocore's models, `src/main/resources/aws/iam-passed-roles.json`. A request mem
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, from Query form parameters, in either list form, or from a REST-XML body by the elements
botocore names, and its role is passed to the service the Service Reference names. Form parameters
botocore names, and its role is passed to the service the Service Reference names. A JSON number or
Boolean in such a member is read as the text a handler reads it as, so `"JobFlowRole":123456` names
the instance profile `123456`, as EMR takes it. Form parameters
are read only from a request the Query protocol dispatches, a form posted to the root path, so a
request to another protocol's route is read as its handler reads it whatever `Content-Type` it is
sent with: an S3 replication configuration sent as a form is still read as its XML. The table is keyed
@@ -3200,9 +3215,8 @@ when the caller may not pass the role.
- Not read: an operation whose request names no role (SSM `CreateDocument` and CloudWatch Logs
`StartQuery`, for two); 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, CloudWatch Logs `CreateImportTask`); and one
the botocore
passes roles from to several services without saying which member goes where (CloudWatch Logs
`CreateImportTask`); and one the botocore
models Floci is pinned to do not have yet (SSM `RegisterDefaultHostManagementConfiguration`,
Kinesis Analytics `ImportSnapshot`, Secrets Manager `AssociateCrossAccountReplica`), whose role
the generator reads as soon as a release that has it is pinned. EC2's `RequestSpotFleet` names
@@ -1191,9 +1191,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
/** The ARNs of the roles the instance profile, named by {@code name} or {@code arn}, holds. */
private List<String> instanceProfileRoleArns(String accountId, String name, String arn) {
String profileName = arn != null ? arn.substring(arn.lastIndexOf('/') + 1) : name;
return iamService.findInstanceProfile(accountId, profileName)
.filter(profile -> arn == null || arn.equals(profile.getArn()))
return IamService.instanceProfileNamed(iamService, accountId, arn != null ? arn : name)
.map(profile -> profile.getRoleNames().stream()
.flatMap(roleName -> iamService.findRole(accountId, roleName).stream())
.map(IamRole::getArn)
@@ -52,9 +52,11 @@ final class PassedRoleMembers {
/**
* 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.
* the form parameters the Query protocol sends the member as; null for a member it cannot carry. A member
* that names an instance profile ({@code instanceProfile}), by its name or its ARN, passes the profile's roles.
*/
record Member(String path, List<Step> steps, Pattern queryKeys, String passedTo, boolean byName) {
record Member(String path, List<Step> steps, Pattern queryKeys, String passedTo, boolean byName,
boolean instanceProfile) {
}
/** The file: the members of each operation read from it, and the operations read by hand. */
@@ -118,7 +120,8 @@ final class PassedRoleMembers {
+ ", which is no member path");
}
String passedTo = role.hasNonNull("passedTo") ? role.get("passedTo").asText() : null;
return new Member(path, steps, queryKeys(steps), passedTo, role.path("byName").asBoolean(false));
return new Member(path, steps, queryKeys(steps), passedTo, role.path("byName").asBoolean(false),
role.path("instanceProfile").asBoolean(false));
}
/** The steps of a vendored member path; null when {@code path} is none. */
@@ -16,6 +16,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
@@ -75,6 +76,11 @@ import java.util.regex.Pattern;
* an access entry with type EC2_LINUX or EC2_WINDOWS, the IAM principal creating the access entry must
* have the iam:PassRole permission."
*
* <p>An EMR cluster's service and automatic scaling roles, given by name or ARN, and the roles of the instance
* profile its {@code JobFlowRole} names are read from the table, to the services the vendored EMR role source gives
* them: {@code elasticmapreduce.amazonaws.com}, {@code application-autoscaling.amazonaws.com} and
* {@code ec2.amazonaws.com}.
*
* <p>A CloudFormation stack's service role is checked where a request names it, and not on later
* operations that reuse it: CloudFormation "uses this role even if the users don't have permission
* to pass it". A self-managed StackSet that names no administration role passes the default one:
@@ -349,12 +355,13 @@ final class PassedRoles {
return List.of();
}
UnaryOperator<String> named = name -> lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name));
Function<String, List<String>> profiles = profile -> instanceProfileRoles(lookups, profile);
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
JsonNode body = form.isEmpty() ? jsonBody(ctx) : null;
if (form.isEmpty() && body == null) {
return fromXml(members, IamConditionContextResolver.bodyText(ctx), named);
return fromXml(members, IamConditionContextResolver.bodyText(ctx), named, profiles);
}
return fromTable(members, form, body, named);
return fromTable(members, form, body, named, profiles);
}
/**
@@ -365,7 +372,7 @@ final class PassedRoles {
* when the body does not parse, which its operation refuses.
*/
private static List<PassedRole> fromXml(List<PassedRoleMembers.Member> members, String xml,
UnaryOperator<String> named) {
UnaryOperator<String> named, Function<String, List<String>> profiles) {
Map<PassedRoleMembers.Member, String> paths = new LinkedHashMap<>();
for (PassedRoleMembers.Member member : members) {
xmlPath(member.steps()).ifPresent(path -> paths.put(member, path));
@@ -376,9 +383,8 @@ final class PassedRoles {
}
List<PassedRole> passed = new ArrayList<>();
paths.forEach((member, path) -> {
List<String> roles = read.getOrDefault(path, List.of()).stream().map(String::strip).toList();
passed.addAll(passed(member.byName() ? heldOrNamedRoles(roles, named) : roles,
member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo())));
List<String> values = read.getOrDefault(path, List.of()).stream().map(String::strip).toList();
passed.addAll(memberRoles(member, values, named, profiles));
});
return passed;
}
@@ -405,18 +411,24 @@ final class PassedRoles {
* The roles a JSON request for {@code operation} passes, for a call that is not an HTTP request of its own (a
* state machine's task to its integrated service), read from the members the table gives the operation as a
* direct request's are, a role given by name being the one {@code named} gives. An operation whose roles are
* read by hand here, from a request of its own, is not read so, and fails.
* read by hand here, from a request of its own, or that names an instance profile, whose roles only IAM's own
* lookup finds, is not read so, and fails.
*/
static List<PassedRole> ofBody(String operation, JsonNode body, UnaryOperator<String> named) {
if (PassedRoleMembers.table().byHand().contains(operation)) {
throw new IllegalArgumentException(operation + " passes roles read by hand, from a request of its own");
}
List<PassedRoleMembers.Member> members = PassedRoleMembers.of(operation);
return members == null ? List.of() : fromTable(members, Map.of(), body, named);
if (members != null && members.stream().anyMatch(PassedRoleMembers.Member::instanceProfile)) {
throw new IllegalArgumentException(operation + " passes an instance profile's roles, which only a lookup "
+ "finds");
}
return members == null ? List.of() : fromTable(members, Map.of(), body, named, null);
}
private static List<PassedRole> fromTable(List<PassedRoleMembers.Member> members, Map<String, String> form,
JsonNode body, UnaryOperator<String> named) {
JsonNode body, UnaryOperator<String> named,
Function<String, List<String>> profiles) {
List<PassedRole> passed = new ArrayList<>();
for (PassedRoleMembers.Member member : members) {
List<String> roles = new ArrayList<>();
@@ -431,20 +443,36 @@ final class PassedRoles {
} else {
collect(body, member.steps(), 0, roles);
}
passed.addAll(passed(member.byName() ? heldOrNamedRoles(roles, named) : roles,
member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo())));
passed.addAll(memberRoles(member, roles, named, profiles));
}
return passed;
}
/**
* The roles a member's values pass, to the service the table gives it: a member naming an instance profile passes
* the roles of the profile each value names, by its name or its ARN, as {@code profiles} finds them; one taking a
* role by name the role {@code named} gives for a name; any other the role ARNs it holds.
*/
private static List<PassedRole> memberRoles(PassedRoleMembers.Member member, List<String> values,
UnaryOperator<String> named, Function<String, List<String>> profiles) {
List<String> roles;
if (member.instanceProfile()) {
roles = new ArrayList<>();
for (String profile : values) {
roles.addAll(profiles.apply(profile));
}
} else {
roles = member.byName() ? heldOrNamedRoles(values, named) : values;
}
return passed(roles, member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo()));
}
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());
}
addScalar(node, found);
return;
}
PassedRoleMembers.Step step = steps.get(index);
@@ -879,6 +907,17 @@ final class PassedRoles {
}
/** The strings at {@code path} in {@code node}, where a {@code []} step takes each element of an array. */
/**
* A member's value as the text a handler's {@code asText()} reads it as, a number or a Boolean included, as the
* request resources and condition keys read a body's values: a handler that takes {@code 123456} as the name
* {@code "123456"} acts on that name. A null or a structure names nothing.
*/
private static void addScalar(JsonNode node, List<String> found) {
if (node.isValueNode() && !node.isNull()) {
found.add(node.asText());
}
}
static List<String> values(JsonNode node, String... path) {
List<String> found = new ArrayList<>();
collect(node, path, 0, found);
@@ -890,9 +929,7 @@ final class PassedRoles {
return;
}
if (step == path.length) {
if (node.isTextual()) {
found.add(node.asText());
}
addScalar(node, found);
return;
}
if ("[]".equals(path[step])) {
@@ -924,11 +961,16 @@ final class PassedRoles {
/** The roles of the instance profile {@code profile}, given by its name or its ARN. */
private static List<PassedRole> fromInstanceProfile(Lookups lookups, String profile) {
return passed(instanceProfileRoles(lookups, profile), EC2);
}
/** The role ARNs of the instance profile {@code profile}, given by its name or its ARN; none for no profile. */
private static List<String> instanceProfileRoles(Lookups lookups, String profile) {
if (profile == null || profile.isBlank()) {
return List.of();
}
boolean arn = AwsArnUtils.isArn(profile);
return passed(lookups.instanceProfileRoleArns(arn ? null : profile, arn ? profile : null), EC2);
return lookups.instanceProfileRoleArns(arn ? null : profile, arn ? profile : null);
}
/** The roles that are IAM role ARNs; anything else is left for the operation to refuse. */
@@ -136,8 +136,7 @@ final class Ec2InstanceCredentials {
|| !parsed.accountId().matches("[0-9]{12}") || !parsed.resource().startsWith("instance-profile/")) {
return Optional.empty();
}
String name = arn.substring(arn.lastIndexOf('/') + 1);
return iam.findInstanceProfile(parsed.accountId(), name).filter(profile -> arn.equals(profile.getArn()));
return IamService.instanceProfileNamed(iam, parsed.accountId(), arn);
}
synchronized Optional<SessionCredential> get(Instance instance, String roleName, Instant now) {
@@ -3000,13 +3000,16 @@ public class EmrService implements Resettable, StoredResourceArns, ContainerTear
? step.getExecutionRoleArn() : instanceProfileRole(cluster, accountId);
}
/** The role of the cluster's EC2 instance profile, its {@code JobFlowRole}, given by name or ARN, or null. */
/**
* The role of the cluster's EC2 instance profile, its {@code JobFlowRole}, given by name or by the profile's own
* ARN, as IAM's passed-role check finds it ({@link IamService#instanceProfileNamed}), or null.
*/
private String instanceProfileRole(EmrCluster cluster, String accountId) {
String profile = cluster.getJobFlowRole();
if (profile == null || iamService == null) {
return null;
}
return iamService.findInstanceProfile(accountId, profile.substring(profile.lastIndexOf('/') + 1))
return IamService.instanceProfileNamed(iamService, accountId, profile)
.filter(found -> found.getRoleNames() != null && found.getRoleNames().size() == 1)
.flatMap(found -> iamService.findRole(accountId, found.getRoleNames().getFirst()))
.map(IamRole::getArn)
@@ -3191,6 +3191,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
}
}
/**
* The instance profile {@code nameOrArn} names in {@code accountId}, read as EC2 reads the profile a request
* names: by its name, or by its ARN, which must be the profile's own, its path and account included, so an ARN
* of another account or path names none; empty for one {@code iam} does not hold there. The one reading IAM's
* passed-role check, EMR's instance profile and an EC2 instance's credentials share, so a profile none of them
* finds is used by none.
*/
public static Optional<InstanceProfile> instanceProfileNamed(IamService iam, String accountId, String nameOrArn) {
if (nameOrArn == null || nameOrArn.isBlank()) {
return Optional.empty();
}
if (!AwsArnUtils.isArn(nameOrArn)) {
return iam.findInstanceProfile(accountId, nameOrArn);
}
return iam.findInstanceProfile(accountId, nameOrArn.substring(nameOrArn.lastIndexOf('/') + 1))
.filter(profile -> nameOrArn.equals(profile.getArn()));
}
public Optional<InstanceProfile> findInstanceProfile(String accountId, String profileName) {
if (instanceProfiles instanceof AccountAwareStorageBackend<InstanceProfile> aware) {
return aware.getForAccount(accountId, profileName);
+5 -1
View File
@@ -441,7 +441,11 @@
{"member": "ServiceRole"},
{"member": "UserRole"}
]},
"elasticmapreduce:RunJobFlow": {"passedTo": ["application-autoscaling", "ec2", "elasticmapreduce"], "notRead": "JobFlowRole names an instance profile, and the reference passes the roles to three services without saying which goes where"},
"elasticmapreduce:RunJobFlow": {"passedTo": ["application-autoscaling", "ec2", "elasticmapreduce"], "roles": [
{"member": "AutoScalingRole", "passedTo": "application-autoscaling", "byName": true},
{"member": "JobFlowRole", "passedTo": "ec2", "instanceProfile": true},
{"member": "ServiceRole", "passedTo": "elasticmapreduce", "byName": true}
]},
"elasticmapreduce:StartNotebookExecution": {"passedTo": [], "roles": [
{"member": "ExecutionEngine.ExecutionRoleArn"},
{"member": "ServiceRole", "byName": true}
@@ -42,12 +42,16 @@ class PassedRoleMembersTest {
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";
private static final String PROFILE = "passed-profile";
/** IAM holds {@code named-role} under the path {@code /held/}; nothing else is there to look up. */
/**
* IAM holds {@code named-role} under the path {@code /held/}, and the instance profile {@code passed-profile}
* holding the role {@code passed}; 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();
return PROFILE.equals(profileName) ? List.of(ROLE) : List.of();
}
@Override
@@ -177,13 +181,19 @@ class PassedRoleMembersTest {
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. */
/**
* The role a request names at the member: the instance profile holding it where the member names one, by name
* where the member takes one, else by ARN.
*/
private static String value(Member member) {
if (member.instanceProfile()) {
return PROFILE;
}
return member.byName() ? NAMED : ROLE;
}
private static PassedRole expected(Member member) {
return new PassedRole(member.byName() ? HELD : ROLE,
return new PassedRole(member.byName() && !member.instanceProfile() ? HELD : ROLE,
member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo()));
}
@@ -17,6 +17,7 @@ import java.util.Optional;
import java.util.zip.GZIPOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -45,7 +46,7 @@ class PassedRolesTest {
* {@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/}. Service Catalog holds a launch constraint {@code cons-launch} and a notification
* constraint {@code cons-notify}.
* constraint {@code cons-notify}. The instance profile {@code 123456} holds the role {@code numbered-instance}.
*/
private static final PassedRoles.Lookups LOOKUPS = new PassedRoles.Lookups() {
@Override
@@ -53,6 +54,9 @@ class PassedRolesTest {
if ("web-profile".equals(profileName)) {
return List.of(ROLES + "web-instance");
}
if ("123456".equals(profileName)) {
return List.of(ROLES + "numbered-instance");
}
return PROFILE_ARN.equals(profileArn) ? List.of(ROLES + "arn-instance") : List.of();
}
@@ -701,6 +705,30 @@ class PassedRolesTest {
json("{\"name\":\"p\",\"serviceRole\":\"app-role\"}"), LOOKUPS));
}
@Test
void anEmrClusterPassesItsInstanceProfilesRolesToEc2AndItsRolesByNameToTheirServices() {
// JobFlowRole names an instance profile, whose roles go to EC2; the service role, given by its name, to EMR, and
// the automatic scaling role to Application Auto Scaling. The steps' runtime role is not passed.
String request = """
{"Name":"c","ServiceRole":"app-role","JobFlowRole":"web-profile","AutoScalingRole":"%1$sscaling",
"StepExecutionRoleArn":"%1$sruntime"}""".formatted(ROLES);
assertEquals(List.of(passed("scaling", "application-autoscaling.amazonaws.com"), passed("web-instance", EC2),
new PassedRole(ROLES + "app/app-role", "elasticmapreduce.amazonaws.com")),
PassedRoles.of("elasticmapreduce:RunJobFlow", json(request), LOOKUPS));
// A profile named by its ARN passes its roles too, and one that does not exist passes none.
assertEquals(List.of(passed("arn-instance", EC2)), PassedRoles.of("elasticmapreduce:RunJobFlow",
json("{\"JobFlowRole\":\"" + PROFILE_ARN + "\"}"), LOOKUPS));
assertEquals(List.of(), PassedRoles.of("elasticmapreduce:RunJobFlow",
json("{\"JobFlowRole\":\"no-such-profile\"}"), LOOKUPS));
// A number is read as the name EMR reads it as, a profile's or a role's.
assertEquals(List.of(passed("numbered-instance", EC2), passed("123456", "elasticmapreduce.amazonaws.com")),
PassedRoles.of("elasticmapreduce:RunJobFlow", json("{\"JobFlowRole\":123456,\"ServiceRole\":123456}"),
LOOKUPS));
// A call that is no request of its own has no instance profile lookup, so it is refused.
assertThrows(IllegalArgumentException.class, () -> PassedRoles.ofBody("elasticmapreduce:RunJobFlow",
new ObjectMapper().createObjectNode(), name -> ROLES + name));
}
@Test
void anXmlBodyPassesTheRolesItsModeledMembersName() {
// S3's PutBucketReplication, authorized as s3:PutReplicationConfiguration, passes its configuration's Role.
@@ -1653,6 +1653,33 @@ class EmrServiceContainerStepsTest {
assertEquals("arn:aws:iam::" + ACCOUNT + ":role/step", runner.jobs.get(1).executionRole());
}
@Test
void aJobFlowRoleArnOfAnotherAccountOrPathNamesNoProfile() {
// The instance profile is read as IAM's passed-role check reads it: by its name or by its own ARN, so an ARN
// of another account or path, which that check finds no role for, gives the steps no role either.
IamService iam = mock(IamService.class);
InstanceProfile profile = new InstanceProfile();
profile.setArn("arn:aws:iam::" + ACCOUNT + ":instance-profile/EMR_EC2_DefaultRole");
profile.setRoleNames(List.of("emr-ec2"));
IamRole role = new IamRole();
role.setArn("arn:aws:iam::" + ACCOUNT + ":role/emr-ec2");
when(iam.findInstanceProfile(ACCOUNT, "EMR_EC2_DefaultRole")).thenReturn(Optional.of(profile));
when(iam.findRole(ACCOUNT, "emr-ec2")).thenReturn(Optional.of(role));
EmrServiceFixture withIam = EmrServiceFixture.docker(runner, iam);
List<String> named = List.of("arn:aws:iam::999999999999:instance-profile/EMR_EC2_DefaultRole",
"arn:aws:iam::" + ACCOUNT + ":instance-profile/other/EMR_EC2_DefaultRole", profile.getArn());
for (int i = 0; i < named.size(); i++) {
EmrCluster requested = cluster("named-" + i, true, sparkStep("profile", "CONTINUE"));
requested.setJobFlowRole(named.get(i));
withIam.service.runJobFlow(requested, REGION);
withIam.runStepThread();
}
assertNull(runner.jobs.get(0).executionRole());
assertNull(runner.jobs.get(1).executionRole());
assertEquals(role.getArn(), runner.jobs.get(2).executionRole());
}
@Test
void aStepRunsWithoutARoleWhenIamKnowsNone() {
service.runJobFlow(cluster("roleless", true, sparkStep("plain", "CONTINUE")), REGION);
@@ -132,6 +132,54 @@ class IamPassRoleEnforcementIntegrationTest {
user.s3().body(configuration).put("/" + bucket + "?replication").then().statusCode(200);
}
@Test
void anEmrClusterNeedsPassRoleOnItsServiceRoleForEmrAndItsInstanceProfilesRoleForEc2() {
// ServiceRole is given by name and goes to EMR; JobFlowRole names an instance profile, whose role goes to EC2.
String service = role("emr-service");
String instance = role("emr-instance");
String profile = instanceProfile(instance.substring(instance.lastIndexOf('/') + 1));
User user = user("passrole-emr");
String body = """
{"Name":"passrole-emr-%s","ReleaseLabel":"emr-7.5.0","ServiceRole":"%s","JobFlowRole":"%s",
"Instances":{"KeepJobFlowAliveWhenNoSteps":true,"InstanceGroups":[{"Name":"master",
"InstanceRole":"MASTER","InstanceType":"m5.xlarge","InstanceCount":1}]}}"""
.formatted(suffix(), service.substring(service.lastIndexOf('/') + 1), profile);
String runJobFlow = "ElasticMapReduce.RunJobFlow";
user.policy(allow("elasticmapreduce:RunJobFlow", "*"));
deniedJson(user.json("elasticmapreduce", runJobFlow).body(body).post("/").then());
user.policy(allow("elasticmapreduce:RunJobFlow", "*") + "," + passRole(service, "elasticmapreduce.amazonaws.com")
+ "," + passRole(instance, "elasticmapreduce.amazonaws.com"));
deniedJson(user.json("elasticmapreduce", runJobFlow).body(body).post("/").then());
// The service role, named by its name, is checked on the role IAM holds under it.
user.policy(allow("elasticmapreduce:RunJobFlow", "*") + "," + passRole(instance, "ec2.amazonaws.com"));
deniedJson(user.json("elasticmapreduce", runJobFlow).body(body).post("/").then());
user.policy(allow("elasticmapreduce:RunJobFlow", "*") + "," + passRole(service, "elasticmapreduce.amazonaws.com")
+ "," + passRole(instance, "ec2.amazonaws.com"));
// A profile named by a JSON number is the one EMR reads it as.
String numbered = Long.toString(System.nanoTime());
admin("iam").formParam("Action", "CreateInstanceProfile").formParam("InstanceProfileName", numbered)
.post("/").then().statusCode(200);
cleanup.register(() -> EnforcementFixtures.removeInstanceProfile(baseUri.getPort(), auth(ADMIN, "iam"),
numbered));
admin("iam").formParam("Action", "AddRoleToInstanceProfile").formParam("InstanceProfileName", numbered)
.formParam("RoleName", instance.substring(instance.lastIndexOf('/') + 1)).post("/").then()
.statusCode(200);
user.policy(allow("elasticmapreduce:RunJobFlow", "*") + "," + passRole(service, "elasticmapreduce.amazonaws.com"));
deniedJson(user.json("elasticmapreduce", runJobFlow)
.body(body.replace("\"JobFlowRole\":\"" + profile + "\"", "\"JobFlowRole\":" + numbered)).post("/")
.then());
user.policy(allow("elasticmapreduce:RunJobFlow", "*") + "," + passRole(service, "elasticmapreduce.amazonaws.com")
+ "," + passRole(instance, "ec2.amazonaws.com"));
String clusterId = user.json("elasticmapreduce", runJobFlow).body(body).post("/").then().statusCode(200)
.extract().path("JobFlowId");
cleanup.register(() -> admin("elasticmapreduce").header("X-Amz-Target", "ElasticMapReduce.TerminateJobFlows")
.contentType("application/x-amz-json-1.1").body("{\"JobFlowIds\":[\"" + clusterId + "\"]}")
.post("/"));
}
@Test
void aPassRoleGrantKeyedOnTheRolesTagIsNotSatisfiedByTheTag() {
// The IAM guide warns that ResourceTag conditions with PassRole "do not have reliable results", so the
+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env python3
"""Vendor which role each Amazon EMR RunJobFlow member names, and the service it is passed to, into
tools/aws/sources/emr-roles.json, a source of the passed-roles table.
AWS's Service Reference passes RunJobFlow's roles to `application-autoscaling.amazonaws.com`, `ec2.amazonaws.com` and
`elasticmapreduce.amazonaws.com` without saying which member's role goes where, and botocore does not say it as data
either. The EMR management guide has a page for each role a cluster takes, naming its default role:
The default role name is EMR_DefaultRole_V2. (Service role for Amazon EMR (EMR role))
The default role name is EMR_EC2_DefaultRole. (Service role for cluster EC2 instances)
The default role name is EMR_AutoScaling_DefaultRole. (Service role for automatic scaling)
and the full access policy it gives users passes each default role to its service alone:
"Sid": "PassRoleForEC2", "Action": "iam:PassRole", "Resource": ["arn:aws:iam::*:role/EMR_EC2_DefaultRole"],
"Condition": {"StringLike": {"iam:PassedToService": "ec2.amazonaws.com*"}}
https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-policy-fullaccess-v2.html
The EMR API reference describes each RunJobFlow member as the role it names, `JobFlowRole` as an instance profile
("Also called instance profile and Amazon EC2 role"), and `StepExecutionRoleArn` as the runtime role of the steps the
request runs, whose access the guide's page on runtime roles controls by a condition key, not by passing it:
You can control access to the runtime role with the condition key elasticmapreduce:ExecutionRoleArn.
https://docs.aws.amazon.com/emr/latest/APIReference/API_RunJobFlow.html
https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-steps-runtime-roles.html
The AWS CLI reference's create-cluster examples, whose options the CLI sends as those members, give each role by its
name (`--service-role EMR_DefaultRole`, `--ec2-attributes InstanceProfile=EMR_EC2_DefaultRole`,
`--auto-scaling-role EMR_AutoScaling_DefaultRole`), so a member is also given a role by its name:
https://docs.aws.amazon.com/cli/latest/reference/emr/create-cluster.html
This script copies each member's description as it stands, the title and default role of the page of its role, the
services the full access policy passes that default role to, and the value the CLI's examples give its option; for
the runtime role, the sentence naming the condition key that controls access to it. Nothing in the output is written by hand; regen_iam_passed_roles.py reads
it to choose, among the services the Service Reference passes RunJobFlow's roles to, the one each member's role goes
to.
Run from anywhere in the repo:
python3 tools/aws/fetch_emr_roles.py # rewrite the vendored file from the pages
python3 tools/aws/fetch_emr_roles.py --verify # online: the file still says what the pages do
"""
from __future__ import annotations
import argparse
import html
import json
import re
import sys
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
API_PAGE = "https://docs.aws.amazon.com/emr/latest/APIReference/API_RunJobFlow.html"
GUIDE = "https://docs.aws.amazon.com/emr/latest/ManagementGuide/"
POLICY_PAGE = GUIDE + "emr-managed-policy-fullaccess-v2.html"
RUNTIME_ROLES_PAGE = GUIDE + "emr-steps-runtime-roles.html"
CLI_PAGE = "https://docs.aws.amazon.com/cli/latest/reference/emr/create-cluster.html"
REPO_ROOT = Path(__file__).resolve().parents[2]
OUTPUT = REPO_ROOT / "tools/aws/sources/emr-roles.json"
# The RunJobFlow members that name a role, each with the guide's page of that role and the CLI option sending it, or,
# for the steps' runtime role, the guide's page on runtime roles.
MEMBERS = (
{"member": "ServiceRole", "rolePage": GUIDE + "emr-iam-role.html", "cliOption": "--service-role"},
{"member": "JobFlowRole", "rolePage": GUIDE + "emr-iam-role-for-ec2.html", "cliOption": "InstanceProfile="},
{"member": "AutoScalingRole", "rolePage": GUIDE + "emr-iam-role-automatic-scaling.html",
"cliOption": "--auto-scaling-role"},
{"member": "StepExecutionRoleArn", "runtimeRolesPage": RUNTIME_ROLES_PAGE},
)
# A role page's sentence naming its default role.
DEFAULT_ROLE_RE = re.compile(r"\bThe default role name is (?P<role>EMR_[A-Za-z0-9_]+) \.")
# A member description naming the default role, which must be its page's.
DESCRIBED_DEFAULT_RE = re.compile(r"\bThe default role is (?P<role>EMR_[A-Za-z0-9_]+) \.")
# A member description saying the member names an instance profile.
INSTANCE_PROFILE_RE = re.compile(r"\bAlso called instance profile\b")
# The runtime roles page's sentence naming the condition key that controls access to the runtime role.
ACCESS_RE = re.compile(r"You can control access to the runtime role with the condition key "
r"(?P<key>[a-z0-9-]+:[A-Za-z]+) \.")
# A role ARN of the full access policy, its name the default role it passes.
POLICY_ROLE_RE = re.compile(r"^arn:aws:iam::\*:role/(?P<role>EMR_[A-Za-z0-9_]+)$")
def text(fragment: str) -> str:
"""A fragment of a page as text, spaces collapsed."""
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip()
def code(fragment: str) -> str:
"""A code block as the text it shows, the page's copy button left out."""
fragment = re.sub(r'<div class="code-btn-container">.*?</div></div>', "", fragment, flags=re.S)
return html.unescape(re.sub(r"<[^>]+>", "", re.sub(r"<!--.*?-->", "", fragment, flags=re.S))).strip()
def read_description(page: str, member: str) -> str:
"""The member's description on the RunJobFlow page, as text."""
match = re.search(r'id="EMR-RunJobFlow-request-' + re.escape(member) + r'"[^>]*>(?P<entry>.*?)</dd>', page, re.S)
if match is None:
raise ValueError(f"{API_PAGE} has no entry for {member}: its layout changed")
entry = match.group("entry")
described = re.search(r"<dd[^>]*>(?P<body>.*?)<p>\s*Type:", entry + "<p>Type:", re.S)
return text(described.group("body") if described else entry)
def read_role_page(page: str, url: str) -> dict:
"""The title of a role's page and the default role it names."""
title = re.search(r"<title>(?P<title>.*?)</title>", page, re.S)
named = DEFAULT_ROLE_RE.search(text(page))
if title is None or named is None:
raise ValueError(f"{url} names no default role: its layout changed")
return {"title": text(title.group("title")), "defaultRole": named.group("role")}
def read_policy(page: str) -> dict[str, list[str]]:
"""The services the full access policy passes each default role it names to."""
passed: dict[str, set[str]] = {}
for block in re.findall(r"<pre[^>]*>(.*?)</pre>", page, re.S):
shown = code(block)
if "iam:PassRole" not in shown:
continue
for statement in json.loads(shown)["Statement"]:
actions = statement.get("Action")
if "iam:PassRole" not in (actions if isinstance(actions, list) else [actions]):
continue
services = statement.get("Condition", {}).get("StringLike", {}).get("iam:PassedToService")
resources = statement.get("Resource")
for resource in resources if isinstance(resources, list) else [resources]:
role = POLICY_ROLE_RE.match(resource or "")
if role is None or services is None:
continue
for service in services if isinstance(services, list) else [services]:
passed.setdefault(role.group("role"), set()).add(service.removesuffix("*"))
if not passed:
raise ValueError(f"{POLICY_PAGE} passes no default role to a service: its layout changed")
return {role: sorted(services) for role, services in passed.items()}
def read_cli_example(page: str, option: str) -> str:
"""The value the first of the CLI reference's examples that gives `option` gives it."""
start = page.find('id="examples"')
if start < 0:
raise ValueError(f"{CLI_PAGE} has no examples: its layout changed")
for block in re.findall(r"<pre[^>]*>(.*?)</pre>", page[start:], re.S):
match = re.search(re.escape(option) + r"\s*(?P<value>[A-Za-z0-9_+=.@/:-]+)", code(block))
if match is not None:
return match.group("value").rstrip(".")
raise ValueError(f"{CLI_PAGE} gives no example of {option}: its layout changed")
def read_access(page: str) -> dict:
"""The runtime roles page's sentence naming the condition key that controls access to the runtime role."""
match = ACCESS_RE.search(text(page))
if match is None:
raise ValueError(f"{RUNTIME_ROLES_PAGE} names no condition key controlling access to the runtime role: "
f"its layout changed")
return {"accessControlledBy": match.group("key"), "accessSentence": match.group(0)}
def build(fetch) -> dict:
api = fetch(API_PAGE)
policy = read_policy(fetch(POLICY_PAGE))
cli = fetch(CLI_PAGE)
members = []
for member in MEMBERS:
description = read_description(api, member["member"])
entry: dict = {"operation": "RunJobFlow", "member": member["member"], "description": description}
if "runtimeRolesPage" in member:
entry.update({"runtimeRolesPage": member["runtimeRolesPage"],
**read_access(fetch(member["runtimeRolesPage"]))})
members.append(entry)
continue
role = read_role_page(fetch(member["rolePage"]), member["rolePage"])
described = DESCRIBED_DEFAULT_RE.search(description)
if described is not None and described.group("role") != role["defaultRole"]:
raise ValueError(f"{API_PAGE} names {described.group('role')} as {member['member']}'s default role, and "
f"{member['rolePage']} {role['defaultRole']}")
if role["defaultRole"] not in policy:
raise ValueError(f"{POLICY_PAGE} passes {role['defaultRole']} to no service: its layout changed")
example = read_cli_example(cli, member["cliOption"])
entry.update({"rolePage": member["rolePage"], **role, "policyPage": POLICY_PAGE,
"passedToService": policy[role["defaultRole"]], "cliOption": member["cliOption"],
"cliExample": example})
if INSTANCE_PROFILE_RE.search(description):
entry["instanceProfile"] = True
elif not example.startswith("arn:"):
entry["byName"] = True
members.append(entry)
return {
"_source": {
"pages": [API_PAGE, POLICY_PAGE, CLI_PAGE] + [m.get("rolePage") or m["runtimeRolesPage"] for m in MEMBERS],
"fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)),
"retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
"note": "Each RunJobFlow member's description on the API reference, copied as it stands; the title and "
"default role of the guide's page of its role and the services the full access policy passes "
"that default role to, and the value the CLI reference's examples give the option sending it; "
"and for the steps' runtime role, the runtime roles page's sentence naming the condition key "
"that controls access to it.",
},
"members": members,
}
def fetch_url(url: str) -> str:
request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"})
with urllib.request.urlopen(request, timeout=60) as response:
return response.read().decode("utf-8")
def fetch_all(fetch=fetch_url) -> tuple:
"""The pages, each fetched once."""
cache: dict[str, str] = {}
def cached(url: str) -> str:
if url not in cache:
cache[url] = fetch(url)
return cache[url]
build(cached)
return (cache,)
def stale(vendored: dict, pages: dict[str, str]) -> bool:
"""Whether the pages now give something other than the vendored file, its date aside."""
return vendored.get("members") != build(lambda url: pages[url])["members"]
def main(argv: list[str] | None = None, fetch=fetch_url) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the pages")
args = parser.parse_args(argv)
try:
(pages,) = fetch_all(fetch)
except OSError as e:
print(f"error: could not read the Amazon EMR documentation ({e})", file=sys.stderr)
return 2
if args.verify:
vendored = json.loads(OUTPUT.read_text(encoding="utf-8"))
if stale(vendored, pages):
print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the EMR API reference and "
f"management guide do: run tools/aws/fetch_emr_roles.py and then make iam-passed-roles-sync",
file=sys.stderr)
return 1
print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the EMR API reference and management guide")
return 0
built = build(lambda url: pages[url])
OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8")
print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['members'])} members' roles)")
return 0
if __name__ == "__main__":
sys.exit(main())
+50 -19
View File
@@ -31,7 +31,11 @@ operation is corrected here, each with its reason: a role member it does not see
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`). Where a namespace's documentation says it, which
service that is comes from a vendored source instead (`ROLE_SOURCES`): EKS's API reference names the
role each member takes, and its user guide the service each role's trust policy is for.
role each member takes, and its user guide the service each role's trust policy is for; EMR's
management guide names the default role of each role RunJobFlow takes and the service its full access
policy passes each to, and its API reference which member names an instance profile, whose roles are
the ones passed (`instanceProfile`), and which names a runtime role, whose access a condition key
controls instead, so it passes none.
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
@@ -75,6 +79,7 @@ from datetime import datetime, timezone
from pathlib import Path
import fetch_eks_roles
import fetch_emr_roles
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
@@ -272,8 +277,6 @@ NOT_READ = {
"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:UpdateDaemon": "the roles are the daemon task definition's, which only a lookup finds",
"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,
@@ -413,14 +416,24 @@ MEMBER_SERVICES = {
# computeConfig.nodeRoleArn as "the IAM Role EKS will assign to EC2 Managed Instances", naming the guide's IAM
# reference for EKS Auto Mode, whose section of the node role links the guide's page of it, whose trust policy names
# "ec2.amazonaws.com"; tools/aws/fetch_eks_roles.py vendors those pages and `vendored_service` reads them, choosing
# among the services the reference names. The file is written by its own script from the pages, unchanged, and nothing
# about an operation is stated here.
# among the services the reference names. And granted for EMR: the management guide's page of each role RunJobFlow
# takes names its default role ("The default role name is EMR_EC2_DefaultRole"), and the full access policy it gives
# users passes each default role to its service alone ("iam:PassedToService": "ec2.amazonaws.com*"); the API reference
# says JobFlowRole names an instance profile ("Also called instance profile and Amazon EC2 role"), whose roles are the
# ones passed, the CLI reference's create-cluster examples give the others by name ("--service-role EMR_DefaultRole"),
# and the guide's page on runtime roles that access to StepExecutionRoleArn's runtime role is controlled
# by a condition key ("You can control access to the runtime role with the condition key
# elasticmapreduce:ExecutionRoleArn"), so it passes none; tools/aws/fetch_emr_roles.py vendors those pages and
# `vendored_role` reads them. Each file is written by its own script from the pages, unchanged, and nothing about an
# operation is stated here.
ROLE_SOURCES: dict[str, Path] = {
"eks": REPO_ROOT / "tools/aws/sources/eks-roles.json",
"elasticmapreduce": REPO_ROOT / "tools/aws/sources/emr-roles.json",
}
# The script that writes each namespace's role source, whose pages `verify_role_sources` reads it against.
ROLE_FETCHERS = {
"eks": fetch_eks_roles,
"elasticmapreduce": fetch_emr_roles,
}
@@ -614,10 +627,10 @@ def _role_source(namespace: str) -> tuple[dict, ...]:
return () if path is None else tuple(json.loads(path.read_text(encoding="utf-8"))["members"])
def vendored_service(operation: str, path: str, passed_to: list[str], models: dict[str, dict]) -> str | None:
"""The one of `passed_to` the role at `path` is for, by the namespace's vendored role source (`ROLE_SOURCES`):
the service a trust policy of the role its member names is for, the member given by its operation when it is the
request's own and by the botocore type holding it otherwise. None for a member the source does not give."""
def vendored_role(operation: str, path: str, models: dict[str, dict]) -> dict | None:
"""What the namespace's vendored role source (`ROLE_SOURCES`) gives for the member at `path`, the member given by
its operation when it is the request's own and by the botocore type holding it otherwise; None for a member the
source does not give."""
name = operation.split(":", 1)[1]
own = PATH_STEP_RE.match(path) is not None
for model in models.values():
@@ -626,17 +639,27 @@ def vendored_service(operation: str, path: str, passed_to: list[str], models: di
continue
owner, member, _shape = walked
for entry in _role_source(namespace_of(operation)):
if entry["member"] != member or (entry.get("operation") != name if own else entry.get("type") != owner):
continue
services = [service.removesuffix(SERVICE_SUFFIX) for service in entry["trustedBy"]]
chosen = [service for service in services if service in passed_to]
if len(chosen) != 1:
raise ValueError(f"{operation}: the role at {path} is for {services} by {entry['rolePage']}, which "
f"is not one of {passed_to} the reference passes its roles to")
return chosen[0]
if entry["member"] == member and (entry.get("operation") == name if own else entry.get("type") == owner):
return entry
return None
def vendored_service(operation: str, path: str, passed_to: list[str], models: dict[str, dict]) -> str | None:
"""The one of `passed_to` the role at `path` is for, by the namespace's vendored role source (`ROLE_SOURCES`):
the service its documentation passes the role its member names to, or else the service a trust policy of that
role is for. None for a member the source does not give."""
entry = vendored_role(operation, path, models)
if entry is None:
return None
services = [service.removesuffix(SERVICE_SUFFIX)
for service in entry.get("passedToService", entry.get("trustedBy", []))]
chosen = [service for service in services if service in passed_to]
if len(chosen) != 1:
raise ValueError(f"{operation}: the role at {path} is for {services} by {entry.get('rolePage')}, which "
f"is not one of {passed_to} the reference passes its roles to")
return chosen[0]
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()}
@@ -708,6 +731,10 @@ def entry_for(operation: str, passed_to: list[str], models: dict[str, dict]) ->
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
# A member the vendored role source says names a role whose access a condition key controls, rather than passing
# it, passes none.
for path in [path for path in members if (vendored_role(operation, path, models) or {}).get("accessControlledBy")]:
members.pop(path)
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)")
@@ -725,8 +752,11 @@ def entry_for(operation: str, passed_to: list[str], models: dict[str, dict]) ->
raise ValueError(f"{operation}: the role at {path} can go to any of {passed_to}; "
f"say which in MEMBER_SERVICES or a vendored role source (ROLE_SOURCES)")
role["passedTo"] = vendored
if members[path]:
vendored = vendored_role(operation, path, models) or {}
if members[path] or vendored.get("byName"):
role["byName"] = True
if vendored.get("instanceProfile"):
role["instanceProfile"] = True
roles.append(role)
return {"passedTo": passed_to, "roles": roles}
@@ -895,7 +925,8 @@ def validate(document: dict) -> list[str]:
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:
if (set(role) - {"member", "passedTo", "byName", "instanceProfile"} or role.get("byName", True) is not True
or role.get("instanceProfile", True) is not True):
problems.append(f"{operation}: the role at {path} carries an unknown field")
return problems
+71
View File
@@ -0,0 +1,71 @@
{
"_source": {
"pages": [
"https://docs.aws.amazon.com/emr/latest/APIReference/API_RunJobFlow.html",
"https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-policy-fullaccess-v2.html",
"https://docs.aws.amazon.com/cli/latest/reference/emr/create-cluster.html",
"https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role.html",
"https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role-for-ec2.html",
"https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role-automatic-scaling.html",
"https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-steps-runtime-roles.html"
],
"fetcher": "tools/aws/fetch_emr_roles.py",
"retrieved": "2026-11-27",
"note": "Each RunJobFlow member's description on the API reference, copied as it stands; the title and default role of the guide's page of its role and the services the full access policy passes that default role to, and the value the CLI reference's examples give the option sending it; and for the steps' runtime role, the runtime roles page's sentence naming the condition key that controls access to it."
},
"members": [
{
"operation": "RunJobFlow",
"member": "ServiceRole",
"description": "The IAM role that Amazon EMR assumes in order to access AWS resources on your behalf. If you've created a custom service role path, you must specify it for the service role when you launch your cluster.",
"rolePage": "https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role.html",
"title": "Service role for Amazon EMR (EMR role) - Amazon EMR",
"defaultRole": "EMR_DefaultRole_V2",
"policyPage": "https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-policy-fullaccess-v2.html",
"passedToService": [
"elasticmapreduce.amazonaws.com"
],
"cliOption": "--service-role",
"cliExample": "EMR_DefaultRole",
"byName": true
},
{
"operation": "RunJobFlow",
"member": "JobFlowRole",
"description": "Also called instance profile and Amazon EC2 role. An IAM role for an Amazon EMR cluster. The Amazon EC2 instances of the cluster assume this role. The default role is EMR_EC2_DefaultRole . In order to use the default role, you must have already created it using the AWS CLI or console.",
"rolePage": "https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role-for-ec2.html",
"title": "Service role for cluster EC2 instances (EC2 instance profile) - Amazon EMR",
"defaultRole": "EMR_EC2_DefaultRole",
"policyPage": "https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-policy-fullaccess-v2.html",
"passedToService": [
"ec2.amazonaws.com"
],
"cliOption": "InstanceProfile=",
"cliExample": "EMR_EC2_DefaultRole",
"instanceProfile": true
},
{
"operation": "RunJobFlow",
"member": "AutoScalingRole",
"description": "An IAM role for automatic scaling policies. The default role is EMR_AutoScaling_DefaultRole . The IAM role provides permissions that the automatic scaling feature requires to launch and terminate Amazon EC2 instances in an instance group.",
"rolePage": "https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-role-automatic-scaling.html",
"title": "Service role for automatic scaling in Amazon EMR (Auto Scaling role) - Amazon EMR",
"defaultRole": "EMR_AutoScaling_DefaultRole",
"policyPage": "https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-managed-policy-fullaccess-v2.html",
"passedToService": [
"application-autoscaling.amazonaws.com"
],
"cliOption": "--auto-scaling-role",
"cliExample": "EMR_AutoScaling_DefaultRole",
"byName": true
},
{
"operation": "RunJobFlow",
"member": "StepExecutionRoleArn",
"description": "The Amazon Resource Name (ARN) of the runtime role for steps specified in the RunJobFlow request. The runtime role can be a cross-account IAM role. The runtime role ARN is a combination of account ID, role name, and role type using the following format: arn:partition:iam::account-id:role/role-name . For example, arn:aws:iam::1234567890:role/ReadOnly is a correctly formatted runtime role ARN. This parameter applies only to steps included in the Steps parameter of this RunJobFlow request. It does not apply to steps added later to the cluster.",
"runtimeRolesPage": "https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-steps-runtime-roles.html",
"accessControlledBy": "elasticmapreduce:ExecutionRoleArn",
"accessSentence": "You can control access to the runtime role with the condition key elasticmapreduce:ExecutionRoleArn ."
}
]
}
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Tests for fetch_emr_roles.py, on pages in the Amazon EMR API reference's, management guide's and AWS CLI
reference's markup."""
from __future__ import annotations
import pytest
import fetch_emr_roles as f
def entry(member: str, description: str) -> str:
return (f'<dt id="EMR-RunJobFlow-request-{member}"><a id="EMR-RunJobFlow-request-{member}"></a>'
f'<b><code class="code">{member}</code></b></dt><dd><p>{description}</p><p>Type: String</p></dd>')
def role_page(title: str, role: str) -> str:
return f"<title>{title}</title><p>The default role name is <code class=\"code\">{role}</code>.</p>"
POLICY = ('<pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy">'
'<awsui-icon name="copy"></awsui-icon></div></div><code class="json ">{"Version":"2012-10-17","Statement":['
'{"Sid":"PassRoleForElasticMapReduce","Effect":"Allow","Action":"iam:PassRole",'
'"Resource":["arn:aws:iam::*:role/EMR_DefaultRole_V2"],'
'"Condition":{"StringLike":{"iam:PassedToService":"elasticmapreduce.amazonaws.com*"}}},'
'{"Sid":"PassRoleForEC2","Effect":"Allow","Action":"iam:PassRole",'
'"Resource":["arn:aws:iam::*:role/EMR_EC2_DefaultRole"],'
'"Condition":{"StringLike":{"iam:PassedToService":"ec2.amazonaws.com*"}}},'
'{"Sid":"PassRoleForAutoScaling","Effect":"Allow","Action":"iam:PassRole",'
'"Resource":["arn:aws:iam::*:role/EMR_AutoScaling_DefaultRole"],'
'"Condition":{"StringLike":{"iam:PassedToService":"application-autoscaling.amazonaws.com*"}}}]}'
'</code></pre>')
CLI = ('<pre>aws emr create-cluster [--service-role &lt;value&gt;]</pre><p>InstanceProfile=string</p>'
'<div class="section" id="examples"><h2>Examples</h2>'
'<pre>aws emr create-cluster --service-role EMR_DefaultRole --ec2-attributes '
'InstanceProfile=EMR_EC2_DefaultRole --auto-scaling-role EMR_AutoScaling_DefaultRole</pre></div>')
PAGES = {
f.API_PAGE: (
entry("ServiceRole", "The IAM role that Amazon EMR assumes in order to access AWS resources on your behalf.")
+ entry("JobFlowRole", "Also called instance profile and Amazon EC2 role. The default role is "
"<code class=\"code\">EMR_EC2_DefaultRole</code>.")
+ entry("AutoScalingRole", "An IAM role for automatic scaling policies. The default role is "
"<code class=\"code\">EMR_AutoScaling_DefaultRole</code>.")
+ entry("StepExecutionRoleArn", "The runtime role can be a cross-account IAM role.")),
f.POLICY_PAGE: POLICY,
f.CLI_PAGE: CLI,
f.GUIDE + "emr-iam-role.html": role_page("Service role for Amazon EMR (EMR role)", "EMR_DefaultRole_V2"),
f.GUIDE + "emr-iam-role-for-ec2.html": role_page("Service role for cluster EC2 instances (EC2 instance profile)",
"EMR_EC2_DefaultRole"),
f.GUIDE + "emr-iam-role-automatic-scaling.html": role_page("Service role for automatic scaling in Amazon EMR",
"EMR_AutoScaling_DefaultRole"),
f.RUNTIME_ROLES_PAGE: "<p>You can control access to the runtime role with the condition key "
"<code class=\"code\">elasticmapreduce:ExecutionRoleArn</code>.</p>",
}
def by_member(built: dict) -> dict:
return {member["member"]: member for member in built["members"]}
def test_each_member_gives_its_default_roles_service_and_how_it_names_its_role():
members = by_member(f.build(lambda url: PAGES[url]))
assert members["ServiceRole"]["defaultRole"] == "EMR_DefaultRole_V2"
assert members["ServiceRole"]["passedToService"] == ["elasticmapreduce.amazonaws.com"]
assert members["ServiceRole"]["byName"] is True and members["ServiceRole"]["cliExample"] == "EMR_DefaultRole"
assert members["JobFlowRole"]["passedToService"] == ["ec2.amazonaws.com"]
assert members["JobFlowRole"]["instanceProfile"] is True and "byName" not in members["JobFlowRole"]
assert members["JobFlowRole"]["cliExample"] == "EMR_EC2_DefaultRole"
assert members["AutoScalingRole"]["passedToService"] == ["application-autoscaling.amazonaws.com"]
assert members["StepExecutionRoleArn"]["accessControlledBy"] == "elasticmapreduce:ExecutionRoleArn"
assert "passedToService" not in members["StepExecutionRoleArn"]
def test_a_description_naming_another_default_role_than_its_page_is_refused():
changed = dict(PAGES, **{f.GUIDE + "emr-iam-role-for-ec2.html": role_page("EC2", "EMR_EC2_OtherRole")})
with pytest.raises(ValueError, match="names EMR_EC2_DefaultRole"):
f.build(lambda url: changed[url])
def test_a_page_whose_layout_changed_is_refused():
for url, page, message in ((f.POLICY_PAGE, "<p>No policy.</p>", "passes no default role"),
(f.RUNTIME_ROLES_PAGE, "<p>Nothing.</p>", "names no condition key"),
(f.CLI_PAGE, "<pre>aws emr create-cluster</pre>", "has no examples"),
(f.API_PAGE, "<dl></dl>", "has no entry")):
changed = dict(PAGES, **{url: page})
with pytest.raises(ValueError, match=message):
f.build(lambda u: changed[u])
def test_the_file_is_stale_when_a_page_says_something_else():
vendored = f.build(lambda url: PAGES[url])
assert not f.stale(vendored, PAGES)
assert f.stale(vendored, dict(PAGES, **{f.POLICY_PAGE: POLICY.replace("ec2.amazonaws.com", "eks.amazonaws.com")}))
+21
View File
@@ -237,6 +237,27 @@ def test_a_vendored_role_for_a_service_the_reference_does_not_name_fails(correct
r.entry_for("svc:CreateCluster", ["other", "svc"], CLUSTER)
JOB_FLOW = {"svc": model({"RunJobFlow": "In"}, {"In": structure(ServiceRole="String", JobFlowRole="String",
StepExecutionRoleArn="String")})}
def test_a_vendored_role_names_an_instance_profile_a_role_by_name_or_one_a_condition_key_controls(corrections,
tmp_path):
# The documented service wins over a trust policy, and a runtime role whose access a condition key controls
# passes none.
role_source(corrections, tmp_path, [
{"operation": "RunJobFlow", "member": "ServiceRole", "passedToService": ["svc.amazonaws.com"],
"trustedBy": ["other.amazonaws.com", "svc.amazonaws.com"], "byName": True},
{"operation": "RunJobFlow", "member": "JobFlowRole", "passedToService": ["other.amazonaws.com"],
"instanceProfile": True},
{"operation": "RunJobFlow", "member": "StepExecutionRoleArn", "accessControlledBy": "svc:ExecutionRoleArn"}])
entry = r.entry_for("svc:RunJobFlow", ["other", "svc"], JOB_FLOW)
assert entry["roles"] == [{"member": "JobFlowRole", "passedTo": "other", "instanceProfile": True},
{"member": "ServiceRole", "passedTo": "svc", "byName": True}]
assert r.validate({"_source": {}, "namespaces": {"svc": ["svc"]}, "notCovered": {}, "otherNamespaces": [],
"operations": {"svc:RunJobFlow": entry}}) == []
def test_a_vendored_role_no_operation_reads_is_reported(corrections, tmp_path):
corrections.setattr(r, "load_models", lambda data, clients: CLUSTER)
covered = {"svc:CreateCluster": {"passedTo": ["other", "svc"], "clients": ["svc"]}}