mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+41
@@ -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()));
|
||||
|
||||
+165
-12
@@ -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) -> {
|
||||
|
||||
+1
-1
@@ -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");
|
||||
|
||||
+414
@@ -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);
|
||||
}
|
||||
}
|
||||
+349
@@ -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";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user