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:
Priamo Germosen authored and GitHub committed 2026-10-24 08:38:14 -05:00
1 parent cc1ce89ac0
commit 1276a8857f
15 files changed
+3646 -23

No files matched your search

@@ -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;
}
}
@@ -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);
}
@@ -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);
}