mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(stepfunctions): authorize a Lambda task as the state machine's execution role (#5554)
Under IAM enforcement, a Lambda task naming a function in another account was refused outright, because Floci evaluated no Lambda function policy when #5079 added the check, and a task on a function in the state machine's own account was not checked at all. Function policies now take part in authorization (#5476), so a task is decided the way Lambda decides the Invoke call the execution role makes (Step Functions Developer Guide, "I can't invoke a Lambda function from another account"): within one account the role's policies or the function's policy can allow it, and across accounts both have to (IAM User Guide, cross-account policy evaluation logic). - LambdaTaskAuthorizer evaluates the role's policies, its permissions boundary and its account's SCPs together with the function policy LambdaResourcePolicyProvider supplies. The role ARN has to name an existing role, path included, matched as STS AssumeRole matches one (IamService.roleArnMatches), and the role is evaluated under the ARN IAM holds for it. - The task is authorized against the function ARN LambdaArnUtils.functionArn gives for its reference: a full ARN as written, a name or partial ARN completed in the state machine's partition, Region and account, with the version or alias it names, as Lambda authorizes an invoke. - A task whose Credentials name a role invokes the function as that role, once the execution role has assumed it (Developer Guide, Task state "Credentials"). The role's trust policy has to allow the execution role, with the state machine's ARN as sts:ExternalId, which the cross-account tutorial's trust policy checks. The execution role's own policies have to allow sts:AssumeRole on the role too when it is in another account, or when the trust policy names only the execution role's account, since an account principal delegates to the account (IAM User Guide, "AWS account principals"); AssumeRolePolicyEvaluator.decide tells the two grants apart. RoleArn is read the way the task's Parameters or Arguments are. A role the execution role cannot assume fails the task with States.Permissions, the Developer Guide's error for a task without the privileges to run. - A refusal to invoke fails the task with Lambda.AccessDeniedException. The cause names the role's session as the Step Functions Developer Guide shows it (arn:aws:sts::<account>:assumed-role/<role>) and ends in the IAM User Guide's context for the policy type that refused it, explicit denials first, each in AWS's evaluation order: service control policies, the resource-based policy or role trust policy, identity-based policies, the permissions boundary.
This commit is contained in:
1 parent
287d683da7
commit
c6c2c609c3
10 files changed
+1409
-71
No files matched your search
+85
-44
@@ -48,9 +48,37 @@ public class AssumeRolePolicyEvaluator {
|
||||
this.policyEvaluator = policyEvaluator;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a trust policy answers a caller's {@code sts:AssumeRole}. A {@code Principal} naming an
|
||||
* account, by its id or its root ARN, delegates the decision to that account's own policies
|
||||
* (IAM User Guide, "AWS account principals"), so an Allow through one is told apart from an
|
||||
* Allow naming the caller.
|
||||
*/
|
||||
public enum TrustDecision {
|
||||
/** An Allow names the caller, its role or every principal. */
|
||||
ALLOW,
|
||||
/** An Allow names the caller's account and nothing narrower. */
|
||||
ALLOW_ACCOUNT,
|
||||
EXPLICIT_DENY,
|
||||
NEUTRAL
|
||||
}
|
||||
|
||||
private enum PrincipalMatch { NONE, ACCOUNT, CALLER }
|
||||
|
||||
/**
|
||||
* Returns true if {@code trustPolicyDocument} allows the caller (identified by
|
||||
* {@code callerArn}, in {@code callerAccount}) to perform {@code sts:AssumeRole}.
|
||||
* {@code callerArn}, in {@code callerAccount}) to perform {@code sts:AssumeRole}, through any
|
||||
* principal: see {@link #decide} for the arguments.
|
||||
*/
|
||||
public boolean allows(String trustPolicyDocument, String callerArn, String principalArn,
|
||||
String callerAccount, Map<String, List<String>> requestContext) {
|
||||
TrustDecision decision = decide(trustPolicyDocument, callerArn, principalArn, callerAccount, requestContext);
|
||||
return decision == TrustDecision.ALLOW || decision == TrustDecision.ALLOW_ACCOUNT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides whether {@code trustPolicyDocument} lets the caller (identified by {@code callerArn},
|
||||
* in {@code callerAccount}) perform {@code sts:AssumeRole}, and through which principal.
|
||||
*
|
||||
* <p>{@code principalArn} is the caller's IAM identity: the user's ARN, or for a role session
|
||||
* the role's own ARN, path included, which the session ARN does not carry. A {@code Principal}
|
||||
@@ -58,40 +86,40 @@ public class AssumeRolePolicyEvaluator {
|
||||
* {@code requestContext} holds the other condition keys the request carries, such as
|
||||
* {@code sts:ExternalId}; each statement's {@code Condition} is evaluated against both.
|
||||
*
|
||||
* <p>A null/blank/unparseable document or one with no matching {@code Allow} denies.
|
||||
* <p>A null/blank/unparseable document or one with no matching statement is
|
||||
* {@link TrustDecision#NEUTRAL}.
|
||||
*/
|
||||
public boolean allows(String trustPolicyDocument, String callerArn, String principalArn,
|
||||
String callerAccount, Map<String, List<String>> requestContext) {
|
||||
public TrustDecision decide(String trustPolicyDocument, String callerArn, String principalArn,
|
||||
String callerAccount, Map<String, List<String>> requestContext) {
|
||||
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
|
||||
return false;
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
JsonNode statements;
|
||||
try {
|
||||
statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
|
||||
return false;
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
if (!isWellFormed(statements)) {
|
||||
return false;
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
Map<String, List<String>> context = new HashMap<>(requestContext);
|
||||
if (principalArn != null) {
|
||||
context.put("aws:PrincipalArn", List.of(principalArn));
|
||||
}
|
||||
boolean allow = false;
|
||||
if (statements.isArray()) {
|
||||
for (JsonNode stmt : statements) {
|
||||
switch (evaluateStatement(stmt, callerArn, principalArn, callerAccount, context)) {
|
||||
case DENY -> { return false; }
|
||||
case ALLOW -> allow = true;
|
||||
case NO_MATCH -> { }
|
||||
}
|
||||
Iterable<JsonNode> statementList = statements.isArray() ? statements : List.of(statements);
|
||||
TrustDecision decision = TrustDecision.NEUTRAL;
|
||||
for (JsonNode stmt : statementList) {
|
||||
TrustDecision match = evaluateStatement(stmt, callerArn, principalArn, callerAccount, context);
|
||||
if (match == TrustDecision.EXPLICIT_DENY) {
|
||||
return TrustDecision.EXPLICIT_DENY;
|
||||
}
|
||||
if (match == TrustDecision.ALLOW || decision == TrustDecision.NEUTRAL) {
|
||||
decision = match;
|
||||
}
|
||||
} else if (statements.isObject()) {
|
||||
return evaluateStatement(statements, callerArn, principalArn, callerAccount, context) == Match.ALLOW;
|
||||
}
|
||||
return allow;
|
||||
return decision;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -215,18 +243,23 @@ public class AssumeRolePolicyEvaluator {
|
||||
return true;
|
||||
}
|
||||
|
||||
private Match evaluateStatement(JsonNode stmt, String callerArn, String principalArn,
|
||||
String callerAccount, Map<String, List<String>> context) {
|
||||
private TrustDecision evaluateStatement(JsonNode stmt, String callerArn, String principalArn,
|
||||
String callerAccount, Map<String, List<String>> context) {
|
||||
if (!actionApplies(stmt)) {
|
||||
return Match.NO_MATCH;
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
if (!matchesPrincipal(stmt.get("Principal"), callerArn, principalArn, callerAccount)) {
|
||||
return Match.NO_MATCH;
|
||||
PrincipalMatch principal = matchPrincipal(stmt.get("Principal"), callerArn, principalArn, callerAccount);
|
||||
if (principal == PrincipalMatch.NONE) {
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context)) {
|
||||
return Match.NO_MATCH;
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
return effectOf(stmt);
|
||||
return switch (effectOf(stmt)) {
|
||||
case DENY -> TrustDecision.EXPLICIT_DENY;
|
||||
case ALLOW -> principal == PrincipalMatch.CALLER ? TrustDecision.ALLOW : TrustDecision.ALLOW_ACCOUNT;
|
||||
case NO_MATCH -> TrustDecision.NEUTRAL;
|
||||
};
|
||||
}
|
||||
|
||||
private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal) {
|
||||
@@ -315,58 +348,66 @@ public class AssumeRolePolicyEvaluator {
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean matchesPrincipal(JsonNode principalNode, String callerArn, String principalArn,
|
||||
String callerAccount) {
|
||||
/** The narrowest of the statement's principals that matches the caller wins: the caller over its account. */
|
||||
private PrincipalMatch matchPrincipal(JsonNode principalNode, String callerArn, String principalArn,
|
||||
String callerAccount) {
|
||||
if (principalNode == null) {
|
||||
return false;
|
||||
return PrincipalMatch.NONE;
|
||||
}
|
||||
// Principal: "*"
|
||||
if (principalNode.isTextual()) {
|
||||
return "*".equals(principalNode.asText());
|
||||
return "*".equals(principalNode.asText()) ? PrincipalMatch.CALLER : PrincipalMatch.NONE;
|
||||
}
|
||||
if (!principalNode.isObject()) {
|
||||
return false;
|
||||
return PrincipalMatch.NONE;
|
||||
}
|
||||
// Only the AWS principal type can match a SigV4 caller.
|
||||
JsonNode aws = principalNode.get("AWS");
|
||||
if (aws == null) {
|
||||
return false;
|
||||
return PrincipalMatch.NONE;
|
||||
}
|
||||
if (aws.isTextual()) {
|
||||
return matchesAwsPrincipal(aws.asText(), callerArn, principalArn, callerAccount);
|
||||
return matchAwsPrincipal(aws.asText(), callerArn, principalArn, callerAccount);
|
||||
}
|
||||
PrincipalMatch match = PrincipalMatch.NONE;
|
||||
if (aws.isArray()) {
|
||||
for (JsonNode entry : aws) {
|
||||
if (entry.isTextual()
|
||||
&& matchesAwsPrincipal(entry.asText(), callerArn, principalArn, callerAccount)) {
|
||||
return true;
|
||||
PrincipalMatch entryMatch = entry.isTextual()
|
||||
? matchAwsPrincipal(entry.asText(), callerArn, principalArn, callerAccount)
|
||||
: PrincipalMatch.NONE;
|
||||
if (entryMatch == PrincipalMatch.CALLER) {
|
||||
return PrincipalMatch.CALLER;
|
||||
}
|
||||
if (entryMatch == PrincipalMatch.ACCOUNT) {
|
||||
match = PrincipalMatch.ACCOUNT;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return match;
|
||||
}
|
||||
|
||||
private boolean matchesAwsPrincipal(String principal, String callerArn, String principalArn,
|
||||
String callerAccount) {
|
||||
private PrincipalMatch matchAwsPrincipal(String principal, String callerArn, String principalArn,
|
||||
String callerAccount) {
|
||||
if (principal == null) {
|
||||
return false;
|
||||
return PrincipalMatch.NONE;
|
||||
}
|
||||
if ("*".equals(principal)) {
|
||||
return true;
|
||||
return PrincipalMatch.CALLER;
|
||||
}
|
||||
// Bare 12-digit account id, or an account-root ARN → matches any principal in that account.
|
||||
if (principal.matches("\\d{12}")) {
|
||||
return principal.equals(callerAccount);
|
||||
return principal.equals(callerAccount) ? PrincipalMatch.ACCOUNT : PrincipalMatch.NONE;
|
||||
}
|
||||
Matcher rootMatcher = ACCOUNT_ROOT_ARN.matcher(principal);
|
||||
if (rootMatcher.matches()) {
|
||||
return rootMatcher.group(1).equals(callerAccount);
|
||||
return rootMatcher.group(1).equals(callerAccount) ? PrincipalMatch.ACCOUNT : PrincipalMatch.NONE;
|
||||
}
|
||||
// Otherwise an exact (glob-capable) principal ARN: the caller's own ARN, which for a role
|
||||
// session is its assumed-role session ARN, or the role's ARN for a Principal naming the role.
|
||||
if (callerArn != null && IamPolicyEvaluator.globMatches(principal, callerArn)) {
|
||||
return true;
|
||||
return PrincipalMatch.CALLER;
|
||||
}
|
||||
return principalArn != null && IamPolicyEvaluator.globMatches(principal, principalArn);
|
||||
return principalArn != null && IamPolicyEvaluator.globMatches(principal, principalArn)
|
||||
? PrincipalMatch.CALLER : PrincipalMatch.NONE;
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,7 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
@@ -255,6 +256,7 @@ public class AslExecutor {
|
||||
private final RdsDataService rdsDataService;
|
||||
private final RedshiftDataJsonHandler redshiftDataHandler;
|
||||
private final ServiceRegistry serviceRegistry;
|
||||
private final LambdaTaskAuthorizer lambdaTaskAuthorizer;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final Configuration jsonPathConfiguration;
|
||||
private final JsonataEvaluator jsonataEvaluator;
|
||||
@@ -285,13 +287,14 @@ public class AslExecutor {
|
||||
ObjectMapper objectMapper, JsonataEvaluator jsonataEvaluator,
|
||||
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
|
||||
CustomResourceLiveness customResourceLiveness, RedshiftDataJsonHandler redshiftDataHandler,
|
||||
ServiceRegistry serviceRegistry) {
|
||||
ServiceRegistry serviceRegistry, LambdaTaskAuthorizer lambdaTaskAuthorizer) {
|
||||
this(lambdaExecutor, targetResolver, dynamoDb, dynamoDbJsonHandler,
|
||||
sqsJsonHandler, snsJsonHandler, cloudFormationHandler,
|
||||
ec2Service, s3Service, ecsService, ecsJsonHandler,
|
||||
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
|
||||
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
|
||||
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry);
|
||||
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, redshiftDataHandler, serviceRegistry,
|
||||
lambdaTaskAuthorizer);
|
||||
}
|
||||
|
||||
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaTargetResolver targetResolver,
|
||||
@@ -306,8 +309,10 @@ public class AslExecutor {
|
||||
Instance<StepFunctionsService> sfnService, EmulatorConfig config, Vertx vertx,
|
||||
CustomResourceLiveness customResourceLiveness,
|
||||
Clock clock, Sleeper sleeper, Integer maxWaitSecondsOverride,
|
||||
RedshiftDataJsonHandler redshiftDataHandler, ServiceRegistry serviceRegistry) {
|
||||
RedshiftDataJsonHandler redshiftDataHandler, ServiceRegistry serviceRegistry,
|
||||
LambdaTaskAuthorizer lambdaTaskAuthorizer) {
|
||||
this.serviceRegistry = serviceRegistry;
|
||||
this.lambdaTaskAuthorizer = lambdaTaskAuthorizer;
|
||||
this.customResourceLiveness = customResourceLiveness;
|
||||
this.redshiftDataHandler = redshiftDataHandler;
|
||||
this.lambdaExecutor = lambdaExecutor;
|
||||
@@ -364,7 +369,7 @@ public class AslExecutor {
|
||||
ec2Service, s3Service, ecsService, ecsJsonHandler,
|
||||
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
|
||||
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
|
||||
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null);
|
||||
Clock.systemUTC(), TimeUnit.NANOSECONDS::sleep, null, null, null, null);
|
||||
}
|
||||
|
||||
// Kept for tests that do not exercise the Redshift Data API integration.
|
||||
@@ -385,7 +390,7 @@ public class AslExecutor {
|
||||
ec2Service, s3Service, ecsService, ecsJsonHandler,
|
||||
eventBridgeHandler, schedulerService, schedulerController, rdsDataService,
|
||||
objectMapper, jsonataEvaluator, sfnService, config, vertx, customResourceLiveness,
|
||||
clock, sleeper, maxWaitSecondsOverride, null, null);
|
||||
clock, sleeper, maxWaitSecondsOverride, null, null, null);
|
||||
}
|
||||
|
||||
AslExecutor(LambdaExecutorService lambdaExecutor, LambdaFunctionStore functionStore,
|
||||
@@ -847,6 +852,10 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
JsonNode effectiveInput;
|
||||
// The role a task's Credentials name is read the way its Parameters or Arguments are, and
|
||||
// only under IAM enforcement, the one place it is used.
|
||||
JsonNode credentials = null;
|
||||
boolean readCredentials = stateDef.has("Credentials") && iamEnforcementEnabled();
|
||||
if (jsonata) {
|
||||
effectiveInput = input;
|
||||
if (stateDef.has("Arguments")) {
|
||||
@@ -854,12 +863,20 @@ public class AslExecutor {
|
||||
effectiveInput = jsonataEvaluator.resolveTemplate(
|
||||
stateDef.get("Arguments"), "Arguments", statesVar, variables);
|
||||
}
|
||||
if (readCredentials) {
|
||||
credentials = jsonataEvaluator.resolveTemplate(stateDef.get("Credentials"), "Credentials",
|
||||
buildStatesVar(input, null, context), variables);
|
||||
}
|
||||
} else {
|
||||
effectiveInput = applyInputPath(stateDef, input, context);
|
||||
if (readCredentials) {
|
||||
credentials = resolveParameters(stateDef.get("Credentials"), effectiveInput, context);
|
||||
}
|
||||
if (stateDef.has("Parameters")) {
|
||||
effectiveInput = resolveParameters(stateDef.get("Parameters"), effectiveInput, context);
|
||||
}
|
||||
}
|
||||
String credentialsRoleArn = credentials == null ? null : credentials.path("RoleArn").asText(null);
|
||||
|
||||
// Registered after the input template resolved, so a template failure leaves no token behind.
|
||||
CompletableFuture<JsonNode> tokenFuture = needsToken ? sfnService.get().registerPendingToken(taskToken) : null;
|
||||
@@ -877,7 +894,7 @@ public class AslExecutor {
|
||||
: invokeResource(effectiveResource, effectiveInput, sm, taskToken,
|
||||
context.path("Execution").path("Id").asText(null),
|
||||
executionDeadlineNanos, taskDeadlineNanos,
|
||||
jsonata ? null : stateDef.path("Parameters"),
|
||||
jsonata ? null : stateDef.path("Parameters"), credentialsRoleArn,
|
||||
jobResponse -> addTaskSubmittedEvent(chain, profile, jobResponse));
|
||||
if (tokenFuture != null) {
|
||||
taskResult = awaitToken(tokenFuture, stateDef, taskToken, executionDeadlineNanos,
|
||||
@@ -1137,12 +1154,15 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param credentialsRoleArn the role the task's {@code Credentials} name, read only under IAM
|
||||
* enforcement, or null when the task runs as the execution role
|
||||
* @param jobSubmitted called with the response of the call that started a {@code .sync} job,
|
||||
* once it has returned and before the job is waited on
|
||||
*/
|
||||
private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken,
|
||||
String executionArn, long executionDeadlineNanos, long taskDeadlineNanos,
|
||||
JsonNode rawParameters, Consumer<JsonNode> jobSubmitted) throws Exception {
|
||||
JsonNode rawParameters, String credentialsRoleArn,
|
||||
Consumer<JsonNode> jobSubmitted) throws Exception {
|
||||
// Support Lambda resources: direct ARN or optimized integration
|
||||
String functionName = null;
|
||||
String functionRef = null;
|
||||
@@ -1187,13 +1207,25 @@ public class AslExecutor {
|
||||
String region = ref.region() != null ? ref.region() : stateMachineArn.region();
|
||||
String accountId = ref.account() == null || ref.account().equals(stateMachineArn.accountId())
|
||||
? null : ref.account();
|
||||
// Floci evaluates no Lambda resource policy, so under IAM enforcement it answers a
|
||||
// cross-account function as its own Invoke API does: refused.
|
||||
if (accountId != null && iamEnforcementEnabled()) {
|
||||
throw new FailStateException("Lambda.AccessDeniedException",
|
||||
"User: " + sm.getRoleArn() + " is not authorized to perform: lambda:InvokeFunction"
|
||||
+ " on resource: " + functionRef
|
||||
+ " because no resource-based policy allows the lambda:InvokeFunction action");
|
||||
// The task invokes the function as its role: the execution role, or the role its
|
||||
// Credentials name once the execution role has assumed it. The role's policies or the
|
||||
// function's have to allow the call, and both when the function is in another account.
|
||||
if (iamEnforcementEnabled()) {
|
||||
String invokingRoleArn = sm.getRoleArn();
|
||||
if (credentialsRoleArn != null) {
|
||||
Optional<String> assumeRefusal = lambdaTaskAuthorizer.assumeRefusal(sm.getRoleArn(),
|
||||
credentialsRoleArn, sm.getStateMachineArn());
|
||||
if (assumeRefusal.isPresent()) {
|
||||
throw new FailStateException("States.Permissions", assumeRefusal.get());
|
||||
}
|
||||
invokingRoleArn = credentialsRoleArn;
|
||||
}
|
||||
String functionArn = LambdaArnUtils.functionArn(functionRef, stateMachineArn.partition(), region,
|
||||
stateMachineArn.accountId());
|
||||
Optional<String> refusal = lambdaTaskAuthorizer.refusal(invokingRoleArn, functionArn);
|
||||
if (refusal.isPresent()) {
|
||||
throw new FailStateException("Lambda.AccessDeniedException", refusal.get());
|
||||
}
|
||||
}
|
||||
LambdaFunction fn = resolveLambdaFunction(accountId, region, functionName,
|
||||
extractLambdaQualifier(functionRef));
|
||||
|
||||
+282
@@ -0,0 +1,282 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
|
||||
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator.TrustDecision;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourceAccountRelationship;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.ResourcePolicyDecision;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.SimulationDecision;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.RequestPrincipal;
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaResourcePolicyProvider;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Decides a Lambda Task's call to its function. The task calls Invoke as its role: the state
|
||||
* machine's execution role (Step Functions Developer Guide, "I can't invoke a Lambda function from
|
||||
* another account": the role "must have the right permissions to invoke cross-account Lambda
|
||||
* functions"), or the role its {@code Credentials} name, which the execution role must assume
|
||||
* first (Developer Guide, Task state "Credentials"). Within one account, the role's policies or the
|
||||
* resource's policy can allow a call; across accounts, both have to (IAM User Guide, cross-account
|
||||
* policy evaluation logic). The role's permissions boundary and its account's service control
|
||||
* policies limit it, and an explicit Deny in any of them refuses it.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaTaskAuthorizer {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(LambdaTaskAuthorizer.class);
|
||||
private static final String INVOKE = "lambda:InvokeFunction";
|
||||
private static final String ASSUME_ROLE = "sts:AssumeRole";
|
||||
|
||||
private final IamService iamService;
|
||||
private final IamPolicyEvaluator evaluator;
|
||||
private final AssumeRolePolicyEvaluator trustEvaluator;
|
||||
private final LambdaResourcePolicyProvider functionPolicies;
|
||||
private final Instance<ScpProvider> scpProvider;
|
||||
|
||||
@Inject
|
||||
public LambdaTaskAuthorizer(IamService iamService, IamPolicyEvaluator evaluator,
|
||||
AssumeRolePolicyEvaluator trustEvaluator,
|
||||
LambdaResourcePolicyProvider functionPolicies, Instance<ScpProvider> scpProvider) {
|
||||
this.iamService = iamService;
|
||||
this.evaluator = evaluator;
|
||||
this.trustEvaluator = trustEvaluator;
|
||||
this.functionPolicies = functionPolicies;
|
||||
this.scpProvider = scpProvider;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns why {@code roleArn} may not invoke {@code functionArn}, as Lambda's access denied
|
||||
* message words it, or nothing when it may.
|
||||
*
|
||||
* @param functionArn the function, version or alias the task invokes, qualified as it names it
|
||||
*/
|
||||
public Optional<String> refusal(String roleArn, String functionArn) {
|
||||
AwsArnUtils.Arn function = AwsArnUtils.parse(functionArn);
|
||||
Optional<IamRole> invokingRole = role(roleArn);
|
||||
if (invokingRole.isEmpty()) {
|
||||
LOG.infov("Role {0} names no existing role, so it cannot invoke {1}", roleArn, functionArn);
|
||||
return Optional.of(denied(roleArn, INVOKE, functionArn, "because no identity-based policy allows the "
|
||||
+ INVOKE + " action"));
|
||||
}
|
||||
// The role is evaluated as itself, under the ARN IAM holds for it, whichever form names it.
|
||||
String invokingRoleArn = invokingRole.get().getArn();
|
||||
CallerContext role = iamService.resolvePrincipalContext(invokingRoleArn);
|
||||
AwsArnUtils.Arn roleId = AwsArnUtils.parse(invokingRoleArn);
|
||||
List<List<String>> scpLevels = scpLevels(roleId.accountId());
|
||||
|
||||
List<ResourcePolicy> policies = functionPolicies.getResourcePolicies("lambda", functionArn);
|
||||
String ownerAccount = policies.isEmpty() ? function.accountId() : policies.getFirst().ownerAccountId();
|
||||
List<String> documents = policies.stream()
|
||||
.map(ResourcePolicy::policyDocument)
|
||||
.filter(document -> document != null && !document.isBlank())
|
||||
.toList();
|
||||
Map<String, List<String>> context = IamConditionContextResolver.withGlobalContext(
|
||||
Map.of("aws:PrincipalArn", List.of(invokingRoleArn)), functionArn, function.region(),
|
||||
roleId.accountId(), ownerAccount);
|
||||
|
||||
RequestPrincipal session = RequestPrincipal.roleSession(sessionArn(invokingRoleArn), invokingRoleArn);
|
||||
ResourcePolicyDecision functionPolicy = evaluator.evaluateResourcePolicyFor(
|
||||
documents.isEmpty() ? null : documents, session, INVOKE, functionArn, context);
|
||||
ResourceAccountRelationship relationship = relationship(roleId.accountId(), ownerAccount);
|
||||
Decision decision = evaluator.evaluateResolvedResourcePolicy(
|
||||
role.withScpLevels(scpLevels), functionPolicy, relationship, INVOKE, functionArn, context);
|
||||
if (decision == Decision.ALLOW) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(denied(invokingRoleArn, INVOKE, functionArn, reason(role, scpLevels, INVOKE, functionArn,
|
||||
context, relationship, ResourceGrant.of(functionPolicy))));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns why the execution role {@code executionRoleArn} may not assume {@code roleArn}, the
|
||||
* role a task's {@code Credentials} name, as STS's access denied message words it, or nothing
|
||||
* when it may. The role's trust policy has to allow the execution role, and the execution
|
||||
* role's own policies have to allow {@code sts:AssumeRole} on it when the role is in another
|
||||
* account or the trust policy names only the execution role's account. Step Functions passes
|
||||
* the state machine's ARN as {@code sts:ExternalId}, which the Developer Guide's cross-account
|
||||
* tutorial has the trust policy check.
|
||||
*/
|
||||
public Optional<String> assumeRefusal(String executionRoleArn, String roleArn, String stateMachineArn) {
|
||||
Optional<IamRole> executionRole = role(executionRoleArn);
|
||||
if (executionRole.isEmpty()) {
|
||||
LOG.infov("Execution role {0} names no existing role, so it cannot assume {1}", executionRoleArn, roleArn);
|
||||
return Optional.of(denied(executionRoleArn, ASSUME_ROLE, roleArn, "because no identity-based policy allows the "
|
||||
+ ASSUME_ROLE + " action"));
|
||||
}
|
||||
String callerRoleArn = executionRole.get().getArn();
|
||||
Optional<IamRole> target = role(roleArn);
|
||||
if (target.isEmpty()) {
|
||||
// STS refuses a role that does not exist as it refuses one the caller may not assume,
|
||||
// and no policy of the role took part, so the message names none.
|
||||
LOG.infov("Role {0} named by a task's Credentials does not exist", roleArn);
|
||||
return Optional.of(denied(callerRoleArn, ASSUME_ROLE, roleArn, null));
|
||||
}
|
||||
String targetRoleArn = target.get().getArn();
|
||||
CallerContext caller = iamService.resolvePrincipalContext(callerRoleArn);
|
||||
AwsArnUtils.Arn callerId = AwsArnUtils.parse(callerRoleArn);
|
||||
String roleAccount = AwsArnUtils.parse(targetRoleArn).accountId();
|
||||
List<List<String>> scpLevels = scpLevels(callerId.accountId());
|
||||
Map<String, List<String>> context = IamConditionContextResolver.withGlobalContext(
|
||||
Map.of("aws:PrincipalArn", List.of(callerRoleArn), "sts:ExternalId", List.of(stateMachineArn)),
|
||||
targetRoleArn, AwsArnUtils.parse(stateMachineArn).region(), callerId.accountId(), roleAccount);
|
||||
|
||||
TrustDecision trust = trustEvaluator.decide(target.get().getAssumeRolePolicyDocument(),
|
||||
sessionArn(callerRoleArn), callerRoleArn, callerId.accountId(), context);
|
||||
ResourceAccountRelationship relationship = relationship(callerId.accountId(), roleAccount);
|
||||
// A grant to the execution role's account delegates to that account, so within it the
|
||||
// role's own policies have to allow the call too, as they do across accounts anyway.
|
||||
ResourcePolicyDecision trustGrant = switch (trust) {
|
||||
case ALLOW -> ResourcePolicyDecision.ALLOW;
|
||||
case ALLOW_ACCOUNT -> relationship == ResourceAccountRelationship.CROSS_ACCOUNT
|
||||
? ResourcePolicyDecision.ALLOW : ResourcePolicyDecision.NEUTRAL;
|
||||
case EXPLICIT_DENY -> ResourcePolicyDecision.EXPLICIT_DENY;
|
||||
case NEUTRAL -> ResourcePolicyDecision.NEUTRAL;
|
||||
};
|
||||
ResourceGrant grant = ResourceGrant.of(trust);
|
||||
Decision decision = grant.allows()
|
||||
? evaluator.evaluateResolvedResourcePolicy(caller.withScpLevels(scpLevels), trustGrant, relationship,
|
||||
ASSUME_ROLE, targetRoleArn, context)
|
||||
: Decision.DENY;
|
||||
if (decision == Decision.ALLOW) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(denied(callerRoleArn, ASSUME_ROLE, roleArn,
|
||||
reason(caller, scpLevels, ASSUME_ROLE, targetRoleArn, context, relationship, grant)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The role {@code roleArn} names, matched as STS {@code AssumeRole} matches a role ARN
|
||||
* ({@link IamService#roleArnMatches}). A role ARN that names no role, or names one under
|
||||
* another path, is not that role, and a grant written for the ARN must not admit it.
|
||||
*/
|
||||
private Optional<IamRole> role(String roleArn) {
|
||||
if (!AwsArnUtils.isArn(roleArn)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(roleArn);
|
||||
String roleName = arn.resource().substring(arn.resource().lastIndexOf('/') + 1);
|
||||
return iamService.findRole(arn.accountId(), roleName)
|
||||
.filter(role -> IamService.roleArnMatches(roleArn, role));
|
||||
}
|
||||
|
||||
private List<List<String>> scpLevels(String accountId) {
|
||||
return scpProvider.isResolvable() ? scpProvider.get().effectiveScpLevels(accountId) : null;
|
||||
}
|
||||
|
||||
private static ResourceAccountRelationship relationship(String callerAccount, String resourceAccount) {
|
||||
return callerAccount.equals(resourceAccount)
|
||||
? ResourceAccountRelationship.SAME_ACCOUNT : ResourceAccountRelationship.CROSS_ACCOUNT;
|
||||
}
|
||||
|
||||
/**
|
||||
* The context that ends the access denied message (IAM User Guide, "Access denied error message
|
||||
* examples"): the first policy type that refuses the call, explicit denials before implicit ones,
|
||||
* each in the order AWS evaluates the types: service control policies, the resource's policy,
|
||||
* identity-based policies, then the permissions boundary.
|
||||
*/
|
||||
private String reason(CallerContext role, List<List<String>> scpLevels, String action, String resource,
|
||||
Map<String, List<String>> context, ResourceAccountRelationship relationship,
|
||||
ResourceGrant grant) {
|
||||
List<SimulationDecision> scps = scpLevels == null ? List.of() : scpLevels.stream()
|
||||
.filter(level -> !level.isEmpty())
|
||||
.map(level -> simulate(level, action, resource, context))
|
||||
.toList();
|
||||
SimulationDecision identity = simulate(role.identityPolicies(), action, resource, context);
|
||||
SimulationDecision boundary = role.boundaryPolicyDocument() == null
|
||||
? SimulationDecision.ALLOWED
|
||||
: simulate(List.of(role.boundaryPolicyDocument()), action, resource, context);
|
||||
boolean crossAccount = relationship == ResourceAccountRelationship.CROSS_ACCOUNT;
|
||||
|
||||
if (scps.contains(SimulationDecision.EXPLICIT_DENY)) {
|
||||
return "with an explicit deny in a service control policy";
|
||||
}
|
||||
if (grant.explicitDeny()) {
|
||||
return "with an explicit deny in " + grant.deniedIn();
|
||||
}
|
||||
if (identity == SimulationDecision.EXPLICIT_DENY) {
|
||||
return "with an explicit deny in an identity-based policy";
|
||||
}
|
||||
if (boundary == SimulationDecision.EXPLICIT_DENY) {
|
||||
return "with an explicit deny in a permissions boundary";
|
||||
}
|
||||
if (scps.contains(SimulationDecision.IMPLICIT_DENY)) {
|
||||
return "because no service control policy allows the " + action + " action";
|
||||
}
|
||||
if ((grant.required() || crossAccount) && !grant.allows()) {
|
||||
return "because no " + grant.kind() + " allows the " + action + " action";
|
||||
}
|
||||
if (identity != SimulationDecision.ALLOWED && (crossAccount || !grant.sufficient())) {
|
||||
return "because no identity-based policy allows the " + action + " action";
|
||||
}
|
||||
return "because no permissions boundary allows the " + action + " action";
|
||||
}
|
||||
|
||||
private SimulationDecision simulate(List<String> documents, String action, String resource,
|
||||
Map<String, List<String>> context) {
|
||||
return evaluator.simulatePrincipalPolicy(CallerContext.of(documents), action, resource, context);
|
||||
}
|
||||
|
||||
private static String denied(String roleArn, String action, String resource, String reason) {
|
||||
return "User: " + sessionArn(roleArn) + " is not authorized to perform: " + action + " on resource: "
|
||||
+ resource + (reason == null ? "" : " " + reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* The role's session, which makes the call, as the Step Functions Developer Guide writes it in
|
||||
* an access denied message: {@code arn:aws:sts::account-id:assumed-role/StepFunctions-MyStateMachine-role}.
|
||||
*/
|
||||
private static String sessionArn(String roleArn) {
|
||||
try {
|
||||
AwsArnUtils.Arn role = AwsArnUtils.parse(roleArn);
|
||||
String roleName = role.resource().substring(role.resource().lastIndexOf('/') + 1);
|
||||
return AwsArnUtils.Arn.global(role.partition(), "sts", role.accountId(), "assumed-role/" + roleName)
|
||||
.toString();
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// A role ARN that does not parse names no session, so the message names the ARN as given.
|
||||
return roleArn;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What the resource's own policy said about a call, and how the access denied message names it.
|
||||
*
|
||||
* @param allows whether it allows the call at all
|
||||
* @param sufficient whether, within one account, that allow grants the call without the
|
||||
* caller's identity-based policies
|
||||
* @param required whether the call needs it to allow even within one account, as a role's
|
||||
* trust policy does
|
||||
* @param deniedIn the policy, as an explicit denial names it
|
||||
* @param kind the policy type, as an implicit denial names it
|
||||
*/
|
||||
private record ResourceGrant(boolean explicitDeny, boolean allows, boolean sufficient, boolean required,
|
||||
String deniedIn, String kind) {
|
||||
|
||||
static ResourceGrant of(ResourcePolicyDecision functionPolicy) {
|
||||
boolean allows = functionPolicy == ResourcePolicyDecision.ALLOW
|
||||
|| functionPolicy == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER;
|
||||
return new ResourceGrant(functionPolicy == ResourcePolicyDecision.EXPLICIT_DENY, allows, allows, false,
|
||||
"a resource-based policy", "resource-based policy");
|
||||
}
|
||||
|
||||
static ResourceGrant of(TrustDecision trust) {
|
||||
return new ResourceGrant(trust == TrustDecision.EXPLICIT_DENY,
|
||||
trust == TrustDecision.ALLOW || trust == TrustDecision.ALLOW_ACCOUNT,
|
||||
trust == TrustDecision.ALLOW, true, "the role trust policy", "role trust policy");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user