mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(iam): check iam:PassRole from a table generated from the Service Reference (#6422)
Under IAM enforcement a request that names a role is checked for iam:PassRole only where PassedRoles has a case for its operation, so most of the operations AWS's Service Reference lists with iam:PassRole went through without it: a caller allowed to create a CodeBuild project, a Firehose stream, a Glue job or an SSM association could hand it any role in the account. Adding a case per operation took one pull request per few services. The Service Reference names, for each operation, the services its role goes to, but not the request member that names it; botocore's models give the members. tools/aws/regen_iam_passed_roles.py joins the two into src/main/resources/aws/iam-passed-roles.json: every operation listing iam:PassRole in the namespaces Floci serves over JSON, Query and Smithy RPC v2 CBOR, and in the REST services whose routes are authorized as operations, each either read from the table, read by hand in PassedRoles, or not read with a reason. Generation fails on an operation in none of the three. A member names a role when its name ends in Role, RoleArn or RoleName (a plural, or one followed by Update or Override) and it holds a string or a list or map of them, not an enum. A member whose documentation says it takes a role by name is checked on the ARN IAM holds the role under. A role the Service Reference passes to no named service, as it does Cognito's, is checked with no iam:PassedToService. The generator records its corrections with their reasons: members that pass no role (the roles a Budgets action attaches a policy to, a CodePipeline action's role, which the pipeline's role assumes, SSM target accounts' execution roles, the roles a Glue job's generated nodes assume with STS, Firehose's Snowflake role), members the rule does not see (a Cognito user pool's SMS caller roles, a Glue connection's ROLE_ARN property and a view's definer, Service Catalog's AssumeRole and LAUNCH_ROLE keys), and which service a member's role goes to where the reference names several. PassedRoles reads a table member from a JSON or CBOR body, or from Query form parameters in either list form. Its own cases now return null for an operation they do not read, and the table covers the rest. New cases read SNS's role attributes (a topic's delivery status roles, a platform application's, a Firehose subscription's and the SMS one, as the SNS handlers read the map; an attribute with no value names none), a CloudWatch Logs subscription filter policy's RoleArn, a Service Catalog launch constraint's role, by the type Service Catalog holds for the constraint on an update and in any case, since Floci keeps the type as given, and an SWF decision's Lambda role from the attributes its type names. Not read: requests that name no role, roles that are a runbook's parameter, operations whose roles go to several services without the reference saying which member goes where (EMR RunJobFlow, EKS UpdateClusterConfig, CloudWatch Logs CreateImportTask, SageMaker CreateTrainingSession), XML bodies (S3 PutBucketReplication), EC2's RequestSpotFleet, and REST services whose routes no rule maps yet. make iam-passed-roles-check, part of aws-data-check, re-derives every member from the pinned botocore; make iam-passed-roles-verify, part of iam-data-verify, checks every operation against AWS; the IAM data drift workflow now also runs on a change to the table or its generator. PassedRoleNamespacesIntegrationTest fails for a namespace Floci serves that the table neither reads nor names as not read yet.
This commit is contained in:
1 parent
cc1ce89ac0
commit
1276a8857f
15 files changed
+3646
-23
No files matched your search
@@ -908,10 +908,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
/**
|
||||
* A request that passes a role to a service also needs {@code iam:PassRole} on that role (see
|
||||
* {@link PassedRoles}), checked as the caller with {@code iam:PassedToService} naming the
|
||||
* service and the keys that say who is calling, which {@code callerArns} writes when it is known.
|
||||
* What a request names that holds roles, an instance profile, a launch template or a task
|
||||
* definition, is looked up in the request's account, as the service resolves it; one that does not
|
||||
* exist passes nothing, and the operation reports it. Returns true when the request was aborted.
|
||||
* service, when AWS's Service Reference names one, and the keys that say who is calling, which
|
||||
* {@code callerArns} writes when it is known. What a request names that holds roles, an instance
|
||||
* profile, a launch template or a task definition, is looked up in the request's account, as the
|
||||
* service resolves it; one that does not exist passes nothing, and the operation reports it. Returns
|
||||
* true when the request was aborted.
|
||||
*/
|
||||
private boolean abortIfRolePassDenied(ContainerRequestContext ctx, CallerContext caller, RequestPrincipal principal,
|
||||
CallerArns callerArns, String action, String credentialScope,
|
||||
@@ -921,7 +922,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
if (callerArns != null) {
|
||||
callerArns.putPrincipalKeys(context);
|
||||
}
|
||||
context.put("iam:PassedToService", List.of(passed.passedToService()));
|
||||
if (passed.passedToService() != null) {
|
||||
context.put("iam:PassedToService", List.of(passed.passedToService()));
|
||||
}
|
||||
if (abortIfDenied(ctx, caller, principal, "iam:PassRole", action, credentialScope,
|
||||
List.of(passed.roleArn()), List.of(context), region, accountId, akid)) {
|
||||
return true;
|
||||
@@ -980,6 +983,11 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
public Optional<String> heldRoleArn(String roleName) {
|
||||
return iamService.findRole(accountId, roleName).map(IamRole::getArn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> serviceCatalogConstraintType(String constraintId) {
|
||||
return firstFound(lookup -> lookup.serviceCatalogConstraintType(constraintId));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Where each operation's request names the roles it passes, read once from the vendored
|
||||
* {@code aws/iam-passed-roles.json}.
|
||||
*
|
||||
* <p>The file is generated by {@code tools/aws/regen_iam_passed_roles.py} from AWS's Service Reference,
|
||||
* which lists {@code iam:PassRole} among an operation's authorized actions with the services the role goes
|
||||
* to, and from botocore's model of the request, which gives the members that name a role. Every operation
|
||||
* of the namespaces it reads is in it once: with the members to read, as one {@link PassedRoles} reads by
|
||||
* hand, or as one whose request names no role it can read. {@code make iam-passed-roles-check} re-derives
|
||||
* every member from botocore and {@code make iam-passed-roles-verify} checks every operation against AWS.
|
||||
*
|
||||
* <p>A missing or malformed resource is a build defect, so loading fails with
|
||||
* {@link IllegalStateException} rather than leaving every operation it reads unchecked.
|
||||
*/
|
||||
final class PassedRoleMembers {
|
||||
|
||||
static final String RESOURCE_NAME = "aws/iam-passed-roles.json";
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
/** One step of a member path: a member, then each element of a list, each value of a map, or one key's value. */
|
||||
private static final Pattern STEP = Pattern.compile(
|
||||
"([A-Za-z][A-Za-z0-9_]*)(?:\\[([A-Za-z0-9_]*)]|\\{([A-Za-z0-9_]*)})?");
|
||||
|
||||
/** How a member path goes on from a member. */
|
||||
enum Into { NONE, LIST, MAP, KEY }
|
||||
|
||||
/**
|
||||
* A step of a member path: the member {@code name}, then for {@link Into#LIST} each element, named
|
||||
* {@code key} in the Query protocol when its shape names it, for {@link Into#MAP} each value, and for
|
||||
* {@link Into#KEY} the value under {@code key}.
|
||||
*/
|
||||
record Step(String name, Into into, String key) {
|
||||
}
|
||||
|
||||
/**
|
||||
* A member of a request that names a role, the service it is passed to (null when the Service Reference
|
||||
* names none) and whether the member takes the role by name as well as by ARN. {@code queryKeys} matches
|
||||
* the form parameters the Query protocol sends the member as; null for a member it cannot carry.
|
||||
*/
|
||||
record Member(String path, List<Step> steps, Pattern queryKeys, String passedTo, boolean byName) {
|
||||
}
|
||||
|
||||
/** The file: the members of each operation read from it, and the operations read by hand. */
|
||||
record Table(Map<String, List<Member>> members, Set<String> byHand, Set<String> notRead,
|
||||
Set<String> namespaces, Set<String> notCovered, Set<String> otherNamespaces) {
|
||||
}
|
||||
|
||||
private static final class Holder {
|
||||
static final Table TABLE = VendoredResources.read(RESOURCE_NAME, "IAM passed role table",
|
||||
PassedRoleMembers::parse);
|
||||
}
|
||||
|
||||
private PassedRoleMembers() {
|
||||
}
|
||||
|
||||
/** The members a request for {@code action} names its roles in; null when this table does not read it. */
|
||||
static List<Member> of(String action) {
|
||||
return Holder.TABLE.members().get(action);
|
||||
}
|
||||
|
||||
static Table table() {
|
||||
return Holder.TABLE;
|
||||
}
|
||||
|
||||
static Table parse(InputStream in) throws IOException {
|
||||
JsonNode document = MAPPER.readTree(in);
|
||||
JsonNode operations = document.path("operations");
|
||||
if (!operations.isObject() || operations.isEmpty()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " carries no operations");
|
||||
}
|
||||
Map<String, List<Member>> members = new LinkedHashMap<>();
|
||||
Set<String> byHand = new LinkedHashSet<>();
|
||||
Set<String> notRead = new LinkedHashSet<>();
|
||||
operations.properties().forEach(operation -> {
|
||||
JsonNode entry = operation.getValue();
|
||||
if (entry.has("byHand")) {
|
||||
byHand.add(operation.getKey());
|
||||
} else if (entry.has("notRead")) {
|
||||
notRead.add(operation.getKey());
|
||||
} else if (entry.path("roles").isArray() && !entry.path("roles").isEmpty()) {
|
||||
List<Member> roles = new ArrayList<>();
|
||||
for (JsonNode role : entry.path("roles")) {
|
||||
roles.add(member(operation.getKey(), role));
|
||||
}
|
||||
members.put(operation.getKey(), List.copyOf(roles));
|
||||
} else {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " says nothing usable for " + operation.getKey());
|
||||
}
|
||||
});
|
||||
return new Table(Map.copyOf(members), Set.copyOf(byHand), Set.copyOf(notRead),
|
||||
Set.copyOf(document.path("namespaces").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
Set.copyOf(document.path("notCovered").propertyStream().map(Map.Entry::getKey).toList()),
|
||||
Set.copyOf(document.path("otherNamespaces").valueStream().map(JsonNode::asText).toList()));
|
||||
}
|
||||
|
||||
private static Member member(String operation, JsonNode role) {
|
||||
String path = role.path("member").asText("");
|
||||
List<Step> steps = new ArrayList<>();
|
||||
for (String step : path.split("\\.", -1)) {
|
||||
Matcher matcher = STEP.matcher(step);
|
||||
if (!matcher.matches()) {
|
||||
throw new IllegalStateException(RESOURCE_NAME + " reads " + operation + " at " + path
|
||||
+ ", which is no member path");
|
||||
}
|
||||
Into into = matcher.group(2) != null ? Into.LIST : matcher.group(3) == null ? Into.NONE
|
||||
: matcher.group(3).isEmpty() ? Into.MAP : Into.KEY;
|
||||
String key = into == Into.LIST ? matcher.group(2) : into == Into.KEY ? matcher.group(3) : null;
|
||||
steps.add(new Step(matcher.group(1), into, key));
|
||||
}
|
||||
String passedTo = role.hasNonNull("passedTo") ? role.get("passedTo").asText() : null;
|
||||
return new Member(path, List.copyOf(steps), queryKeys(steps), passedTo, role.path("byName").asBoolean(false));
|
||||
}
|
||||
|
||||
/**
|
||||
* The form parameters the Query protocol sends a member as: a list's elements numbered under its name,
|
||||
* generically as {@code member.N}, under the name its shape gives them or bare, as {@link AwsQueryLists}
|
||||
* reads them, and a map's values as {@code entry.N.value}. A step into one key of a map is not read from a
|
||||
* form, whose keys and values are separate parameters.
|
||||
*/
|
||||
private static Pattern queryKeys(List<Step> steps) {
|
||||
StringBuilder regex = new StringBuilder();
|
||||
for (Step step : steps) {
|
||||
if (step.into() == Into.KEY) {
|
||||
return null;
|
||||
}
|
||||
if (!regex.isEmpty()) {
|
||||
regex.append("\\.");
|
||||
}
|
||||
regex.append(Pattern.quote(step.name()));
|
||||
if (step.into() == Into.LIST) {
|
||||
regex.append(step.key().isEmpty() ? "(\\.member)?" : "(\\.member|\\." + Pattern.quote(step.key()) + ")?")
|
||||
.append("\\.\\d+");
|
||||
} else if (step.into() == Into.MAP) {
|
||||
regex.append("\\.entry\\.\\d+\\.value");
|
||||
}
|
||||
}
|
||||
return Pattern.compile(regex.toString());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
|
||||
@@ -10,6 +11,7 @@ import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -21,7 +23,14 @@ import java.util.regex.Pattern;
|
||||
* The IAM user guide: "To pass a role (and its permissions) to an AWS service, a user must have
|
||||
* permissions to pass the role to the service." AWS's Service Reference names, for each operation
|
||||
* that passes one, the service the role goes to, which the check offers as {@code iam:PassedToService};
|
||||
* where the request carries the role differs per operation and is listed here.
|
||||
* where the request carries the role differs per operation.
|
||||
*
|
||||
* <p>Most operations name their roles in plain request members, which {@link PassedRoleMembers} reads
|
||||
* from a table generated from the Service Reference and botocore's models. A member that takes a role
|
||||
* by name is read as the role IAM holds under that name, or else the one the name gives in the
|
||||
* request's account, and a role the Service Reference passes to no named service is checked with no
|
||||
* {@code iam:PassedToService}. The operations below are read here instead, since their roles are not
|
||||
* such a member.
|
||||
*
|
||||
* <p>An EC2 request names an instance profile rather than a role, and passes the roles the profile
|
||||
* holds. Launching from a launch template passes nothing here: the EC2 user guide warns that a user
|
||||
@@ -89,6 +98,20 @@ import java.util.regex.Pattern;
|
||||
* {@code IAM_ROLE_ARN} setting, as SQL Server's backup and audit options do. A DMS endpoint passes to
|
||||
* {@code dms.amazonaws.com} its service access role and the roles its settings name for each engine, and
|
||||
* a replication instance the role its Kerberos settings name.
|
||||
*
|
||||
* <p>An SNS topic's delivery status roles are attributes, which "are used to give Amazon SNS write access
|
||||
* to use CloudWatch Logs on your behalf": {@code <ENDPOINT>SuccessFeedbackRoleArn} and
|
||||
* {@code <ENDPOINT>FailureFeedbackRoleArn} for each kind of endpoint. So are a platform application's
|
||||
* {@code SuccessFeedbackRoleArn} and {@code FailureFeedbackRoleArn}, a Firehose subscription's
|
||||
* {@code SubscriptionRoleArn} and the SMS {@code DeliveryStatusIAMRole}; all go to {@code sns.amazonaws.com}.
|
||||
* A CloudWatch Logs subscription filter policy names its role in its document: "To perform a
|
||||
* PutAccountPolicy subscription filter operation for any destination except a Lambda function, you must
|
||||
* also have the iam:PassRole permission."
|
||||
*
|
||||
* <p>A Service Catalog launch constraint names its launch role in its parameters document, by
|
||||
* {@code RoleArn} or by {@code LocalRoleName}, which names the role without its path, so it is checked on
|
||||
* the ARN IAM holds the role under. An SWF decision that starts a workflow execution names its Lambda role
|
||||
* in the attributes its {@code decisionType} names.
|
||||
*/
|
||||
final class PassedRoles {
|
||||
|
||||
@@ -118,6 +141,27 @@ final class PassedRoles {
|
||||
private static final String REDSHIFT_SERVERLESS = ServicePrincipals.of("redshift-serverless");
|
||||
private static final String RDS = ServicePrincipals.of("rds");
|
||||
private static final String DMS = ServicePrincipals.of("dms");
|
||||
private static final String SNS = ServicePrincipals.of("sns");
|
||||
private static final String LOGS = ServicePrincipals.of("logs");
|
||||
private static final String SERVICE_CATALOG = ServicePrincipals.of("servicecatalog");
|
||||
private static final String SWF = ServicePrincipals.of("swf");
|
||||
|
||||
/** The topic attributes that name a delivery status role, a success and a failure one per kind of endpoint. */
|
||||
private static final Set<String> SNS_TOPIC_ROLES = Set.of(
|
||||
"ApplicationSuccessFeedbackRoleArn", "ApplicationFailureFeedbackRoleArn",
|
||||
"FirehoseSuccessFeedbackRoleArn", "FirehoseFailureFeedbackRoleArn",
|
||||
"HTTPSuccessFeedbackRoleArn", "HTTPFailureFeedbackRoleArn",
|
||||
"LambdaSuccessFeedbackRoleArn", "LambdaFailureFeedbackRoleArn",
|
||||
"SQSSuccessFeedbackRoleArn", "SQSFailureFeedbackRoleArn");
|
||||
private static final Set<String> SNS_SUBSCRIPTION_ROLES = Set.of("SubscriptionRoleArn");
|
||||
private static final Set<String> SNS_PLATFORM_ROLES = Set.of("SuccessFeedbackRoleArn", "FailureFeedbackRoleArn");
|
||||
private static final Set<String> SNS_SMS_ROLES = Set.of("DeliveryStatusIAMRole");
|
||||
private static final String SUBSCRIPTION_FILTER_POLICY = "SUBSCRIPTION_FILTER_POLICY";
|
||||
private static final String LAUNCH_CONSTRAINT = "LAUNCH";
|
||||
/** The SWF decisions that start a workflow execution, and the member each carries its attributes in. */
|
||||
private static final Map<String, String> SWF_EXECUTION_DECISIONS = Map.of(
|
||||
"ContinueAsNewWorkflowExecution", "continueAsNewWorkflowExecutionDecisionAttributes",
|
||||
"StartChildWorkflowExecution", "startChildWorkflowExecutionDecisionAttributes");
|
||||
|
||||
/** The RDS operations whose request takes a {@code MonitoringRoleArn}. */
|
||||
private static final Set<String> RDS_MONITORING_ROLE = Set.of("rds:CreateDBCluster", "rds:CreateDBInstance",
|
||||
@@ -162,7 +206,7 @@ final class PassedRoles {
|
||||
private static final String DEFAULT_AUTOSCALING_ROLE =
|
||||
":role/aws-service-role/" + AUTOSCALING + "/AWSServiceRoleForAutoScaling";
|
||||
|
||||
/** A role a request passes, and the service principal it is passed to. */
|
||||
/** A role a request passes, and the service principal it is passed to; null when AWS names none. */
|
||||
record PassedRole(String roleArn, String passedToService) {
|
||||
}
|
||||
|
||||
@@ -199,6 +243,9 @@ final class PassedRoles {
|
||||
|
||||
/** The ARN, path included, of the role IAM holds under {@code roleName}; empty when it holds none. */
|
||||
Optional<String> heldRoleArn(String roleName);
|
||||
|
||||
/** The type of the Service Catalog constraint {@code constraintId}; empty when there is none. */
|
||||
Optional<String> serviceCatalogConstraintType(String constraintId);
|
||||
}
|
||||
|
||||
private PassedRoles() {
|
||||
@@ -206,6 +253,15 @@ final class PassedRoles {
|
||||
|
||||
/** The roles a request for {@code action} passes; empty when the operation passes none or the request names none. */
|
||||
static List<PassedRole> of(String action, ContainerRequestContext ctx, Lookups lookups) {
|
||||
List<PassedRole> byHand = byHand(action, ctx, lookups);
|
||||
return byHand != null ? byHand : fromTable(PassedRoleMembers.of(action), ctx, lookups);
|
||||
}
|
||||
|
||||
/**
|
||||
* The roles a request for {@code action} passes, for an operation read here rather than from the table;
|
||||
* null for any other.
|
||||
*/
|
||||
static List<PassedRole> byHand(String action, ContainerRequestContext ctx, Lookups lookups) {
|
||||
return switch (action) {
|
||||
case "lambda:CreateFunction", "lambda:UpdateFunctionConfiguration" -> fromJson(ctx, LAMBDA, "Role");
|
||||
case "lambda:CreateWebFunction" ->
|
||||
@@ -268,10 +324,211 @@ final class PassedRoles {
|
||||
case "dms:CreateEndpoint", "dms:ModifyEndpoint" -> dmsEndpointRoles(jsonBody(ctx));
|
||||
case "dms:CreateReplicationInstance", "dms:ModifyReplicationInstance" ->
|
||||
fromJson(ctx, DMS, "KerberosAuthenticationSettings", "KeyCacheSecretIamArn");
|
||||
default -> List.of();
|
||||
case "sns:CreateTopic" -> snsAttributeRoles(ctx, "Attributes", SNS_TOPIC_ROLES);
|
||||
case "sns:SetTopicAttributes" -> snsAttributeRole(ctx, SNS_TOPIC_ROLES);
|
||||
case "sns:Subscribe" -> snsAttributeRoles(ctx, "Attributes", SNS_SUBSCRIPTION_ROLES);
|
||||
case "sns:SetSubscriptionAttributes" -> snsAttributeRole(ctx, SNS_SUBSCRIPTION_ROLES);
|
||||
case "sns:CreatePlatformApplication", "sns:SetPlatformApplicationAttributes" ->
|
||||
snsAttributeRoles(ctx, "Attributes", SNS_PLATFORM_ROLES);
|
||||
case "sns:SetSMSAttributes" -> snsAttributeRoles(ctx, "attributes", SNS_SMS_ROLES);
|
||||
case "logs:PutAccountPolicy" -> subscriptionFilterPolicyRole(jsonBody(ctx));
|
||||
case "servicecatalog:CreateConstraint" -> launchConstraintRoles(jsonBody(ctx), lookups, false);
|
||||
case "servicecatalog:UpdateConstraint" -> launchConstraintRoles(jsonBody(ctx), lookups, true);
|
||||
case "swf:RespondDecisionTaskCompleted" -> swfDecisionRoles(jsonBody(ctx));
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The roles a request names in the members the table gives for its operation: from its form parameters
|
||||
* when it comes in the Query protocol, and from its JSON or CBOR body otherwise.
|
||||
*/
|
||||
private static List<PassedRole> fromTable(List<PassedRoleMembers.Member> members, ContainerRequestContext ctx,
|
||||
Lookups lookups) {
|
||||
if (members == null) {
|
||||
return List.of();
|
||||
}
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
JsonNode body = form.isEmpty() ? jsonBody(ctx) : null;
|
||||
List<PassedRole> passed = new ArrayList<>();
|
||||
for (PassedRoleMembers.Member member : members) {
|
||||
List<String> roles = new ArrayList<>();
|
||||
if (!form.isEmpty()) {
|
||||
if (member.queryKeys() != null) {
|
||||
form.forEach((key, value) -> {
|
||||
if (member.queryKeys().matcher(key).matches()) {
|
||||
roles.add(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
collect(body, member.steps(), 0, roles);
|
||||
}
|
||||
passed.addAll(passed(member.byName() ? heldOrNamedRoles(roles, lookups) : roles,
|
||||
member.passedTo() == null ? null : ServicePrincipals.of(member.passedTo())));
|
||||
}
|
||||
return passed;
|
||||
}
|
||||
|
||||
private static void collect(JsonNode node, List<PassedRoleMembers.Step> steps, int index, List<String> found) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
if (index == steps.size()) {
|
||||
if (node.isTextual()) {
|
||||
found.add(node.asText());
|
||||
}
|
||||
return;
|
||||
}
|
||||
PassedRoleMembers.Step step = steps.get(index);
|
||||
JsonNode value = node.get(step.name());
|
||||
switch (step.into()) {
|
||||
case NONE -> collect(value, steps, index + 1, found);
|
||||
case KEY -> collect(value == null ? null : value.get(step.key()), steps, index + 1, found);
|
||||
case LIST, MAP -> {
|
||||
if (value != null && (step.into() == PassedRoleMembers.Into.LIST ? value.isArray() : value.isObject())) {
|
||||
for (JsonNode element : value) {
|
||||
collect(element, steps, index + 1, found);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Roles given by ARN or by name: a name is the role IAM holds under it, or else the one it gives. */
|
||||
private static List<String> heldOrNamedRoles(List<String> roles, Lookups lookups) {
|
||||
List<String> arns = new ArrayList<>();
|
||||
for (String role : roles) {
|
||||
if (!role.isBlank()) {
|
||||
arns.add(role.startsWith("arn:") ? role
|
||||
: lookups.heldRoleArn(role).orElseGet(() -> lookups.roleArn(role)));
|
||||
}
|
||||
}
|
||||
return arns;
|
||||
}
|
||||
|
||||
/**
|
||||
* The roles among an SNS request's attributes {@code map}, read as the SNS handlers read the map: from a
|
||||
* form, each {@code map.entry.N} from 1 up to the first with no key, the last value of a key named twice;
|
||||
* from a JSON body, the {@code map} object.
|
||||
*/
|
||||
private static List<PassedRole> snsAttributeRoles(ContainerRequestContext ctx, String map, Set<String> roleAttributes) {
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
Map<String, String> attributes = new LinkedHashMap<>();
|
||||
if (!form.isEmpty()) {
|
||||
for (int i = 1; form.get(map + ".entry." + i + ".key") != null; i++) {
|
||||
attributes.put(form.get(map + ".entry." + i + ".key"), form.get(map + ".entry." + i + ".value"));
|
||||
}
|
||||
} else {
|
||||
JsonNode body = jsonBody(ctx);
|
||||
JsonNode values = body == null ? null : body.get(map);
|
||||
if (values != null && values.isObject()) {
|
||||
values.properties().forEach(entry -> attributes.put(entry.getKey(), entry.getValue().asText(null)));
|
||||
}
|
||||
}
|
||||
List<String> roles = new ArrayList<>();
|
||||
attributes.forEach((name, value) -> {
|
||||
if (roleAttributes.contains(name)) {
|
||||
roles.add(value);
|
||||
}
|
||||
});
|
||||
return passed(roles, SNS);
|
||||
}
|
||||
|
||||
/**
|
||||
* The role an SNS {@code AttributeValue} names, when its {@code AttributeName} is one that names a role; a
|
||||
* request with no value names none, and is left to SNS to answer.
|
||||
*/
|
||||
private static List<PassedRole> snsAttributeRole(ContainerRequestContext ctx, Set<String> roleAttributes) {
|
||||
Map<String, String> form = IamConditionContextResolver.formParameters(ctx);
|
||||
String name;
|
||||
String value;
|
||||
if (!form.isEmpty()) {
|
||||
name = form.get("AttributeName");
|
||||
value = form.get("AttributeValue");
|
||||
} else {
|
||||
JsonNode body = jsonBody(ctx);
|
||||
name = body == null ? null : body.path("AttributeName").asText(null);
|
||||
value = body == null ? null : body.path("AttributeValue").asText(null);
|
||||
}
|
||||
if (name == null || value == null || !roleAttributes.contains(name)) {
|
||||
return List.of();
|
||||
}
|
||||
return passed(List.of(value), SNS);
|
||||
}
|
||||
|
||||
/** The role a CloudWatch Logs subscription filter policy's document names; another policy names none. */
|
||||
private static List<PassedRole> subscriptionFilterPolicyRole(JsonNode body) {
|
||||
if (body == null || !SUBSCRIPTION_FILTER_POLICY.equals(body.path("policyType").asText(null))) {
|
||||
return List.of();
|
||||
}
|
||||
return passed(values(embeddedJson(body.get("policyDocument")), "RoleArn"), LOGS);
|
||||
}
|
||||
|
||||
/**
|
||||
* The launch role a Service Catalog launch constraint names in its {@code Parameters}, a JSON document,
|
||||
* by {@code RoleArn} or by {@code LocalRoleName}, which names the role of that name in the caller's
|
||||
* account without its path. A constraint of another type names no launch role. An update is read by
|
||||
* the type Floci keeps for the constraint, since its request names none. The type is matched in any
|
||||
* case, since Floci keeps it as given.
|
||||
*/
|
||||
private static List<PassedRole> launchConstraintRoles(JsonNode body, Lookups lookups, boolean update) {
|
||||
JsonNode parameters = body == null ? null : embeddedJson(body.get("Parameters"));
|
||||
if (parameters == null) {
|
||||
return List.of();
|
||||
}
|
||||
String type;
|
||||
if (update) {
|
||||
String id = blankToNull(body.path("Id").asText(null));
|
||||
type = id == null ? null : lookups.serviceCatalogConstraintType(id).orElse(null);
|
||||
} else {
|
||||
type = body.path("Type").asText(null);
|
||||
}
|
||||
if (!LAUNCH_CONSTRAINT.equalsIgnoreCase(type)) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> roles = new ArrayList<>(values(parameters, "RoleArn"));
|
||||
for (String name : values(parameters, "LocalRoleName")) {
|
||||
if (!name.isBlank()) {
|
||||
roles.add(lookups.heldRoleArn(name).orElseGet(() -> lookups.roleArn(name)));
|
||||
}
|
||||
}
|
||||
return passed(roles, SERVICE_CATALOG);
|
||||
}
|
||||
|
||||
/**
|
||||
* The roles of the decisions that start a workflow execution, each read from the attributes its
|
||||
* {@code decisionType} names, as the SWF handler reads a decision.
|
||||
*/
|
||||
private static List<PassedRole> swfDecisionRoles(JsonNode body) {
|
||||
JsonNode decisions = body == null ? null : body.get("decisions");
|
||||
if (decisions == null || !decisions.isArray()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> roles = new ArrayList<>();
|
||||
for (JsonNode decision : decisions) {
|
||||
String attributes = SWF_EXECUTION_DECISIONS.get(decision.path("decisionType").asText(""));
|
||||
if (attributes != null) {
|
||||
roles.addAll(values(decision, attributes, "lambdaRole"));
|
||||
}
|
||||
}
|
||||
return passed(roles, SWF);
|
||||
}
|
||||
|
||||
/** The JSON document a string member holds; null when the member holds no JSON. */
|
||||
private static JsonNode embeddedJson(JsonNode member) {
|
||||
if (member == null || !member.isTextual()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return MAPPER.readTree(member.asText());
|
||||
} catch (JsonProcessingException e) {
|
||||
// A document that is not JSON has no member to name a role in.
|
||||
LOG.debugv(e, "Embedded document is not JSON, so it passes no role");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The role AddRoleToInstanceProfile adds, which {@code RoleName} names without its path: the ARN IAM
|
||||
* holds it under, or else the one the name gives, so a role IAM does not hold is checked as named.
|
||||
|
||||
@@ -7,8 +7,9 @@ import java.util.Optional;
|
||||
* Looks up what a stored resource holds that the {@code iam:PassRole} check of a request needs, for
|
||||
* the operations that pass a role the request does not name itself: an ECS task started from a task
|
||||
* definition runs with the definition's roles, a self-managed StackSet that names no
|
||||
* administration role uses the default one, and an Auto Scaling group launches its instances with
|
||||
* the instance profile of its launch template, or of the instance its launch configuration was made from.
|
||||
* administration role uses the default one, an Auto Scaling group launches its instances with
|
||||
* the instance profile of its launch template, or of the instance its launch configuration was made from,
|
||||
* and a Service Catalog constraint update names no type, which says whether it sets a launch role.
|
||||
*
|
||||
* <p>Implemented by the services that own those resources, each answering for its own and leaving
|
||||
* the default for the rest; consumed lazily by {@code IamEnforcementFilter} via
|
||||
@@ -61,4 +62,9 @@ public interface PassedRoleLookup {
|
||||
String version, String region) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** The type of the Service Catalog constraint {@code constraintId}; empty when there is none. */
|
||||
default Optional<String> serviceCatalogConstraintType(String constraintId) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.iam.PassedRoleLookup;
|
||||
import io.github.hectorvent.floci.services.organizations.OrganizationsService;
|
||||
import io.github.hectorvent.floci.services.organizations.model.CreateAccountStatus;
|
||||
import io.github.hectorvent.floci.services.organizations.model.OrganizationAccount;
|
||||
@@ -22,7 +23,7 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@ApplicationScoped
|
||||
public class ServiceCatalogService {
|
||||
public class ServiceCatalogService implements PassedRoleLookup {
|
||||
|
||||
static final String CONTROL_TOWER_PORTFOLIO_ID = "port-flocicontrol1";
|
||||
static final String CONTROL_TOWER_PORTFOLIO_NAME = "AWS Control Tower Account Factory Portfolio";
|
||||
@@ -998,6 +999,12 @@ public class ServiceCatalogService {
|
||||
return require(associationStore, id, "constraint").deepCopy();
|
||||
}
|
||||
|
||||
/** The constraint's type, which says whether an update of its parameters sets a launch role. */
|
||||
@Override
|
||||
public Optional<String> serviceCatalogConstraintType(String constraintId) {
|
||||
return associationStore.get(constraintId).map(constraint -> constraint.path("Type").asText(""));
|
||||
}
|
||||
|
||||
public ObjectNode describeProvisionedProduct(String id, String name) {
|
||||
if (id != null && !id.isBlank()) {
|
||||
return require(provisionedProductStore, id, "provisioned product").deepCopy();
|
||||
|
||||
Reference in new issue
Block a user