feat(stepfunctions): evaluate the execution role on SQS tasks (#7574)

* feat(stepfunctions): evaluate the execution role on SQS tasks

Under IAM enforcement an SQS task now requires the execution role to exist
and trust Step Functions, assumes the role its Credentials name, and checks
sqs:SendMessage on the queue as the role it ends up with. LambdaTaskAuthorizer
gains a general authorize() that later integrations map onto through
TaskPermissions; it reads any service's resource policy and accepts resource
* and an S3 ARN's empty account. Lambda, API Gateway and nested tasks keep
their own paths and errors.

TaskScheduled and LambdaFunctionScheduled record taskCredentials when a task
declares Credentials. With enforcement off they are read softly, so a RoleArn
that does not resolve is omitted and the task still runs.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(stepfunctions): let a queue's policy decide SQS task and direct calls

SQS had no resource policy provider, so a task's call to a queue in another account could never be granted. Add one reading the queue's Policy attribute, which IAM enforcement and the task authorizer both read, and build a direct request's ARN from the account its QueueUrl names so the right queue's policy is read.

Credentials read only for history now tolerate only a resolution failure, and the Step Functions integration tests share one client.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-05 09:50:01 -06:00
1 parent 4b09c3cf2b
commit bd65477927
21 files changed
+1489 -108

No files matched your search

@@ -1579,6 +1579,12 @@ class ResourceArnBuilderTest {
// ── SQS ─────────────────────────────────────────────────────────────────────
@Test
void sqsNamesTheAccountTheQueueUrlNames() {
queryParams.putSingle("QueueUrl", "http://localhost:4566/111122223333/orders");
assertEquals("arn:aws:sqs:us-east-1:111122223333:orders", builder.build("sqs", ctx, "us-east-1", "000000000000"));
}
@Test
void sqsBuildsArnFromJsonQueueName() {
setJsonBody("{\"QueueName\":\"order-queue\"}");
@@ -0,0 +1,127 @@
package io.github.hectorvent.floci.services.sqs;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.SqsTestQueue;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class SqsQueuePolicyEnforcementIntegrationTest {
private static final String OWNER = "000000000451";
private static final String OTHER = "000000000452";
private static final String REGION = "us-east-1";
private static final String SEND = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sqs:SendMessage","Resource":"*"}]}
""";
private static final String READ_ONLY = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sqs:GetQueueUrl","Resource":"*"}]}
""";
@TestHTTPResource
URI baseUri;
@Inject
SqsService sqsService;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void anotherAccountNeedsTheQueueToGrantIt() {
SqsTestQueue queue = queue();
String accessKey = user(OTHER, SEND);
send(accessKey, queue).statusCode(403);
queue.addPermission("from-other", OTHER, "SendMessage");
send(accessKey, queue).statusCode(200);
assertEquals("hello", queue.receive().getFirst().getBody());
}
@Test
void aQueueGrantDoesNotReplaceTheOtherAccountsOwnPolicy() {
SqsTestQueue queue = queue();
queue.addPermission("from-other", OTHER, "SendMessage");
send(user(OTHER, READ_ONLY), queue).statusCode(403);
}
@Test
void aQueuePolicyAloneAllowsAUserOfItsOwnAccount() {
SqsTestQueue queue = queue();
String name = "sqs-policy-" + UUID.randomUUID();
String accessKey = user(OWNER, name, READ_ONLY);
send(accessKey, queue).statusCode(403);
queue.setPolicy(policy("Allow", "arn:aws:iam::" + OWNER + ":user/" + name, queue.arn()));
send(accessKey, queue).statusCode(200);
}
@Test
void aQueuePolicyDenyRefusesAUserAllowedTheAction() {
SqsTestQueue queue = queue();
String name = "sqs-policy-" + UUID.randomUUID();
String accessKey = user(OWNER, name, SEND);
send(accessKey, queue).statusCode(200);
queue.setPolicy(policy("Deny", "arn:aws:iam::" + OWNER + ":user/" + name, queue.arn()));
send(accessKey, queue).statusCode(403);
}
private static String policy(String effect, String principal, String queueArn) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"%s"},
"Action":"sqs:SendMessage","Resource":"%s"}]}
""".formatted(effect, principal, queueArn);
}
private SqsTestQueue queue() {
SqsTestQueue queue = SqsTestQueue.create(sqsService, OWNER, REGION, "sqs-policy-");
cleanup.register(queue::delete);
return queue;
}
private String user(String account, String policy) {
return user(account, "sqs-policy-" + UUID.randomUUID(), policy);
}
private String user(String account, String name, String policy) {
String authorization = auth(account, "iam");
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), authorization, name);
EnforcementFixtures.putUserPolicy(baseUri.getPort(), authorization, name, "p", policy);
return credentials.accessKeyId();
}
private ValidatableResponse send(String accessKey, SqsTestQueue queue) {
return given().port(baseUri.getPort()).header("Authorization", auth(accessKey, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "SendMessage").formParam("Version", "2012-11-05")
.formParam("QueueUrl", queue.url()).formParam("MessageBody", "hello")
.post("/").then();
}
}
@@ -0,0 +1,50 @@
package io.github.hectorvent.floci.services.sqs;
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy;
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.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class SqsResourcePolicyProviderTest {
private static final String OWNER = "111122223333";
private static final String QUEUE = "arn:aws:sqs:us-east-1:" + OWNER + ":orders";
private static final String POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
private SqsService sqsService;
private SqsResourcePolicyProvider provider;
@BeforeEach
void setUp() {
sqsService = mock(SqsService.class);
when(sqsService.findQueuePolicy(anyString())).thenReturn(Optional.empty());
provider = new SqsResourcePolicyProvider(sqsService);
}
@Test
void aQueueComesWithItsPolicyAndTheAccountInItsArn() {
when(sqsService.findQueuePolicy(QUEUE)).thenReturn(Optional.of(POLICY));
assertEquals(List.of(new ResourcePolicy(POLICY, OWNER)), provider.getResourcePolicies("sqs", QUEUE));
}
@Test
void aQueueWithNoPolicyStillHasItsOwner() {
assertEquals(List.of(new ResourcePolicy(null, OWNER)), provider.getResourcePolicies("sqs", QUEUE));
}
@Test
void anythingThatIsNotOneQueueIsLeftToOtherProviders() {
assertTrue(provider.getResourcePolicies("sqs", "*").isEmpty());
assertTrue(provider.getResourcePolicies("sqs", "arn:aws:sqs:us-east-1:" + OWNER + ":*").isEmpty());
assertTrue(provider.getResourcePolicies("sns", "arn:aws:sns:us-east-1:" + OWNER + ":topic").isEmpty());
}
}
@@ -15,10 +15,10 @@ import io.github.hectorvent.floci.services.apigateway.model.RestApi;
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;
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 io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.AfterEach;
@@ -84,8 +84,9 @@ class ApiGatewayTaskInvokerTest {
void setup() throws Exception {
IamPolicyEvaluator policies = new IamPolicyEvaluator(mapper);
AssumeRolePolicyEvaluator trust = new AssumeRolePolicyEvaluator(mapper, policies);
LambdaTaskAuthorizer authorizer = new LambdaTaskAuthorizer(iam, policies, trust,
mock(LambdaResourcePolicyProvider.class), scps);
Instance<ResourcePolicyProvider> resourcePolicies = mock(Instance.class);
when(resourcePolicies.isUnsatisfied()).thenReturn(true);
LambdaTaskAuthorizer authorizer = new LambdaTaskAuthorizer(iam, policies, trust, resourcePolicies, scps);
when(config.services().iam().enforcementEnabled()).thenReturn(true);
invoker = new ApiGatewayTaskInvoker(api, iam, trust, authorizer, config, mapper, listener);
machine = new StateMachine();
@@ -22,6 +22,8 @@ import io.vertx.mutiny.core.Vertx;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
@@ -49,6 +51,8 @@ class AslExecutorTaskHistoryEventsTest {
private static final String REGION = "us-east-2";
private static final String ACCOUNT = "000000000000";
private static final String SQS_RESOURCE = "arn:aws:states:::aws-sdk:sqs:sendMessage";
private static final String TASK_ROLE = "arn:aws:iam::000000000000:role/task-role";
private final ObjectMapper objectMapper = new ObjectMapper();
private LambdaExecutorService lambdaExecutor;
@@ -69,8 +73,13 @@ class AslExecutorTaskHistoryEventsTest {
}
private AslExecutor newExecutor(DynamoDbFacade dynamoDb) {
return newExecutor(dynamoDb, false);
}
private AslExecutor newExecutor(DynamoDbFacade dynamoDb, boolean enforcing) {
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().stepfunctions().maxWaitSeconds()).thenReturn(30);
when(config.services().iam().enforcementEnabled()).thenReturn(enforcing);
return AslExecutorFixture.builder()
.lambdaExecutor(lambdaExecutor)
@@ -151,6 +160,100 @@ class AslExecutorTaskHistoryEventsTest {
assertEquals("hello", parameters.path("MessageBody").asText());
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void declaredCredentialsAppearInTaskScheduled(boolean enforcing) throws Exception {
executor = newExecutor(mock(DynamoDbFacade.class), enforcing);
Map<String, Object> details = scheduledDetails("TaskScheduled", SQS_RESOURCE,
"\"Credentials\": {\"RoleArn\": \"" + TASK_ROLE + "\"},", "{}");
assertEquals(Map.of("roleArn", TASK_ROLE), details.get("taskCredentials"));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void credentialsResolvedFromTheInputAppearInTaskScheduled(boolean enforcing) throws Exception {
executor = newExecutor(mock(DynamoDbFacade.class), enforcing);
Map<String, Object> details = scheduledDetails("TaskScheduled", SQS_RESOURCE,
"\"Credentials\": {\"RoleArn.$\": \"$.role\"},", "{\"role\":\"" + TASK_ROLE + "\"}");
assertEquals(Map.of("roleArn", TASK_ROLE), details.get("taskCredentials"));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void declaredCredentialsAppearInLambdaFunctionScheduled(boolean enforcing) throws Exception {
executor = newExecutor(mock(DynamoDbFacade.class), enforcing);
Map<String, Object> details = scheduledDetails("LambdaFunctionScheduled", lambdaArn("worker"),
"\"Credentials\": {\"RoleArn\": \"" + TASK_ROLE + "\"},", "{}");
assertEquals(Map.of("roleArn", TASK_ROLE), details.get("taskCredentials"));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void noCredentialsMeansNoTaskCredentials(boolean enforcing) throws Exception {
executor = newExecutor(mock(DynamoDbFacade.class), enforcing);
assertFalse(scheduledDetails("TaskScheduled", SQS_RESOURCE, "", "{}").containsKey("taskCredentials"));
}
/** ActivityScheduledEventDetails has no taskCredentials member, so strict SDKs would not expect one. */
@ParameterizedTest
@ValueSource(booleans = {true, false})
void anActivityNeverRecordsTaskCredentials(boolean enforcing) throws Exception {
executor = newExecutor(mock(DynamoDbFacade.class), enforcing);
assertFalse(scheduledDetails("ActivityScheduled",
"arn:aws:states:%s:%s:activity:work".formatted(REGION, ACCOUNT),
"\"Credentials\": {\"RoleArn\": \"" + TASK_ROLE + "\"},", "{}").containsKey("taskCredentials"));
}
/** With enforcement off Credentials have no effect on a task, so one that cannot resolve must not fail it. */
@Test
void credentialsThatDoNotResolveAreOmittedWithEnforcementOff() throws Exception {
assertFalse(scheduledDetails("TaskScheduled", SQS_RESOURCE,
"\"Credentials\": {\"RoleArn.$\": \"$.missing\"},", "{}").containsKey("taskCredentials"));
}
@Test
void jsonataCredentialsThatDoNotResolveAreOmittedWithEnforcementOff() throws Exception {
ArrayList<HistoryEvent> history = new ArrayList<>();
Execution execution = run("""
{"QueryLanguage": "JSONata", "StartAt": "Send", "States": {"Send": {"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:sqs:sendMessage",
"Credentials": {"RoleArn": "{% $missing.role.$error() %}"},
"Arguments": {"QueueUrl": "q", "MessageBody": "x"}, "End": true}}}
""", "{}", testCase(Map.of("Send", List.of(returnStep(0, 0, "{}")))), history);
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
assertFalse(detailsOf(history, "TaskScheduled").containsKey("taskCredentials"));
}
@Test
void credentialsNamingNoRoleAreOmitted() throws Exception {
assertFalse(scheduledDetails("TaskScheduled", SQS_RESOURCE,
"\"Credentials\": {\"RoleArn\": 42},", "{}").containsKey("taskCredentials"));
}
private Map<String, Object> scheduledDetails(String eventType, String resource, String credentials, String input)
throws Exception {
ArrayList<HistoryEvent> history = new ArrayList<>();
Execution execution = run("""
{"StartAt": "Send", "States": {"Send": {"Type": "Task", "Resource": "%s", %s "End": true}}}
""".formatted(resource, credentials), input,
testCase(Map.of("Send", List.of(returnStep(0, 0, "{}")))), history);
assertEquals("SUCCEEDED", execution.getStatus(), execution.getCause());
return detailsOf(history, eventType);
}
private static Map<String, Object> detailsOf(List<HistoryEvent> history, String eventType) {
return history.stream().filter(event -> eventType.equals(event.getType())).findFirst().orElseThrow().getDetails();
}
@Test
void retriedMockEmitsTaskEventsPerAttempt() throws Exception {
MockedTestCase mocks = testCase(Map.of("Send", List.of(
@@ -4,20 +4,27 @@ 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;
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 io.github.hectorvent.floci.services.stepfunctions.LambdaTaskAuthorizer.Permission;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import jakarta.enterprise.inject.Instance;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -45,8 +52,20 @@ class LambdaTaskAuthorizerTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}""";
private static final String BUCKET = "arn:aws:s3:::orders";
private static final String PUT_OBJECTS = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}]}""";
private static final String STATES_DESCRIBE_ANYTHING = """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"states:DescribeRegions","Resource":"*"}]}""";
private static final String STATES_TRUST = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
"Principal":{"Service":"states.amazonaws.com"}}]}""";
private IamService iamService;
private LambdaResourcePolicyProvider functionPolicies;
private ResourcePolicyProvider bucketPolicies;
private Instance<ScpProvider> scpProvider;
private LambdaTaskAuthorizer authorizer;
@@ -56,14 +75,19 @@ class LambdaTaskAuthorizerTest {
iamService = mock(IamService.class);
functionPolicies = mock(LambdaResourcePolicyProvider.class);
scpProvider = mock(Instance.class);
when(functionPolicies.getResourcePolicies(anyString(), anyString()))
when(functionPolicies.getResourcePolicies(eq("lambda"), anyString()))
.thenReturn(List.of(new ResourcePolicy(null, FUNCTION_ACCOUNT)));
when(functionPolicies.getResourcePolicies("lambda", OWN_FUNCTION))
.thenReturn(List.of(new ResourcePolicy(null, SFN_ACCOUNT)));
when(functionPolicies.getResourcePolicies(anyString(), anyString(), anyString())).thenCallRealMethod();
bucketPolicies = mock(ResourcePolicyProvider.class);
when(bucketPolicies.getResourcePolicies(anyString(), anyString(), anyString())).thenReturn(List.of());
Instance<ResourcePolicyProvider> providers = mock(Instance.class);
when(providers.iterator()).thenAnswer(call -> List.of(functionPolicies, bucketPolicies).iterator());
ObjectMapper mapper = new ObjectMapper();
IamPolicyEvaluator evaluator = new IamPolicyEvaluator(mapper);
authorizer = new LambdaTaskAuthorizer(iamService, evaluator, new AssumeRolePolicyEvaluator(mapper, evaluator),
functionPolicies, scpProvider);
providers, scpProvider);
}
@Test
@@ -389,6 +413,166 @@ class LambdaTaskAuthorizerTest {
authorizer.assumeRefusal(ROLE, OWN_TASK_ROLE, STATE_MACHINE));
}
@Test
void aPermissionOnAnyResourceNeedsAPolicyOnAnyResource() {
roleWithPolicies(STATES_DESCRIBE_ANYTHING);
executionRole(STATES_TRUST);
authorizer.authorize(machine(), null, "Ec2.", List.of(new Permission("states:DescribeRegions", "*")));
}
@Test
void aPolicyOnOneResourceDoesNotCoverAPermissionOnAnyResource() {
roleWithPolicies("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"states:DescribeRegions","Resource":"%s"}]}""".formatted(BUCKET));
executionRole(STATES_TRUST);
AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class,
() -> authorizer.authorize(machine(), null, "Ec2.",
List.of(new Permission("states:DescribeRegions", "*"))));
assertEquals("Ec2.AccessDeniedException", refused.error);
assertEquals("User: " + SESSION + " is not authorized to perform: states:DescribeRegions on resource: * "
+ "because no identity-based policy allows the states:DescribeRegions action", refused.cause);
}
/** An S3 ARN has no account segment: with no owner known, it is not another account's resource. */
@Test
void anS3ArnWithNoAccountIsNotCrossAccount() {
roleWithPolicies(PUT_OBJECTS);
assertEquals(Optional.empty(), authorizer.refusal(ROLE, "s3:PutObject", BUCKET));
}
@Test
void anS3BucketOfAnotherAccountIsCrossAccount() {
roleWithPolicies(PUT_OBJECTS);
when(bucketPolicies.getResourcePolicies("s3", "s3:PutObject", BUCKET))
.thenReturn(List.of(new ResourcePolicy(null, FUNCTION_ACCOUNT)));
assertEquals(Optional.of("User: " + SESSION + " is not authorized to perform: s3:PutObject on resource: " + BUCKET
+ " because no resource-based policy allows the s3:PutObject action"),
authorizer.refusal(ROLE, "s3:PutObject", BUCKET));
}
@Test
void aResourcePolicyOfAnyServiceCanGrantTheRole() {
roleWithPolicies(READ_OBJECTS);
when(bucketPolicies.getResourcePolicies("s3", "s3:PutObject", BUCKET))
.thenReturn(List.of(new ResourcePolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"%s"},
"Action":"s3:PutObject","Resource":"%s"}]}""".formatted(ROLE, BUCKET), SFN_ACCOUNT)));
assertEquals(Optional.empty(), authorizer.refusal(ROLE, "s3:PutObject", BUCKET));
}
@Test
void aResourcePolicyOfAnyServiceCanRefuseTheRole() {
roleWithPolicies(PUT_OBJECTS);
when(bucketPolicies.getResourcePolicies("s3", "s3:PutObject", BUCKET))
.thenReturn(List.of(new ResourcePolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Principal":"*",
"Action":"s3:PutObject","Resource":"%s"}]}""".formatted(BUCKET), SFN_ACCOUNT)));
assertEquals(Optional.of("User: " + SESSION + " is not authorized to perform: s3:PutObject on resource: " + BUCKET
+ " with an explicit deny in a resource-based policy"),
authorizer.refusal(ROLE, "s3:PutObject", BUCKET));
}
@Test
void aPermissionsConditionKeysReachThePolicy() {
roleWithPolicies("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"states:InvokeHTTPEndpoint",
"Resource":"*","Condition":{"StringEquals":{"states:HTTPEndpoint":"https://example.test"}}}]}""");
executionRole(STATES_TRUST);
authorizer.authorize(machine(), null, "States.", List.of(new Permission("states:InvokeHTTPEndpoint", "*",
Map.of("states:HTTPEndpoint", List.of("https://example.test")))));
AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class,
() -> authorizer.authorize(machine(), null, "States.", List.of(new Permission(
"states:InvokeHTTPEndpoint", "*", Map.of("states:HTTPEndpoint", List.of("https://other.test"))))));
assertEquals("States.AccessDeniedException", refused.error);
}
/** An S3 ARN and {@code *} name no Region, and the task's call still goes to the state machine's. */
@Test
void theRequestedRegionIsTheStateMachinesWhateverTheResourceNames() {
roleWithPolicies("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:PutObject","Resource":"*",
"Condition":{"StringEquals":{"aws:RequestedRegion":"us-east-1"}}}]}""");
executionRole(STATES_TRUST);
authorizer.authorize(machine(), null, "S3.", List.of(new Permission("s3:PutObject", BUCKET)));
}
@Test
void anExecutionRoleThatDoesNotExistRefusesTheTask() {
AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class,
() -> authorizer.authorize(machine(), null, "SQS.", List.of()));
assertEquals("States.Permissions", refused.error);
assertTrue(refused.cause.contains(ROLE), refused.cause);
}
@Test
void anExecutionRoleThatDoesNotTrustStepFunctionsRefusesTheTaskWhateverItsPolicies() {
roleWithPolicies(PUT_OBJECTS);
executionRole(trust("{\"Service\":\"lambda.amazonaws.com\"}"));
AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class,
() -> authorizer.authorize(machine(), null, "S3.", List.of(new Permission("s3:PutObject", BUCKET))));
assertEquals("States.Permissions", refused.error);
assertTrue(refused.cause.contains(ROLE), refused.cause);
}
@Test
void everyPermissionIsDecidedAsTheRoleTheCredentialsName() {
roleWithPolicies(ASSUME_ANY_ROLE);
executionRole(STATES_TRUST);
taskRole(OWN_TASK_ROLE, trust("{\"AWS\":\"" + ROLE + "\"}"));
when(iamService.resolvePrincipalContext(ROLE)).thenReturn(CallerContext.of(List.of(ASSUME_ANY_ROLE)));
when(iamService.resolvePrincipalContext(OWN_TASK_ROLE)).thenReturn(CallerContext.of(List.of(PUT_OBJECTS)));
authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of(new Permission("s3:PutObject", BUCKET)));
AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class,
() -> authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of(
new Permission("s3:PutObject", BUCKET), new Permission("s3:GetObject", BUCKET))));
assertEquals("S3.AccessDeniedException", refused.error);
assertTrue(refused.cause.contains("assumed-role/LambdaRole"), refused.cause);
assertTrue(refused.cause.contains("s3:GetObject"), refused.cause);
}
@Test
void aRoleTheExecutionRoleCannotAssumeFailsTheTaskInTheNestedForm() {
roleWithPolicies(PUT_OBJECTS);
executionRole(STATES_TRUST);
taskRole(OWN_TASK_ROLE, trust("{\"Service\":\"lambda.amazonaws.com\"}"));
AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class,
() -> authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of()));
assertEquals("States.TaskFailed", refused.error);
assertEquals("The role " + ROLE + " is not authorized to assume the task state's role, " + OWN_TASK_ROLE + ".",
refused.cause);
}
private void executionRole(String trustPolicy) {
IamRole role = new IamRole();
role.setArn(ROLE);
role.setAssumeRolePolicyDocument(trustPolicy);
when(iamService.findRole(SFN_ACCOUNT, "sfn-exec")).thenReturn(Optional.of(role));
}
private static StateMachine machine() {
StateMachine machine = new StateMachine();
machine.setStateMachineArn(STATE_MACHINE);
machine.setRoleArn(ROLE);
return 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);
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.StepFunctionsTestClient;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
@@ -20,14 +21,10 @@ import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
@@ -166,50 +163,23 @@ class StepFunctionsNestedTaskIamIntegrationTest {
}
private String machine(String account, String definition, String type, String role) {
String name = "nested-iam-" + UUID.randomUUID();
String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name;
cleanup.register(() -> {
Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn));
if (executions.statusCode() == 200) {
for (Map<String, String> execution : executions.jsonPath().<Map<String, String>>getList("executions")) {
if ("RUNNING".equals(execution.get("status"))) {
request(account, "StopExecution", Map.of("executionArn", execution.get("executionArn")))
.then().statusCode(200);
}
}
}
request(account, "DeleteStateMachine", Map.of("stateMachineArn", arn)).then().statusCode(200);
});
Response created = request(account, "CreateStateMachine", Map.of(
"name", name, "definition", definition, "type", type, "roleArn", role));
created.then().statusCode(200);
return created.jsonPath().getString("stateMachineArn");
return sfn().createMachine(account, "nested-iam-", definition, type, role);
}
private String start(String machine) {
Response started = request(SOURCE, "StartExecution", Map.of("stateMachineArn", machine, "input", "{}"));
started.then().statusCode(200);
return started.jsonPath().getString("executionArn");
return sfn().start(SOURCE, machine, "{}");
}
private Response terminal(String execution) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
do {
Response response = request(SOURCE, "DescribeExecution", Map.of("executionArn", execution));
response.then().statusCode(200);
if (!"RUNNING".equals(response.jsonPath().getString("status"))) {
return response;
}
Thread.sleep(25);
} while (System.nanoTime() < deadline);
fail("Execution did not terminate: " + execution);
return null;
return sfn().terminal(SOURCE, execution, 5);
}
private Response request(String account, String action, Map<String, ?> input) {
return given().port(baseUri.getPort()).header("Authorization", auth(account, "states"))
.header("X-Amz-Target", "AWSStepFunctions." + action)
.contentType("application/x-amz-json-1.0").body(MAPPER.valueToTree(input).toString()).post("/");
return sfn().request(account, action, input);
}
private StepFunctionsTestClient sfn() {
return new StepFunctionsTestClient(baseUri.getPort(), cleanup);
}
private record Fixture(String parent, String child, String executionRole, String taskRole) {
@@ -0,0 +1,461 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.SqsTestQueue;
import io.github.hectorvent.floci.testing.StepFunctionsTestClient;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.net.URI;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class StepFunctionsSqsTaskIamIntegrationTest {
private static final String ACCOUNT = "000000000441";
private static final String OTHER_ACCOUNT = "000000000442";
private static final String REGION = "us-east-1";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String STATES_TRUST = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
"Principal":{"Service":"states.amazonaws.com"}}]}
""";
private static final String LAMBDA_TRUST = """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
"Principal":{"Service":"lambda.amazonaws.com"}}]}
""";
private static final String SEND = allow("sqs:SendMessage");
private static final String READ_ONLY = allow("sqs:GetQueueUrl");
private static final String ASSUME = allow("sts:AssumeRole");
@TestHTTPResource
URI baseUri;
@Inject
SqsService sqsService;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"})
void anExecutionRoleAllowedTheActionSends(String integration) throws Exception {
SqsTestQueue queue = queue();
String machine = machine(jsonPathTask(integration, queue, null), role(STATES_TRUST, SEND));
Response completed = terminal(start(machine, "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals("hello", queue.receive().getFirst().getBody());
}
@ParameterizedTest
@CsvSource({"sqs:sendMessage,SQS.AccessDeniedException", "aws-sdk:sqs:sendMessage,Sqs.AccessDeniedException"})
void anExecutionRoleNotAllowedTheActionIsRefused(String integration, String error) throws Exception {
SqsTestQueue queue = queue();
String machine = machine(jsonPathTask(integration, queue, null), role(STATES_TRUST, READ_ONLY));
Response completed = terminal(start(machine, "{}"));
assertFailed(completed, error);
String cause = completed.jsonPath().getString("cause");
assertTrue(cause.contains("sqs:SendMessage"), cause);
assertTrue(cause.contains(queue.arn()), cause);
assertEquals(0, queue.receive().size());
}
@ParameterizedTest
@ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"})
void anExecutionRoleThatDoesNotTrustStepFunctionsIsRefusedWhateverItsPolicies(String integration) throws Exception {
SqsTestQueue queue = queue();
String role = role(LAMBDA_TRUST, SEND);
Response completed = terminal(start(machine(jsonPathTask(integration, queue, null), role), "{}"));
assertFailed(completed, "States.Permissions");
assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString());
assertEquals(0, queue.receive().size());
}
@ParameterizedTest
@ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"})
void anExecutionRoleThatDoesNotExistIsRefused(String integration) throws Exception {
SqsTestQueue queue = queue();
String role = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID();
Response completed = terminal(start(machine(jsonPathTask(integration, queue, null), role), "{}"));
assertFailed(completed, "States.Permissions");
assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString());
assertEquals(0, queue.receive().size());
}
@ParameterizedTest
@CsvSource({"sqs:sendMessage,jsonpath", "aws-sdk:sqs:sendMessage,jsonpath", "sqs:sendMessage,jsonpath-path",
"sqs:sendMessage,jsonata", "aws-sdk:sqs:sendMessage,jsonata"})
void credentialsSendAsTheirRoleWithoutTheExecutionRolesPermission(String integration, String form) throws Exception {
SqsTestQueue queue = queue();
String executionRole = role(STATES_TRUST, ASSUME);
String taskRole = role(trusting(executionRole), SEND);
String machine = machine(task(integration, queue, form, taskRole), executionRole);
String execution = start(machine, MAPPER.writeValueAsString(Map.of("role", taskRole)));
Response completed = terminal(execution);
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals("hello", queue.receive().getFirst().getBody());
JsonNode scheduled = eventsOfType(execution, "TaskScheduled").getFirst();
assertEquals(taskRole, scheduled.path("taskScheduledEventDetails").path("taskCredentials").path("roleArn").asText());
}
@ParameterizedTest
@CsvSource({"sqs:sendMessage,jsonpath", "aws-sdk:sqs:sendMessage,jsonpath", "sqs:sendMessage,jsonata"})
void aRoleTheExecutionRoleCannotAssumeFailsInTheNestedForm(String integration, String form) throws Exception {
SqsTestQueue queue = queue();
String executionRole = role(STATES_TRUST, SEND);
String taskRole = role(LAMBDA_TRUST, SEND);
String machine = machine(task(integration, queue, form, taskRole), executionRole);
Response completed = terminal(start(machine, MAPPER.writeValueAsString(Map.of("role", taskRole))));
assertFailed(completed, "States.TaskFailed");
assertEquals("The role " + executionRole + " is not authorized to assume the task state's role, " + taskRole + ".",
completed.jsonPath().getString("cause"));
assertEquals(0, queue.receive().size());
}
@Test
void aCredentialsRoleThatDoesNotExistFailsAsARefusedAssumption() throws Exception {
SqsTestQueue queue = queue();
String executionRole = role(STATES_TRUST, SEND);
String taskRole = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID();
String machine = machine(jsonPathTask("sqs:sendMessage", queue, taskRole), executionRole);
Response completed = terminal(start(machine, "{}"));
assertFailed(completed, "States.TaskFailed");
assertEquals(0, queue.receive().size());
}
@ParameterizedTest
@CsvSource({"sqs:sendMessage,SQS.AccessDeniedException", "aws-sdk:sqs:sendMessage,Sqs.AccessDeniedException"})
void aCredentialsRoleNotAllowedTheActionIsRefusedEvenIfTheExecutionRoleIs(String integration, String error)
throws Exception {
SqsTestQueue queue = queue();
String executionRole = role(STATES_TRUST, allow("sts:AssumeRole", "sqs:SendMessage"));
String taskRole = role(trusting(executionRole), READ_ONLY);
String machine = machine(jsonPathTask(integration, queue, taskRole), executionRole);
Response completed = terminal(start(machine, "{}"));
assertFailed(completed, error);
String cause = completed.jsonPath().getString("cause");
assertTrue(cause.contains("assumed-role/" + taskRole.substring(taskRole.lastIndexOf('/') + 1)), cause);
assertEquals(0, queue.receive().size());
}
@Test
void aForeignCredentialsRoleNeedsTheQueueToGrantIt() throws Exception {
SqsTestQueue queue = queue();
String executionRole = role(STATES_TRUST, ASSUME);
String foreignRole = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), OTHER_ACCOUNT, "/",
"sfn-sqs-" + UUID.randomUUID(), trusting(executionRole), SEND);
String machine = machine(jsonPathTask("sqs:sendMessage", queue, foreignRole), executionRole);
Response refused = terminal(start(machine, "{}"));
assertFailed(refused, "SQS.AccessDeniedException");
String cause = refused.jsonPath().getString("cause");
assertTrue(cause.contains("arn:aws:sts::" + OTHER_ACCOUNT + ":assumed-role/"), cause);
assertEquals(0, queue.receive().size());
queue.setPolicy(queuePolicy("Allow", foreignRole, queue.arn()));
Response completed = terminal(start(machine, "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals("hello", queue.receive().getFirst().getBody());
}
@Test
void aQueueInAnotherAccountNeedsItsOwnGrant() throws Exception {
SqsTestQueue queue = SqsTestQueue.create(sqsService, OTHER_ACCOUNT, REGION, "sfn-sqs-iam-");
cleanup.register(queue::delete);
String role = role(STATES_TRUST, SEND);
String machine = machine(jsonPathTask("sqs:sendMessage", queue, null), role);
Response refused = terminal(start(machine, "{}"));
assertFailed(refused, "SQS.AccessDeniedException");
assertEquals(0, queue.receive().size());
queue.addPermission("from-" + ACCOUNT, ACCOUNT, "SendMessage");
Response completed = terminal(start(machine, "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals("hello", queue.receive().getFirst().getBody());
}
@Test
void aQueueInAnotherAccountCannotGrantWhatTheRoleLacks() throws Exception {
SqsTestQueue queue = SqsTestQueue.create(sqsService, OTHER_ACCOUNT, REGION, "sfn-sqs-iam-");
cleanup.register(queue::delete);
String role = role(STATES_TRUST, READ_ONLY);
queue.setPolicy(queuePolicy("Allow", role, queue.arn()));
Response completed = terminal(start(machine(jsonPathTask("sqs:sendMessage", queue, null), role), "{}"));
assertFailed(completed, "SQS.AccessDeniedException");
assertEquals(0, queue.receive().size());
}
@Test
void aQueuePolicyAloneAllowsARoleOfItsOwnAccount() throws Exception {
SqsTestQueue queue = queue();
String role = role(STATES_TRUST, READ_ONLY);
queue.setPolicy(queuePolicy("Allow", role, queue.arn()));
Response completed = terminal(start(machine(jsonPathTask("sqs:sendMessage", queue, null), role), "{}"));
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals("hello", queue.receive().getFirst().getBody());
}
@Test
void aQueuePolicyDenyRefusesARoleAllowedTheAction() throws Exception {
SqsTestQueue queue = queue();
String role = role(STATES_TRUST, SEND);
queue.setPolicy(queuePolicy("Deny", role, queue.arn()));
Response completed = terminal(start(machine(jsonPathTask("sqs:sendMessage", queue, null), role), "{}"));
assertFailed(completed, "SQS.AccessDeniedException");
assertEquals(0, queue.receive().size());
}
@Test
void credentialsWithoutARoleArnDoNotFallBackToTheExecutionRole() throws Exception {
SqsTestQueue queue = queue();
String machine = machine(Map.of("Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage",
"Credentials", Map.of("Role", "x"),
"Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true),
role(STATES_TRUST, SEND));
Response completed = terminal(start(machine, "{}"));
assertFailed(completed, "States.Runtime");
assertEquals("Task Credentials must resolve to an object containing RoleArn",
completed.jsonPath().getString("cause"));
assertEquals(0, queue.receive().size());
}
@Test
void waitForTaskTokenRefusedDoesNotWaitAndLeavesNoMessage() throws Exception {
SqsTestQueue queue = queue();
String machine = machine(Map.of("Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
"Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", Map.of("token.$", "$$.Task.Token")),
"TimeoutSeconds", 60, "End", true), role(STATES_TRUST, READ_ONLY));
Response completed = terminal(start(machine, "{}"));
assertFailed(completed, "SQS.AccessDeniedException");
assertEquals(0, queue.receive().size());
}
@Test
void waitForTaskTokenAllowedSendsAndWaits() throws Exception {
SqsTestQueue queue = queue();
String executionRole = role(STATES_TRUST, ASSUME);
String taskRole = role(trusting(executionRole), SEND);
String machine = machine(Map.of("Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage.waitForTaskToken",
"Credentials", Map.of("RoleArn", taskRole),
"Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", Map.of("token.$", "$$.Task.Token")),
"TimeoutSeconds", 60, "End", true), executionRole);
String execution = start(machine, "{}");
String token = queue.awaitJson(Duration.ofSeconds(5)).path("token").asText();
request("SendTaskSuccess", Map.of("taskToken", token, "output", "{\"done\":true}")).then().statusCode(200);
Response completed = terminal(execution);
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
}
@ParameterizedTest
@CsvSource({"sqs:sendMessage,SQS.AccessDeniedException", "aws-sdk:sqs:sendMessage,Sqs.AccessDeniedException"})
void aRefusalCanBeRetriedAndCaught(String integration, String error) throws Exception {
SqsTestQueue queue = queue();
Map<String, Object> task = new LinkedHashMap<>(jsonPathTask(integration, queue, null));
task.put("Retry", List.of(Map.of("ErrorEquals", List.of(error), "IntervalSeconds", 1,
"BackoffRate", 1.0, "MaxAttempts", 1)));
task.put("Catch", List.of(Map.of("ErrorEquals", List.of(error), "Next", "Recovered")));
String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task,
"Recovered", Map.of("Type", "Pass", "End", true))));
String execution = start(machineWithDefinition(definition, role(STATES_TRUST, READ_ONLY)), "{}");
Response completed = terminal(execution);
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals(2, eventsOfType(execution, "TaskFailed").size());
assertEquals(error, eventsOfType(execution, "TaskFailed").getLast()
.path("taskFailedEventDetails").path("error").asText());
}
/** The retry decides again, so a role granted the action between attempts then sends. */
@Test
void aRetryDecidesAgain() throws Exception {
SqsTestQueue queue = queue();
String roleName = "sfn-sqs-" + UUID.randomUUID();
String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", roleName,
STATES_TRUST, READ_ONLY);
Map<String, Object> task = new LinkedHashMap<>(jsonPathTask("sqs:sendMessage", queue, null));
task.put("Retry", List.of(Map.of("ErrorEquals", List.of("SQS.AccessDeniedException"), "IntervalSeconds", 2,
"BackoffRate", 1.0, "MaxAttempts", 3)));
String execution = start(machine(task, role), "{}");
await(execution, "TaskFailed");
given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "iam"))
.formParam("Action", "PutRolePolicy").formParam("Version", "2010-05-08")
.formParam("RoleName", roleName).formParam("PolicyName", "p").formParam("PolicyDocument", SEND)
.post("/").then().statusCode(200);
Response completed = terminal(execution, 20);
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
assertEquals("hello", queue.receive().getFirst().getBody());
}
private static String allow(String... actions) {
try {
return MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", List.of(
Map.of("Effect", "Allow", "Action", List.of(actions), "Resource", "*"))));
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private static String trusting(String role) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
"Principal":{"AWS":"%s"}}]}
""".formatted(role);
}
private static String queuePolicy(String effect, String principal, String queueArn) {
return """
{"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"%s"},
"Action":"sqs:SendMessage","Resource":"%s"}]}
""".formatted(effect, principal, queueArn);
}
private static void assertFailed(Response completed, String error) {
assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString());
assertEquals(error, completed.jsonPath().getString("error"), completed.asString());
}
private Map<String, Object> jsonPathTask(String integration, SqsTestQueue queue, String taskRole) {
Map<String, Object> task = new LinkedHashMap<>(Map.of("Type", "Task",
"Resource", "arn:aws:states:::" + integration,
"Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true));
if (taskRole != null) {
task.put("Credentials", Map.of("RoleArn", taskRole));
}
return task;
}
private Map<String, Object> task(String integration, SqsTestQueue queue, String form, String taskRole) {
return switch (form) {
case "jsonpath" -> jsonPathTask(integration, queue, taskRole);
case "jsonpath-path" -> {
Map<String, Object> task = jsonPathTask(integration, queue, null);
task.put("Credentials", Map.of("RoleArn.$", "$.role"));
yield task;
}
default -> Map.of("Type", "Task", "QueryLanguage", "JSONata",
"Resource", "arn:aws:states:::" + integration,
"Credentials", Map.of("RoleArn", "{% $states.input.role %}"),
"Arguments", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true);
};
}
private SqsTestQueue queue() {
SqsTestQueue queue = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "sfn-sqs-iam-");
cleanup.register(queue::delete);
return queue;
}
private String role(String trust, String policy) {
return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/",
"sfn-sqs-" + UUID.randomUUID(), trust, policy);
}
private String machine(Map<String, Object> task, String role) throws Exception {
return machineWithDefinition(MAPPER.writeValueAsString(
Map.of("StartAt", "Send", "States", Map.of("Send", task))), role);
}
private String machineWithDefinition(String definition, String role) {
return sfn().createMachine(ACCOUNT, "sfn-sqs-iam-", definition, "STANDARD", role);
}
private String start(String machine, String input) {
return sfn().start(ACCOUNT, machine, input);
}
private Response terminal(String execution) throws Exception {
return terminal(execution, 5);
}
private Response terminal(String execution, int seconds) throws Exception {
return sfn().terminal(ACCOUNT, execution, seconds);
}
private void await(String execution, String eventType) throws Exception {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
do {
if (!eventsOfType(execution, eventType).isEmpty()) {
return;
}
Thread.sleep(25);
} while (System.nanoTime() < deadline);
fail("No " + eventType + " event in " + execution);
}
private List<JsonNode> eventsOfType(String execution, String type) throws Exception {
return sfn().eventsOfType(ACCOUNT, execution, type);
}
private Response request(String action, Map<String, ?> input) {
return sfn().request(ACCOUNT, action, input);
}
private StepFunctionsTestClient sfn() {
return new StepFunctionsTestClient(baseUri.getPort(), cleanup);
}
}
@@ -5,14 +5,18 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
import io.github.hectorvent.floci.services.lambda.model.InvokeResult;
import io.github.hectorvent.floci.services.sqs.SqsService;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.github.hectorvent.floci.testing.SqsTestQueue;
import io.github.hectorvent.floci.testing.StepFunctionsTestClient;
import io.quarkus.test.InjectMock;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -29,7 +33,6 @@ import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
@@ -56,6 +59,9 @@ class StepFunctionsTaskCredentialsIntegrationTest {
@InjectSpy
JsonataEvaluator jsonataEvaluator;
@Inject
SqsService sqsService;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@@ -209,6 +215,46 @@ class StepFunctionsTaskCredentialsIntegrationTest {
verify(lambdaExecutor).invoke(argThat(fn -> fn != null && function.equals(fn.getFunctionArn())), any(), any());
}
/** The execution role does not exist, and neither does the Credentials role: nothing evaluates either. */
@ParameterizedTest
@ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"})
void sqsCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception {
SqsTestQueue queue = SqsTestQueue.create(sqsService, SOURCE, "us-east-1", "credentials-");
cleanup.register(queue::delete);
String taskRole = "arn:aws:iam::" + TARGET + ":role/no-such-role";
String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", Map.of(
"Type", "Task", "Resource", "arn:aws:states:::" + integration,
"Credentials", Map.of("RoleArn", taskRole),
"Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true))));
String execution = start(machine(SOURCE, definition, "STANDARD"), "{}");
Response done = terminal(SOURCE, execution);
assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());
assertEquals("hello", queue.receive().getFirst().getBody());
assertEquals(taskRole, taskScheduled(execution).path("taskCredentials").path("roleArn").asText());
}
@Test
void credentialsThatDoNotResolveStillPassWithEnforcementOff() throws Exception {
SqsTestQueue queue = SqsTestQueue.create(sqsService, SOURCE, "us-east-1", "credentials-");
cleanup.register(queue::delete);
String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", Map.of(
"Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage",
"Credentials", Map.of("RoleArn.$", "$.missing"),
"Parameters", Map.of("QueueUrl", queue.url(), "MessageBody", "hello"), "End", true))));
String execution = start(machine(SOURCE, definition, "STANDARD"), "{}");
Response done = terminal(SOURCE, execution);
assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());
assertTrue(taskScheduled(execution).path("taskCredentials").isMissingNode(), done.asString());
}
private JsonNode taskScheduled(String execution) throws Exception {
return sfn().eventsOfType(SOURCE, execution, "TaskScheduled").getFirst().path("taskScheduledEventDetails");
}
@Test
void childFailureIsCaughtInParentAccount() throws Exception {
String child = machine(TARGET, """
@@ -288,50 +334,23 @@ class StepFunctionsTaskCredentialsIntegrationTest {
}
private String machine(String account, String definition, String type) throws Exception {
String name = "credentials-" + UUID.randomUUID();
String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name;
cleanup.register(() -> removeMachine(account, arn));
Response response = request(account, "CreateStateMachine", Map.of(
"name", name, "definition", definition,
"type", type, "roleArn", "arn:aws:iam::" + account + ":role/execution"));
response.then().statusCode(200);
return response.jsonPath().getString("stateMachineArn");
}
private void removeMachine(String account, String arn) {
Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn));
executions.then().statusCode(200);
for (Map<String, String> execution : executions.jsonPath().<Map<String, String>>getList("executions")) {
if ("RUNNING".equals(execution.get("status"))) {
request(account, "StopExecution", Map.of("executionArn", execution.get("executionArn")))
.then().statusCode(200);
}
}
request(account, "DeleteStateMachine", Map.of("stateMachineArn", arn)).then().statusCode(200);
return sfn().createMachine(account, "credentials-", definition, type,
"arn:aws:iam::" + account + ":role/execution");
}
private String start(String machine, String input) throws Exception {
Response response = request(SOURCE, "StartExecution", Map.of("stateMachineArn", machine, "input", input));
response.then().statusCode(200);
return response.jsonPath().getString("executionArn");
return sfn().start(SOURCE, machine, input);
}
private Response terminal(String account, String execution) throws Exception {
for (int i = 0; i < 100; i++) {
Response response = request(account, "DescribeExecution", Map.of("executionArn", execution));
response.then().statusCode(200);
if (!"RUNNING".equals(response.jsonPath().getString("status"))) {
return response;
}
Thread.sleep(50);
}
fail("Execution did not terminate: " + execution);
return null;
return sfn().terminal(account, execution, 5);
}
private Response request(String account, String action, Map<String, ?> input) {
return given().port(baseUri.getPort()).header("Authorization", auth(account, "states"))
.header("X-Amz-Target", "AWSStepFunctions." + action)
.contentType("application/x-amz-json-1.0").body(MAPPER.valueToTree(input).toString()).post("/");
return sfn().request(account, action, input);
}
private StepFunctionsTestClient sfn() {
return new StepFunctionsTestClient(baseUri.getPort(), cleanup);
}
}
@@ -0,0 +1,79 @@
package io.github.hectorvent.floci.services.stepfunctions;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.stepfunctions.LambdaTaskAuthorizer.Permission;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
class TaskPermissionsTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ACCOUNT = "111122223333";
/** Each form resolves in the state machine's Region, whichever host it names, as the queue lookup does. */
@ParameterizedTest
@CsvSource({
"http://localhost:4566/111122223333/orders, 111122223333",
"https://sqs.ap-south-1.amazonaws.com/111122223333/orders, 111122223333",
"http://localhost:4566/sqs/444455556666/orders, 444455556666",
"orders, 111122223333",
"444455556666/orders, 444455556666",
"http://localhost:4566/not-an-account/orders, 111122223333"})
void aQueueUrlNamesTheQueueItsLookupReaches(String queueUrl, String account) {
assertEquals(new TaskPermissions("SQS.", List.of(new Permission("sqs:SendMessage",
"arn:aws:sqs:eu-west-1:" + account + ":orders"))),
TaskPermissions.of(integration("sqs:sendMessage"), input(queueUrl), machine("aws")).orElseThrow());
}
@Test
void theQueueIsInTheStateMachinesPartition() {
assertEquals(List.of(new Permission("sqs:SendMessage", "arn:aws-cn:sqs:eu-west-1:" + ACCOUNT + ":orders")),
TaskPermissions.of(integration("sqs:sendMessage"), input("orders"), machine("aws-cn"))
.orElseThrow().permissions());
}
@Test
void theSdkFormNamesItsOwnErrorPrefix() {
assertEquals("Sqs.", TaskPermissions.of(integration("aws-sdk:sqs:sendMessage"), input("orders"), machine("aws"))
.orElseThrow().errorPrefix());
}
/** SQS answers these with its own validation error once the role has passed. */
@ParameterizedTest
@ValueSource(strings = {"{}", "{\"QueueUrl\":\" \"}", "{\"QueueUrl\":7}"})
void aRequestNamingNoQueueNeedsNoPermission(String request) throws Exception {
assertEquals(new TaskPermissions("SQS.", List.of()),
TaskPermissions.of(integration("sqs:sendMessage"), MAPPER.readTree(request), machine("aws")).orElseThrow());
}
@ParameterizedTest
@ValueSource(strings = {"lambda:invoke", "apigateway:invoke", "sns:publish", "aws-sdk:sqs:receiveMessage",
"states:startExecution", "dynamodb:putItem", "http:invoke"})
void integrationsNotMappedStayUnchecked(String integration) {
assertEquals(Optional.empty(), TaskPermissions.of(integration(integration), input("orders"), machine("aws")));
}
private static StatesIntegration integration(String tail) {
return StatesIntegration.parse("arn:aws:states:::" + tail).orElseThrow();
}
private static JsonNode input(String queueUrl) {
return MAPPER.valueToTree(Map.of("QueueUrl", queueUrl));
}
private static StateMachine machine(String partition) {
StateMachine machine = new StateMachine();
machine.setStateMachineArn("arn:" + partition + ":states:eu-west-1:" + ACCOUNT + ":stateMachine:m");
return machine;
}
}
@@ -53,6 +53,17 @@ public final class SqsTestQueue {
sqsService.getQueueAttributes(url, List.of("QueueArn"), region).get("QueueArn"));
}
/** Sets the queue's {@code Policy} attribute. */
public void setPolicy(String policy) {
RequestScopes.runAs(account, () -> sqsService.setQueueAttributes(url, Map.of("Policy", policy), region));
}
/** Grants {@code action} to the root of {@code grantedAccount}, as AddPermission writes it into the policy. */
public void addPermission(String label, String grantedAccount, String action) {
RequestScopes.runAs(account, () ->
sqsService.addPermission(url, label, List.of(grantedAccount), List.of(action), region));
}
/** At most one message, received without waiting. */
public List<Message> receive() {
return RequestScopes.callAs(account, () ->
@@ -0,0 +1,93 @@
package io.github.hectorvent.floci.testing;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.response.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.fail;
/** Step Functions calls a test makes as one account, and the state machines it leaves to {@code cleanup}. */
public final class StepFunctionsTestClient {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final long POLL_MILLIS = 25;
private final int port;
private final PartitionCleanup cleanup;
public StepFunctionsTestClient(int port, PartitionCleanup cleanup) {
this.port = port;
this.cleanup = cleanup;
}
public Response request(String account, String action, Map<String, ?> input) {
return given().port(port).header("Authorization", auth(account, "states"))
.header("X-Amz-Target", "AWSStepFunctions." + action)
.contentType("application/x-amz-json-1.0").body(MAPPER.valueToTree(input).toString()).post("/");
}
/** Creates a state machine in us-east-1, which the end of the test stops and deletes. */
public String createMachine(String account, String namePrefix, String definition, String type, String role) {
String name = namePrefix + UUID.randomUUID();
String arn = "arn:aws:states:us-east-1:" + account + ":stateMachine:" + name;
cleanup.register(() -> removeMachine(account, arn));
Response created = request(account, "CreateStateMachine", Map.of(
"name", name, "definition", definition, "type", type, "roleArn", role));
created.then().statusCode(200);
return created.jsonPath().getString("stateMachineArn");
}
public String start(String account, String machine, String input) {
Response started = request(account, "StartExecution", Map.of("stateMachineArn", machine, "input", input));
started.then().statusCode(200);
return started.jsonPath().getString("executionArn");
}
/** Polls until the execution ends: nothing in the API waits for a standard workflow. */
public Response terminal(String account, String execution, int seconds) throws InterruptedException {
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds);
do {
Response response = request(account, "DescribeExecution", Map.of("executionArn", execution));
response.then().statusCode(200);
if (!"RUNNING".equals(response.jsonPath().getString("status"))) {
return response;
}
Thread.sleep(POLL_MILLIS);
} while (System.nanoTime() < deadline);
fail("Execution did not terminate: " + execution);
return null;
}
public List<JsonNode> eventsOfType(String account, String execution, String type) throws Exception {
Response history = request(account, "GetExecutionHistory", Map.of("executionArn", execution));
history.then().statusCode(200);
List<JsonNode> events = new ArrayList<>();
for (JsonNode event : MAPPER.readTree(history.asString()).path("events")) {
if (type.equals(event.path("type").asText())) {
events.add(event);
}
}
return events;
}
private void removeMachine(String account, String arn) {
Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn));
if (executions.statusCode() == 200) {
for (Map<String, String> execution : executions.jsonPath().<Map<String, String>>getList("executions")) {
if ("RUNNING".equals(execution.get("status"))) {
request(account, "StopExecution", Map.of("executionArn", execution.get("executionArn")))
.then().statusCode(200);
}
}
}
request(account, "DeleteStateMachine", Map.of("stateMachineArn", arn)).then().statusCode(200);
}
}