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:
Priamo Germosen authored and GitHub committed 2026-10-13 22:28:56 -05:00
1 parent 287d683da7
commit c6c2c609c3
10 files changed
+1409 -71

No files matched your search

+3
View File
@@ -84,6 +84,9 @@ part in authorizing calls to the function:
- An invoke of a function named by a full or partial ARN runs the function in the account in the
ARN. An invoke of another account's function needs its function policy to allow the caller as
well as the caller's own identity policy.
- A Step Functions Lambda task is authorized the same way, as the state machine's execution role or
the role the task's `Credentials` name; see
[Step Functions](step-functions.md#lambda-tasks-under-iam-enforcement).
- `GetFunction`, `GetFunctionConfiguration` and `ListDurableExecutionsByFunction`, given a full ARN
with a version or alias, read the function in the account in the ARN, and need its function
policy to allow the caller in the same way.
+23
View File
@@ -472,6 +472,29 @@ for the integration that raised it: `StepFunctions.ExecutionAlreadyExistsExcepti
`aws-sdk:sfn:startExecution`. An Express child starts a new execution instead, so the same `Name`
never fails it.
## Lambda tasks under IAM enforcement
A Lambda task, given a function ARN as its `Resource` or as the `FunctionName` of
`arn:aws:states:::lambda:invoke`, runs the function in the account and Region the ARN names. With
[IAM enforcement](iam.md#resource-based-policies) on, the task invokes the function as the state
machine's execution role, as on AWS. In the role's own account, the role's policies or the
function's policy can allow `lambda:InvokeFunction`. For a function in another account, both have
to: the role's policies, and the function's policy through, for example, `AddPermission` naming the
role or its account. The role's permissions boundary and its account's service control policies
apply too, and a Deny in any of them refuses the call. A task that names a version or alias is
authorized against that version or alias. A refused task fails with `Lambda.AccessDeniedException`,
whose cause names the role's session and the kind of policy that refused it.
A task whose `Credentials` name a role invokes the function as that role instead, once the
execution role has assumed it. The role's trust policy has to allow the execution role, and Step
Functions passes the state machine's ARN as `sts:ExternalId`, which the trust policy can require.
The execution role's own policies have to allow `sts:AssumeRole` on the role too when the role is in
another account, or when the trust policy names only the execution role's account. `RoleArn` is
read the way the task's `Parameters` or `Arguments` are: as written, through a path or an intrinsic
function as `RoleArn.$`, or through JSONata. A role the execution role cannot assume fails the task
with `States.Permissions`, whose cause names the execution role's session and `sts:AssumeRole` on
the role.
## AWS SDK task integrations
A resource of the form `arn:aws:states:::aws-sdk:<service>:<action>` calls the service's API and
@@ -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));
@@ -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");
}
}
}
@@ -1,11 +1,13 @@
package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator.TrustDecision;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -388,6 +390,45 @@ class AssumeRolePolicyEvaluatorTest {
"arn:aws:appsync:us-east-1:111111111111:apis/example", "111111111111"));
}
@Test
void aGrantNamingTheCallerIsToldApartFromAGrantToItsAccount() {
assertEquals(TrustDecision.ALLOW, evaluator.decide(trust("{\"AWS\":\"" + CALLER_ARN + "\"}"),
CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
assertEquals(TrustDecision.ALLOW, evaluator.decide(trust("\"*\""),
CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
assertEquals(TrustDecision.ALLOW_ACCOUNT, evaluator.decide(trust("{\"AWS\":\"arn:aws:iam::111111111111:root\"}"),
CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
assertEquals(TrustDecision.ALLOW_ACCOUNT, evaluator.decide(trust("{\"AWS\":\"111111111111\"}"),
CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void aStatementNamingBothTheAccountAndTheCallerGrantsToTheCaller() {
String doc = trust("{\"AWS\":[\"111111111111\",\"" + CALLER_ARN + "\"]}");
assertEquals(TrustDecision.ALLOW, evaluator.decide(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
String twoStatements = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"%1$s"},"Action":"sts:AssumeRole"},
{"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole"}]}
""".formatted(CALLER_ARN);
assertEquals(TrustDecision.ALLOW,
evaluator.decide(twoStatements, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void aDenyOrASilentPolicyIsReportedAsSuch() {
String deny = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"%1$s"},"Action":"sts:AssumeRole"},
{"Effect":"Deny","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole"}]}
""".formatted(CALLER_ARN);
assertEquals(TrustDecision.EXPLICIT_DENY, evaluator.decide(deny, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
assertEquals(TrustDecision.NEUTRAL, evaluator.decide(trust("{\"AWS\":\"222222222222\"}"),
CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
assertEquals(TrustDecision.NEUTRAL, evaluator.decide(null, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void deniesBlankOrMalformedDocument() {
assertFalse(evaluator.allows(null, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
@@ -38,16 +38,21 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A Lambda Task given a function ARN invokes the function that ARN names: the one in its own
* account and region, never a same-named function of the state machine's. The optimized
* integration calls Lambda's Invoke in the state machine's region, which refuses an ARN from
* another region.
* another region. Under IAM enforcement, the function runs only when {@link LambdaTaskAuthorizer}
* lets the execution role invoke it, or, for a task whose {@code Credentials} name a role, lets the
* execution role assume that role and that role invoke it.
*/
@QuarkusTest
class AslExecutorLambdaArnTargetTest {
@@ -57,6 +62,10 @@ class AslExecutorLambdaArnTargetTest {
private static final String ACCOUNT = "000000000000";
private static final String OTHER_ACCOUNT = "111111111111";
private static final String FUNCTION_NAME = "worker";
private static final String ROLE_ARN = "arn:aws:iam::" + ACCOUNT + ":role/test-role";
private static final String TASK_ROLE_ARN = "arn:aws:iam::" + OTHER_ACCOUNT + ":role/LambdaRole";
private static final String STATE_MACHINE_ARN =
"arn:aws:states:%s:%s:stateMachine:lambda-arn-target".formatted(REGION, ACCOUNT);
private final ObjectMapper objectMapper = new ObjectMapper();
private LambdaExecutorService lambdaExecutor;
@@ -83,10 +92,10 @@ class AslExecutorLambdaArnTargetTest {
.thenReturn(new InvokeResult(200, null, output, null, "request"));
}
executor = newExecutor(mock(EmulatorConfig.class));
executor = newExecutor(mock(EmulatorConfig.class), null);
}
private AslExecutor newExecutor(EmulatorConfig config) {
private AslExecutor newExecutor(EmulatorConfig config, LambdaTaskAuthorizer authorizer) {
return new AslExecutor(
lambdaExecutor,
new LambdaTargetResolver(functionStore, mock(LambdaAliasStore.class)),
@@ -104,7 +113,7 @@ class AslExecutorLambdaArnTargetTest {
null,
objectMapper,
new JsonataEvaluator(objectMapper),
mock(Instance.class), config, vertx, null);
mock(Instance.class), config, vertx, null, null, null, authorizer);
}
private static LambdaFunction function(String account, String region) {
@@ -155,10 +164,23 @@ class AslExecutorLambdaArnTargetTest {
}
@Test
void underIamEnforcementAFunctionArnInAnotherAccountIsRefused() {
EmulatorConfig enforcing = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(enforcing.services().iam().enforcementEnabled()).thenReturn(true);
executor = newExecutor(enforcing);
void underIamEnforcementAFunctionInAnotherAccountRunsWhenItsPolicyAndTheRolesAllowIt() throws Exception {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.refusal(ROLE_ARN, functionArn(OTHER_ACCOUNT, REGION))).thenReturn(Optional.empty());
Execution execution = run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task", "Resource": "%s", "End": true}}}
""".formatted(functionArn(OTHER_ACCOUNT, REGION)));
assertEquals("SUCCEEDED", execution.getStatus());
assertEquals(functionArn(OTHER_ACCOUNT, REGION),
objectMapper.readTree(execution.getOutput()).path("invoked").asText());
}
@Test
void underIamEnforcementAFunctionInAnotherAccountIsRefusedWithTheAuthorizersReason() {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.refusal(ROLE_ARN, functionArn(OTHER_ACCOUNT, REGION))).thenReturn(Optional.of("refused"));
Execution execution = run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task", "Resource": "%s", "End": true}}}
@@ -166,14 +188,145 @@ class AslExecutorLambdaArnTargetTest {
assertEquals("FAILED", execution.getStatus());
assertEquals("Lambda.AccessDeniedException", execution.getError());
assertEquals("refused", execution.getCause());
verify(lambdaExecutor, never()).invoke(any(), any(byte[].class), any());
}
@Test
void underIamEnforcementTheFunctionIsAuthorizedAsTheTaskNamesIt() {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.refusal(anyString(), anyString())).thenReturn(Optional.of("refused"));
run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "%s:function:%s:live"}, "End": true}}}
""".formatted(OTHER_ACCOUNT, FUNCTION_NAME));
verify(authorizer).refusal(ROLE_ARN, functionArn(OTHER_ACCOUNT, REGION) + ":live");
}
@Test
void underIamEnforcementAFullFunctionArnIsAuthorizedAsItIsWritten() {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.refusal(anyString(), anyString())).thenReturn(Optional.of("refused"));
String chinaFunction = "arn:aws-cn:lambda:cn-north-1:%s:function:%s:7".formatted(OTHER_ACCOUNT, FUNCTION_NAME);
run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task", "Resource": "%s", "End": true}}}
""".formatted(chinaFunction));
verify(authorizer).refusal(ROLE_ARN, chinaFunction);
}
@Test
void underIamEnforcementAFunctionInTheStateMachinesAccountIsAuthorizedToo() {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.refusal(ROLE_ARN, functionArn(ACCOUNT, REGION))).thenReturn(Optional.of("refused"));
Execution execution = run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "%s"}, "End": true}}}
""".formatted(FUNCTION_NAME));
assertEquals("FAILED", execution.getStatus());
assertEquals("Lambda.AccessDeniedException", execution.getError());
verify(lambdaExecutor, never()).invoke(any(), any(byte[].class), any());
}
@Test
void underIamEnforcementATaskWithCredentialsInvokesAsTheRoleTheyName() throws Exception {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.assumeRefusal(ROLE_ARN, TASK_ROLE_ARN, STATE_MACHINE_ARN)).thenReturn(Optional.empty());
when(authorizer.refusal(TASK_ROLE_ARN, functionArn(OTHER_ACCOUNT, REGION))).thenReturn(Optional.empty());
Execution execution = run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task", "Resource": "%s",
"Credentials": {"RoleArn": "%s"}, "End": true}}}
""".formatted(functionArn(OTHER_ACCOUNT, REGION), TASK_ROLE_ARN));
assertEquals("SUCCEEDED", execution.getStatus());
assertEquals(functionArn(OTHER_ACCOUNT, REGION),
objectMapper.readTree(execution.getOutput()).path("invoked").asText());
verify(authorizer, never()).refusal(eq(ROLE_ARN), anyString());
}
@Test
void underIamEnforcementARoleTheExecutionRoleCannotAssumeFailsTheTaskWithStatesPermissions() {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.assumeRefusal(ROLE_ARN, TASK_ROLE_ARN, STATE_MACHINE_ARN)).thenReturn(Optional.of("refused"));
Execution execution = run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {"FunctionName": "%s"}, "Credentials": {"RoleArn": "%s"}, "End": true}}}
""".formatted(functionArn(OTHER_ACCOUNT, REGION), TASK_ROLE_ARN));
assertEquals("FAILED", execution.getStatus());
assertEquals("States.Permissions", execution.getError());
assertEquals("refused", execution.getCause());
verify(authorizer, never()).refusal(anyString(), anyString());
verify(lambdaExecutor, never()).invoke(any(), any(byte[].class), any());
}
@Test
void underIamEnforcementTheCredentialsRoleArnIsReadFromAPath() {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.assumeRefusal(anyString(), anyString(), anyString())).thenReturn(Optional.of("refused"));
run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task", "Resource": "%s",
"Credentials": {"RoleArn.$": "$.roleArn"}, "End": true}}}
""".formatted(functionArn(OTHER_ACCOUNT, REGION)), "{\"roleArn\": \"" + TASK_ROLE_ARN + "\"}");
verify(authorizer).assumeRefusal(ROLE_ARN, TASK_ROLE_ARN, STATE_MACHINE_ARN);
}
@Test
void underIamEnforcementTheCredentialsRoleArnIsReadFromAnIntrinsicFunction() {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.assumeRefusal(anyString(), anyString(), anyString())).thenReturn(Optional.of("refused"));
run("""
{"StartAt": "Call", "States": {"Call": {"Type": "Task", "Resource": "%s",
"Credentials": {"RoleArn.$": "States.Format('arn:aws:iam::{}:role/LambdaRole', $.account)"},
"End": true}}}
""".formatted(functionArn(OTHER_ACCOUNT, REGION)), "{\"account\": \"" + OTHER_ACCOUNT + "\"}");
verify(authorizer).assumeRefusal(ROLE_ARN, TASK_ROLE_ARN, STATE_MACHINE_ARN);
}
@Test
void underIamEnforcementTheCredentialsRoleArnIsReadFromJsonata() {
LambdaTaskAuthorizer authorizer = enforcing();
when(authorizer.assumeRefusal(anyString(), anyString(), anyString())).thenReturn(Optional.of("refused"));
run("""
{"QueryLanguage": "JSONata", "StartAt": "Call", "States": {"Call": {"Type": "Task",
"Resource": "%s", "Credentials": {"RoleArn": "{%% $states.input.roleArn %%}"}, "End": true}}}
""".formatted(functionArn(OTHER_ACCOUNT, REGION)), "{\"roleArn\": \"" + TASK_ROLE_ARN + "\"}");
verify(authorizer).assumeRefusal(ROLE_ARN, TASK_ROLE_ARN, STATE_MACHINE_ARN);
}
private LambdaTaskAuthorizer enforcing() {
EmulatorConfig enforcing = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(enforcing.services().iam().enforcementEnabled()).thenReturn(true);
LambdaTaskAuthorizer authorizer = mock(LambdaTaskAuthorizer.class);
executor = newExecutor(enforcing, authorizer);
return authorizer;
}
private Execution run(String definition) {
return run(definition, "{}");
}
private Execution run(String definition, String input) {
StateMachine stateMachine = new StateMachine();
stateMachine.setName("lambda-arn-target");
stateMachine.setStateMachineArn(
"arn:aws:states:%s:%s:stateMachine:lambda-arn-target".formatted(REGION, ACCOUNT));
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
stateMachine.setStateMachineArn(STATE_MACHINE_ARN);
stateMachine.setRoleArn(ROLE_ARN);
stateMachine.setDefinition(definition);
Execution execution = new Execution();
@@ -181,7 +334,7 @@ class AslExecutorLambdaArnTargetTest {
execution.setExecutionArn("arn:aws:states:%s:%s:execution:lambda-arn-target:run-1"
.formatted(REGION, ACCOUNT));
execution.setStateMachineArn(stateMachine.getStateMachineArn());
execution.setInput("{}");
execution.setInput(input);
List<HistoryEvent> history = new ArrayList<>();
executor.executeSync(stateMachine, execution, history, (updated, events) -> {
@@ -55,7 +55,7 @@ class AslExecutorRedshiftDataDisabledTest {
RedshiftDataJsonHandler handler = spy(new RedshiftDataJsonHandler(service));
AslExecutor executor = new AslExecutor(null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, objectMapper,
new JsonataEvaluator(objectMapper), null, config, null, null, handler, serviceRegistry);
new JsonataEvaluator(objectMapper), null, config, null, null, handler, serviceRegistry, null);
StateMachine stateMachine = new StateMachine();
stateMachine.setStateMachineArn("arn:aws:states:us-east-1:000000000000:stateMachine:disabled-data");
@@ -0,0 +1,414 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
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.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class LambdaTaskAuthorizerTest {
private static final String SFN_ACCOUNT = "111122223333";
private static final String FUNCTION_ACCOUNT = "444455556666";
private static final String ROLE = "arn:aws:iam::" + SFN_ACCOUNT + ":role/service-role/sfn-exec";
/** The role's session as the Step Functions Developer Guide writes it in an access denied message. */
private static final String SESSION = "arn:aws:sts::" + SFN_ACCOUNT + ":assumed-role/sfn-exec";
private static final String FUNCTION = "arn:aws:lambda:us-east-1:" + FUNCTION_ACCOUNT + ":function:worker";
private static final String ALIAS = FUNCTION + ":live";
private static final String OWN_FUNCTION = "arn:aws:lambda:us-east-1:" + SFN_ACCOUNT + ":function:worker";
private static final String INVOKE_ANYTHING = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"*"}]}""";
private static final String READ_OBJECTS = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""";
/** A role a task's Credentials name, in the function's account as the cross-account tutorial sets it up. */
private static final String TASK_ROLE = "arn:aws:iam::" + FUNCTION_ACCOUNT + ":role/LambdaRole";
private static final String OWN_TASK_ROLE = "arn:aws:iam::" + SFN_ACCOUNT + ":role/LambdaRole";
private static final String STATE_MACHINE = "arn:aws:states:us-east-1:" + SFN_ACCOUNT + ":stateMachine:orders";
private static final String ASSUME_ANY_ROLE = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}""";
private IamService iamService;
private LambdaResourcePolicyProvider functionPolicies;
private Instance<ScpProvider> scpProvider;
private LambdaTaskAuthorizer authorizer;
@BeforeEach
@SuppressWarnings("unchecked")
void setUp() {
iamService = mock(IamService.class);
functionPolicies = mock(LambdaResourcePolicyProvider.class);
scpProvider = mock(Instance.class);
when(functionPolicies.getResourcePolicies(anyString(), anyString()))
.thenReturn(List.of(new ResourcePolicy(null, FUNCTION_ACCOUNT)));
when(functionPolicies.getResourcePolicies("lambda", OWN_FUNCTION))
.thenReturn(List.of(new ResourcePolicy(null, SFN_ACCOUNT)));
ObjectMapper mapper = new ObjectMapper();
IamPolicyEvaluator evaluator = new IamPolicyEvaluator(mapper);
authorizer = new LambdaTaskAuthorizer(iamService, evaluator, new AssumeRolePolicyEvaluator(mapper, evaluator),
functionPolicies, scpProvider);
}
@Test
void aFunctionPolicyGrantingTheRoleLetsTheRoleInvoke() {
roleWithPolicies(INVOKE_ANYTHING);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
assertEquals(Optional.empty(), authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aGrantToTheRolesAccountCoversTheRole() {
roleWithPolicies(INVOKE_ANYTHING);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"arn:aws:iam::" + SFN_ACCOUNT + ":root\"}", FUNCTION));
assertEquals(Optional.empty(), authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aFunctionWhosePolicyGrantsNothingRefusesTheRole() {
roleWithPolicies(INVOKE_ANYTHING);
assertEquals(denied(FUNCTION, "because no resource-based policy allows the lambda:InvokeFunction action"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aGrantFromTheFunctionIsNotEnoughWithoutTheRolesOwnPermission() {
roleWithPolicies(READ_OBJECTS);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
assertEquals(denied(FUNCTION, "because no identity-based policy allows the lambda:InvokeFunction action"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aDenyInTheRolesPolicyRefusesAGrantedFunction() {
roleWithPolicies(INVOKE_ANYTHING, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"lambda:InvokeFunction","Resource":"%s"}]}""".formatted(FUNCTION));
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
assertEquals(denied(FUNCTION, "with an explicit deny in an identity-based policy"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aDenyInTheFunctionPolicyRefusesTheRole() {
roleWithPolicies(INVOKE_ANYTHING);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"%1$s"},"Action":"lambda:InvokeFunction","Resource":"%2$s"},
{"Effect":"Deny","Principal":{"AWS":"%1$s"},"Action":"lambda:InvokeFunction","Resource":"%2$s"}]}"""
.formatted(ROLE, FUNCTION));
assertEquals(denied(FUNCTION, "with an explicit deny in a resource-based policy"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aGrantOnTheFunctionDoesNotCoverACallToItsAlias() {
roleWithPolicies(INVOKE_ANYTHING);
functionPolicy(ALIAS, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
assertEquals(denied(ALIAS, "because no resource-based policy allows the lambda:InvokeFunction action"),
authorizer.refusal(ROLE, ALIAS));
functionPolicy(ALIAS, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", ALIAS));
assertEquals(Optional.empty(), authorizer.refusal(ROLE, ALIAS));
}
@Test
void aGrantConditionedOnThePrincipalArnMatchesTheRole() {
roleWithPolicies(INVOKE_ANYTHING);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, """
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"lambda:InvokeFunction",
"Resource":"%s","Condition":{"ArnLike":{"aws:PrincipalArn":"arn:aws:iam::*:role/service-role/*"}}}]}"""
.formatted(SFN_ACCOUNT, FUNCTION));
assertEquals(Optional.empty(), authorizer.refusal(ROLE, FUNCTION));
}
@Test
void inTheRolesOwnAccountTheRolesPermissionIsEnough() {
roleWithPolicies(INVOKE_ANYTHING);
assertEquals(Optional.empty(), authorizer.refusal(ROLE, OWN_FUNCTION));
}
@Test
void inTheRolesOwnAccountTheFunctionsGrantIsEnough() {
roleWithPolicies(READ_OBJECTS);
functionPolicy(OWN_FUNCTION, SFN_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", OWN_FUNCTION));
assertEquals(Optional.empty(), authorizer.refusal(ROLE, OWN_FUNCTION));
}
@Test
void inTheRolesOwnAccountARoleWithoutPermissionAndNoGrantIsRefused() {
roleWithPolicies(READ_OBJECTS);
assertEquals(denied(OWN_FUNCTION, "because no identity-based policy allows the lambda:InvokeFunction action"),
authorizer.refusal(ROLE, OWN_FUNCTION));
}
@Test
void aRoleThatDoesNotExistIsRefused() {
when(iamService.findRole(SFN_ACCOUNT, "sfn-exec")).thenReturn(Optional.empty());
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
assertEquals(denied(FUNCTION, "because no identity-based policy allows the lambda:InvokeFunction action"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aRoleArnWithAnotherPathIsNotTheRoleAGrantNames() {
roleWithPolicies(INVOKE_ANYTHING);
String otherPath = "arn:aws:iam::" + SFN_ACCOUNT + ":role/other/sfn-exec";
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + otherPath + "\"}", FUNCTION));
assertEquals(denied(FUNCTION, "because no identity-based policy allows the lambda:InvokeFunction action"),
authorizer.refusal(otherPath, FUNCTION));
}
@Test
void aRoleArnInAnotherPartitionNamesTheSameRole() {
roleWithPolicies(INVOKE_ANYTHING);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
assertEquals(Optional.empty(),
authorizer.refusal("arn:aws-cn:iam::" + SFN_ACCOUNT + ":role/service-role/sfn-exec", FUNCTION));
}
@Test
void aServiceControlPolicyDenyingTheCallRefusesIt() {
roleWithPolicies(INVOKE_ANYTHING);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
scps("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"*","Resource":"*"},
{"Effect":"Deny","Action":"lambda:InvokeFunction","Resource":"*"}]}""");
assertEquals(denied(FUNCTION, "with an explicit deny in a service control policy"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aServiceControlPolicyThatDoesNotAllowTheCallRefusesIt() {
roleWithPolicies(INVOKE_ANYTHING);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
scps("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:*","Resource":"*"}]}""");
assertEquals(denied(FUNCTION, "because no service control policy allows the lambda:InvokeFunction action"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aPermissionsBoundaryThatDoesNotAllowTheCallRefusesIt() {
roleWithBoundary(INVOKE_ANYTHING, READ_OBJECTS);
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
assertEquals(denied(FUNCTION, "because no permissions boundary allows the lambda:InvokeFunction action"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aPermissionsBoundaryDenyingTheCallRefusesIt() {
roleWithBoundary(INVOKE_ANYTHING, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"*","Resource":"*"},
{"Effect":"Deny","Action":"lambda:InvokeFunction","Resource":"*"}]}""");
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"" + ROLE + "\"}", FUNCTION));
assertEquals(denied(FUNCTION, "with an explicit deny in a permissions boundary"),
authorizer.refusal(ROLE, FUNCTION));
}
@Test
void aRoleInAnotherAccountTrustingTheExecutionRoleCanBeAssumed() {
roleWithPolicies(ASSUME_ANY_ROLE);
taskRole(TASK_ROLE, trust("{\"AWS\":\"" + ROLE + "\"}"));
assertEquals(Optional.empty(), authorizer.assumeRefusal(ROLE, TASK_ROLE, STATE_MACHINE));
}
@Test
void aRoleInAnotherAccountNeedsTheExecutionRolesOwnPermissionToo() {
roleWithPolicies(READ_OBJECTS);
taskRole(TASK_ROLE, trust("{\"AWS\":\"" + ROLE + "\"}"));
assertEquals(assumeDenied(TASK_ROLE, "because no identity-based policy allows the sts:AssumeRole action"),
authorizer.assumeRefusal(ROLE, TASK_ROLE, STATE_MACHINE));
}
@Test
void aRoleWhoseTrustPolicyDoesNotNameTheExecutionRoleCannotBeAssumed() {
roleWithPolicies(ASSUME_ANY_ROLE);
taskRole(TASK_ROLE, trust("{\"AWS\":\"arn:aws:iam::" + SFN_ACCOUNT + ":role/someone-else\"}"));
assertEquals(assumeDenied(TASK_ROLE, "because no role trust policy allows the sts:AssumeRole action"),
authorizer.assumeRefusal(ROLE, TASK_ROLE, STATE_MACHINE));
}
@Test
void aDenyInTheTrustPolicyRefusesTheExecutionRole() {
roleWithPolicies(ASSUME_ANY_ROLE);
taskRole(TASK_ROLE, """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"%1$s"},"Action":"sts:AssumeRole"},
{"Effect":"Deny","Principal":{"AWS":"%1$s"},"Action":"sts:AssumeRole"}]}""".formatted(ROLE));
assertEquals(assumeDenied(TASK_ROLE, "with an explicit deny in the role trust policy"),
authorizer.assumeRefusal(ROLE, TASK_ROLE, STATE_MACHINE));
}
@Test
void inItsOwnAccountATrustPolicyNamingTheExecutionRoleIsEnough() {
roleWithPolicies(READ_OBJECTS);
taskRole(OWN_TASK_ROLE, trust("{\"AWS\":\"" + ROLE + "\"}"));
assertEquals(Optional.empty(), authorizer.assumeRefusal(ROLE, OWN_TASK_ROLE, STATE_MACHINE));
}
@Test
void inItsOwnAccountARoleWhoseTrustPolicyDoesNotNameTheExecutionRoleCannotBeAssumed() {
roleWithPolicies(ASSUME_ANY_ROLE);
taskRole(OWN_TASK_ROLE, trust("{\"Service\":\"states.amazonaws.com\"}"));
assertEquals(assumeDenied(OWN_TASK_ROLE, "because no role trust policy allows the sts:AssumeRole action"),
authorizer.assumeRefusal(ROLE, OWN_TASK_ROLE, STATE_MACHINE));
}
@Test
void inItsOwnAccountATrustPolicyNamingTheAccountDelegatesToTheExecutionRolesPolicies() {
roleWithPolicies(READ_OBJECTS);
taskRole(OWN_TASK_ROLE, trust("{\"AWS\":\"arn:aws:iam::" + SFN_ACCOUNT + ":root\"}"));
assertEquals(assumeDenied(OWN_TASK_ROLE, "because no identity-based policy allows the sts:AssumeRole action"),
authorizer.assumeRefusal(ROLE, OWN_TASK_ROLE, STATE_MACHINE));
roleWithPolicies(ASSUME_ANY_ROLE);
assertEquals(Optional.empty(), authorizer.assumeRefusal(ROLE, OWN_TASK_ROLE, STATE_MACHINE));
}
@Test
void theTrustPolicyCanRequireTheStateMachineAsTheExternalId() {
roleWithPolicies(ASSUME_ANY_ROLE);
taskRole(TASK_ROLE, """
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Principal":{"AWS":"%s"},"Action":"sts:AssumeRole",
"Condition":{"StringEquals":{"sts:ExternalId":"%s"}}}]}""".formatted(ROLE, STATE_MACHINE));
assertEquals(Optional.empty(), authorizer.assumeRefusal(ROLE, TASK_ROLE, STATE_MACHINE));
assertEquals(assumeDenied(TASK_ROLE, "because no role trust policy allows the sts:AssumeRole action"),
authorizer.assumeRefusal(ROLE, TASK_ROLE, STATE_MACHINE.replace(":orders", ":other")));
}
@Test
void aRoleThatDoesNotExistCannotBeAssumedAndNoPolicyIsNamed() {
roleWithPolicies(ASSUME_ANY_ROLE);
when(iamService.findRole(FUNCTION_ACCOUNT, "LambdaRole")).thenReturn(Optional.empty());
assertEquals(Optional.of("User: " + SESSION + " is not authorized to perform: sts:AssumeRole on resource: "
+ TASK_ROLE), authorizer.assumeRefusal(ROLE, TASK_ROLE, STATE_MACHINE));
}
@Test
void aServiceControlPolicyDenyingAssumeRoleRefusesIt() {
roleWithPolicies(ASSUME_ANY_ROLE);
taskRole(TASK_ROLE, trust("{\"AWS\":\"" + ROLE + "\"}"));
scps("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"*","Resource":"*"},
{"Effect":"Deny","Action":"sts:AssumeRole","Resource":"*"}]}""");
assertEquals(assumeDenied(TASK_ROLE, "with an explicit deny in a service control policy"),
authorizer.assumeRefusal(ROLE, TASK_ROLE, STATE_MACHINE));
}
@Test
void aPermissionsBoundaryLimitsATrustPolicyNamingTheExecutionRole() {
roleWithBoundary(ASSUME_ANY_ROLE, READ_OBJECTS);
taskRole(OWN_TASK_ROLE, trust("{\"AWS\":\"" + ROLE + "\"}"));
assertEquals(assumeDenied(OWN_TASK_ROLE, "because no permissions boundary allows the sts:AssumeRole action"),
authorizer.assumeRefusal(ROLE, OWN_TASK_ROLE, STATE_MACHINE));
}
private static Optional<String> denied(String functionArn, String reason) {
return Optional.of("User: " + SESSION + " is not authorized to perform: lambda:InvokeFunction on resource: "
+ functionArn + " " + reason);
}
private static Optional<String> assumeDenied(String roleArn, String reason) {
return Optional.of("User: " + SESSION + " is not authorized to perform: sts:AssumeRole on resource: "
+ roleArn + " " + reason);
}
private void taskRole(String roleArn, String trustPolicy) {
IamRole role = new IamRole();
role.setArn(roleArn);
role.setAssumeRolePolicyDocument(trustPolicy);
when(iamService.findRole(roleArn.split(":")[4], "LambdaRole")).thenReturn(Optional.of(role));
}
private static String trust(String principal) {
return """
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Principal":%s,"Action":"sts:AssumeRole"}]}""".formatted(principal);
}
private void roleWithPolicies(String... documents) {
role(CallerContext.of(List.of(documents)));
}
private void roleWithBoundary(String policy, String boundary) {
role(new CallerContext(List.of(policy), null, boundary));
}
private void role(CallerContext context) {
IamRole role = new IamRole();
role.setArn(ROLE);
when(iamService.findRole(SFN_ACCOUNT, "sfn-exec")).thenReturn(Optional.of(role));
when(iamService.resolvePrincipalContext(anyString())).thenReturn(context);
}
private void scps(String document) {
ScpProvider provider = mock(ScpProvider.class);
when(provider.effectiveScpLevels(SFN_ACCOUNT)).thenReturn(List.of(List.of(document)));
when(scpProvider.isResolvable()).thenReturn(true);
when(scpProvider.get()).thenReturn(provider);
}
private void functionPolicy(String functionArn, String owner, String document) {
when(functionPolicies.getResourcePolicies("lambda", functionArn))
.thenReturn(List.of(new ResourcePolicy(document, owner)));
}
private static String grant(String principal, String resource) {
return """
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Principal":%s,"Action":"lambda:InvokeFunction","Resource":"%s"}]}"""
.formatted(principal, resource);
}
}
@@ -0,0 +1,349 @@
package io.github.hectorvent.floci.services.stepfunctions;
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import java.nio.charset.StandardCharsets;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Under IAM enforcement, a Lambda Task calls Invoke as the state machine's execution role. On a
* function in another account that needs the role's own permission and a grant in the function's
* policy (Step Functions Developer Guide, "I can't invoke a Lambda function from another account";
* IAM User Guide, cross-account policy evaluation logic); in the role's own account either is enough.
* A task whose {@code Credentials} name a role calls Invoke as that role, once the execution role
* has assumed it (Developer Guide, "Accessing cross-account AWS resources in Step Functions").
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class StepFunctionsLambdaTaskAuthorizationIntegrationTest {
private static final String REGION = "us-east-1";
private static final String SFN_ACCOUNT = "565656565656";
private static final String FUNCTION_ACCOUNT = "787878787878";
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String INVOKE_ANYTHING = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"lambda:InvokeFunction","Resource":"*"}]}""";
private static final String ASSUME_ANY_ROLE = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}""";
private static final String STATES_TRUST = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"Service":"states.amazonaws.com"},"Action":"sts:AssumeRole"}]}""";
@InjectMock
LambdaExecutorService executor;
/** How to delete each thing the test created, pushed as it is created and run newest first. */
private final Deque<Runnable> cleanup = new ArrayDeque<>();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@BeforeEach
void stubExecutor() {
when(executor.invoke(any(), any(), any()))
.thenReturn(new InvokeResult(200, null, "{\"ok\":true}".getBytes(StandardCharsets.UTF_8), null, "req"));
}
@AfterEach
void deleteWhatTheTestCreated() {
while (!cleanup.isEmpty()) {
cleanup.pop().run();
}
}
@Test
void aGrantToTheExecutionRoleLetsTheTaskInvokeTheFunction() {
String roleArn = createRole("sfn-exec-" + suffix(), INVOKE_ANYTHING);
String functionArn = createFunction(FUNCTION_ACCOUNT, "worker-" + suffix());
addPermission(functionArn, null, Map.of("Principal", roleArn));
runTask(roleArn, functionArn)
.body("status", equalTo("SUCCEEDED"))
.body("output", equalTo("{\"ok\":true}"));
verify(executor).invoke(argThat(isFunction(functionArn)), any(), any());
}
@Test
void aFunctionWhosePolicyGrantsNothingFailsTheTask() {
String roleName = "sfn-exec-" + suffix();
String roleArn = createRole(roleName, INVOKE_ANYTHING);
String functionArn = createFunction(FUNCTION_ACCOUNT, "worker-" + suffix());
runTask(roleArn, functionArn)
.body("status", equalTo("FAILED"))
.body("error", equalTo("Lambda.AccessDeniedException"))
.body("cause", equalTo("User: arn:aws:sts::" + SFN_ACCOUNT + ":assumed-role/" + roleName
+ " is not authorized to perform: lambda:InvokeFunction on resource: " + functionArn
+ " because no resource-based policy allows the lambda:InvokeFunction action"));
verify(executor, never()).invoke(argThat(isFunction(functionArn)), any(), any());
}
@Test
void aRoleWithoutPermissionToInvokeFailsTheTaskDespiteTheGrant() {
String roleArn = createRole("sfn-exec-" + suffix(), """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""");
String functionArn = createFunction(FUNCTION_ACCOUNT, "worker-" + suffix());
addPermission(functionArn, null, Map.of("Principal", roleArn));
runTask(roleArn, functionArn)
.body("status", equalTo("FAILED"))
.body("error", equalTo("Lambda.AccessDeniedException"))
.body("cause", containsString("because no identity-based policy allows the lambda:InvokeFunction action"));
verify(executor, never()).invoke(argThat(isFunction(functionArn)), any(), any());
}
@Test
void aGrantOnAnAliasCoversTasksThatNameTheAliasOnly() {
String roleArn = createRole("sfn-exec-" + suffix(), INVOKE_ANYTHING);
String name = "worker-" + suffix();
String functionArn = createFunction(FUNCTION_ACCOUNT, name);
publishVersionAndAlias(name, "live");
addPermission(functionArn, "live", Map.of("Principal", SFN_ACCOUNT));
runTask(roleArn, functionArn + ":live").body("status", equalTo("SUCCEEDED"));
runTask(roleArn, functionArn)
.body("status", equalTo("FAILED"))
.body("error", equalTo("Lambda.AccessDeniedException"));
}
@Test
void inItsOwnAccountTheRolesPermissionIsEnough() {
String roleArn = createRole("sfn-exec-" + suffix(), INVOKE_ANYTHING);
String functionArn = createFunction(SFN_ACCOUNT, "own-" + suffix());
runTask(roleArn, functionArn).body("status", equalTo("SUCCEEDED"));
}
@Test
void inItsOwnAccountARoleWithoutPermissionFailsTheTask() {
String roleArn = createRole("sfn-exec-" + suffix(), """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""");
String functionArn = createFunction(SFN_ACCOUNT, "own-" + suffix());
runTask(roleArn, functionArn)
.body("status", equalTo("FAILED"))
.body("error", equalTo("Lambda.AccessDeniedException"))
.body("cause", containsString("because no identity-based policy allows the lambda:InvokeFunction action"));
verify(executor, never()).invoke(argThat(isFunction(functionArn)), any(), any());
}
@Test
void aTaskWithCredentialsInvokesAsTheRoleTheyNameInTheFunctionsAccount() {
String executionRoleArn = createRole("sfn-exec-" + suffix(), ASSUME_ANY_ROLE);
String stateMachineName = "cross-account-" + suffix();
String stateMachineArn = "arn:aws:states:" + REGION + ":" + SFN_ACCOUNT + ":stateMachine:" + stateMachineName;
String taskRoleArn = createRole(FUNCTION_ACCOUNT, "LambdaRole-" + suffix(), "/", """
{"Version":"2012-10-17","Statement":[{
"Effect":"Allow","Principal":{"AWS":"%s"},"Action":"sts:AssumeRole",
"Condition":{"StringEquals":{"sts:ExternalId":"%s"}}}]}"""
.formatted(executionRoleArn, stateMachineArn), INVOKE_ANYTHING);
String functionArn = createFunction(FUNCTION_ACCOUNT, "worker-" + suffix());
run(executionRoleArn, stateMachineName, """
{"StartAt":"Call","States":{"Call":{"Type":"Task","Resource":"%s",
"Credentials":{"RoleArn":"%s"},"End":true}}}""".formatted(functionArn, taskRoleArn), "{}")
.body("status", equalTo("SUCCEEDED"));
verify(executor).invoke(argThat(isFunction(functionArn)), any(), any());
}
@Test
void inItsOwnAccountATaskWithCredentialsNeedsOnlyThatRoleToInvoke() {
String executionRoleArn = createRole("sfn-exec-" + suffix(), ASSUME_ANY_ROLE);
String taskRoleArn = createRole(SFN_ACCOUNT, "invoker-" + suffix(), "/", trusting(executionRoleArn),
INVOKE_ANYTHING);
String functionArn = createFunction(SFN_ACCOUNT, "own-" + suffix());
run(executionRoleArn, "own-account-" + suffix(), """
{"StartAt":"Call","States":{"Call":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke",
"Parameters":{"FunctionName":"%s"},"Credentials":{"RoleArn.$":"$.roleArn"},"End":true}}}"""
.formatted(functionArn), "{\"roleArn\":\"" + taskRoleArn + "\"}")
.body("status", equalTo("SUCCEEDED"));
verify(executor).invoke(argThat(isFunction(functionArn)), any(), any());
}
@Test
void aRoleThatDoesNotTrustTheExecutionRoleFailsTheTaskWithStatesPermissions() {
String executionRoleName = "sfn-exec-" + suffix();
String executionRoleArn = createRole(executionRoleName, ASSUME_ANY_ROLE);
String taskRoleArn = createRole(FUNCTION_ACCOUNT, "LambdaRole-" + suffix(), "/", STATES_TRUST, INVOKE_ANYTHING);
String functionArn = createFunction(FUNCTION_ACCOUNT, "worker-" + suffix());
run(executionRoleArn, "cross-account-" + suffix(), """
{"StartAt":"Call","States":{"Call":{"Type":"Task","Resource":"%s",
"Credentials":{"RoleArn":"%s"},"End":true}}}""".formatted(functionArn, taskRoleArn), "{}")
.body("status", equalTo("FAILED"))
.body("error", equalTo("States.Permissions"))
.body("cause", equalTo("User: arn:aws:sts::" + SFN_ACCOUNT + ":assumed-role/" + executionRoleName
+ " is not authorized to perform: sts:AssumeRole on resource: " + taskRoleArn
+ " because no role trust policy allows the sts:AssumeRole action"));
verify(executor, never()).invoke(argThat(isFunction(functionArn)), any(), any());
}
private ValidatableResponse runTask(String roleArn, String resource) {
return run(roleArn, "cross-account-" + suffix(), """
{"StartAt":"Call","States":{"Call":{"Type":"Task","Resource":"%s","End":true}}}"""
.formatted(resource), "{}");
}
private ValidatableResponse run(String roleArn, String stateMachineName, String definition, String input) {
String stateMachineArn = createStateMachine(roleArn, stateMachineName, definition);
return sfn("StartSyncExecution", Map.of("stateMachineArn", stateMachineArn, "input", input))
.statusCode(200);
}
private String createStateMachine(String roleArn, String name, String definition) {
String stateMachineArn = sfn("CreateStateMachine", Map.of(
"name", name,
"type", "EXPRESS",
"roleArn", roleArn,
"definition", definition))
.statusCode(200)
.extract().path("stateMachineArn");
cleanup.push(() -> sfn("DeleteStateMachine", Map.of("stateMachineArn", stateMachineArn)).statusCode(200));
return stateMachineArn;
}
private static ValidatableResponse sfn(String operation, Map<String, String> request) {
return given()
.header("Authorization", authorization(SFN_ACCOUNT, "states"))
.header("X-Amz-Target", "AWSStepFunctions." + operation)
.contentType(SFN_CONTENT_TYPE)
.body(request)
.when()
.post("/")
.then();
}
private static String suffix() {
return UUID.randomUUID().toString().substring(0, 8);
}
private static ArgumentMatcher<LambdaFunction> isFunction(String functionArn) {
return fn -> fn != null && functionArn.equals(fn.getFunctionArn());
}
private String createFunction(String account, String name) {
lambda(account)
.body("""
{"FunctionName":"%s","Runtime":"nodejs20.x","Handler":"index.handler",
"Role":"arn:aws:iam::%s:role/lambda-role"}""".formatted(name, account))
.when()
.post("/2015-03-31/functions")
.then()
.statusCode(201);
cleanup.push(() -> lambda(account).delete("/2015-03-31/functions/{name}", name).then().statusCode(204));
return "arn:aws:lambda:" + REGION + ":" + account + ":function:" + name;
}
private static void publishVersionAndAlias(String name, String alias) {
lambda(FUNCTION_ACCOUNT).body("{}").post("/2015-03-31/functions/{name}/versions", name).then().statusCode(201);
lambda(FUNCTION_ACCOUNT)
.body("{\"Name\":\"" + alias + "\",\"FunctionVersion\":\"1\"}")
.post("/2015-03-31/functions/{name}/aliases", name)
.then()
.statusCode(201);
}
private static void addPermission(String functionArn, String qualifier, Map<String, Object> grant) {
String account = functionArn.split(":")[4];
Map<String, Object> request = new LinkedHashMap<>();
request.put("StatementId", "s-" + suffix());
request.put("Action", "lambda:InvokeFunction");
request.putAll(grant);
RequestSpecification spec = lambda(account).body(request);
if (qualifier != null) {
spec.queryParam("Qualifier", qualifier);
}
spec.post("/2015-03-31/functions/{name}/policy", functionArn).then().statusCode(201);
}
private static RequestSpecification lambda(String account) {
return given()
.header("Authorization", authorization(account, "lambda"))
.contentType("application/json");
}
/** An execution role, which Step Functions assumes. */
private String createRole(String roleName, String policyDocument) {
return createRole(SFN_ACCOUNT, roleName, "/service-role/", STATES_TRUST, policyDocument);
}
private String createRole(String account, String roleName, String path, String trustPolicy,
String policyDocument) {
String roleArn = iam(account, "CreateRole", Map.of(
"RoleName", roleName,
"Path", path,
"AssumeRolePolicyDocument", trustPolicy))
.statusCode(200)
.extract().path("CreateRoleResponse.CreateRoleResult.Role.Arn");
cleanup.push(() -> iam(account, "DeleteRole", Map.of("RoleName", roleName)).statusCode(200));
iam(account, "PutRolePolicy", Map.of(
"RoleName", roleName,
"PolicyName", "inline",
"PolicyDocument", policyDocument)).statusCode(200);
cleanup.push(() -> iam(account, "DeleteRolePolicy",
Map.of("RoleName", roleName, "PolicyName", "inline")).statusCode(200));
return roleArn;
}
private static String trusting(String roleArn) {
return """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"%s"},"Action":"sts:AssumeRole"}]}""".formatted(roleArn);
}
private static ValidatableResponse iam(String account, String action, Map<String, String> params) {
RequestSpecification spec = given()
.header("Authorization", authorization(account, "iam"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action)
.formParam("Version", "2010-05-08");
params.forEach(spec::formParam);
return spec.when().post("/").then();
}
private static String authorization(String accessKeyId, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20261012/" + REGION + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
}