mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(stepfunctions): run a task's calls in the account of its credentials role (#9569)
This commit is contained in:
1 parent
2536bc1052
commit
e55988e705
11 files changed
+514
-90
No files matched your search
@@ -77,24 +77,38 @@ return `InvalidToken` before IAM resource evaluation. Resource lookup
|
||||
does not consume the token. The caller must own the token before its resource
|
||||
is used for IAM evaluation, including for recent completed tokens.
|
||||
|
||||
## Nested task credentials
|
||||
## Task credentials
|
||||
|
||||
A Lambda or AWS service task whose `Credentials` name a role makes its calls as that role, in the
|
||||
role's account: a function, queue, table or other resource the task names without its account is the
|
||||
one of the role's account, and one named by an ARN or URL stays the one it names. Activities take no
|
||||
`Credentials`, and an HTTP task (`http:invoke`), for which AWS does not say, keeps the state machine's
|
||||
account. An `apigateway:invoke` task keeps it too: it reaches only an API of the state machine's account,
|
||||
signed as the `Credentials` role. An `events:putEvents` entry whose `EventBusName` is the ARN of a bus of the
|
||||
state machine's account reaches that bus.
|
||||
Where a section below says a task reaches a resource in the state machine's account, a task with a
|
||||
`Credentials` role reaches it in the role's account. Parent history, subsequent states and
|
||||
cancellation checks keep the state machine's account.
|
||||
|
||||
JSONPath `RoleArn.$` resolves against the state input after `InputPath` and before `Parameters`.
|
||||
The role must exist with its exact ARN in the execution's partition, with IAM enforcement off as well:
|
||||
a missing or mismatched role fails the task with `States.TaskFailed`, and `Credentials` that do not
|
||||
resolve to an object holding only `RoleArn` fail with `States.Runtime`.
|
||||
|
||||
With IAM enforcement on, the execution role has to be able to assume a role in another account
|
||||
before the call: one it cannot assume fails the task with `States.TaskFailed`, or `States.Permissions`
|
||||
for a Lambda task, the errors their own checks give. Within one account, each integration's check
|
||||
decides ([Lambda](#lambda-tasks-under-iam-enforcement), [messaging](#messaging-tasks-under-iam-enforcement),
|
||||
[data](#data-tasks-under-iam-enforcement), [jobs](#job-tasks-under-iam-enforcement),
|
||||
[control](#control-tasks-under-iam-enforcement)), evaluating the resources in the role's account.
|
||||
|
||||
Nested `states:startExecution` tasks, including `.sync` and `.sync:2`, and the SDK
|
||||
`sfn:startExecution` and `sfn:startSyncExecution` integrations accept `Credentials.RoleArn`.
|
||||
JSONPath `RoleArn.$` resolves against the state input after `InputPath` and before
|
||||
`Parameters`. The role must exist with its exact ARN in the execution's partition.
|
||||
The child call and polling use that role's account; parent history, subsequent states,
|
||||
and cancellation checks retain the parent's account.
|
||||
|
||||
With IAM enforcement enabled, the existing task authorizer checks the execution role's
|
||||
permission to assume the task role, its trust policy, and the task role's permission to
|
||||
start the child. Account routing also works with enforcement disabled. The `.sync`
|
||||
polling and cancellation paths retain the task account; their additional IAM permissions
|
||||
are not evaluated. Every other integration evaluates `Credentials` itself
|
||||
([Lambda](#lambda-tasks-under-iam-enforcement), [messaging](#messaging-tasks-under-iam-enforcement),
|
||||
[data](#data-tasks-under-iam-enforcement), [jobs](#job-tasks-under-iam-enforcement),
|
||||
[control](#control-tasks-under-iam-enforcement)), and so does a nested task in its `.waitForTaskToken`
|
||||
form, which this routing does not serve: it runs in the state machine's account.
|
||||
`sfn:startExecution` and `sfn:startSyncExecution` integrations check, with enforcement on, the
|
||||
execution role's permission to assume the task role, its trust policy, and the task role's permission
|
||||
to start the child, which has to be in the role's account. The child call and polling use that role's
|
||||
account. The `.sync` polling and cancellation paths retain the task account; their additional IAM
|
||||
permissions are not evaluated. A nested task in its `.waitForTaskToken` form runs in the role's
|
||||
account too, and is authorized as a [control task](#control-tasks-under-iam-enforcement).
|
||||
A foreign state-machine ARN without task credentials grants no account access.
|
||||
|
||||
A missing or mismatched task role fails with `States.TaskFailed`. A target account
|
||||
@@ -657,9 +671,8 @@ event buses:
|
||||
`Principal` account id, leaves the decision to that account's IAM policies. Across accounts both the
|
||||
role's policies and the bus policy have to allow the send.
|
||||
|
||||
A role in another account, named by `Credentials`, is authorized as that role but the task still
|
||||
runs in the state machine's account. Nested executions are the only tasks that run in the role's
|
||||
account. With enforcement off nothing here is evaluated.
|
||||
A role in another account, named by `Credentials`, is authorized as that role, and the task runs in
|
||||
its account ([task credentials](#task-credentials)). With enforcement off nothing here is evaluated.
|
||||
|
||||
Floci has no `aws-sdk:eventbridge:putEvents` integration: that resource fails with
|
||||
`States.TaskFailed` and "Unsupported resource" whether or not enforcement is on.
|
||||
@@ -835,7 +848,7 @@ trusting Step Functions, as a Lambda task does not. It only needs the action, wh
|
||||
exist does not have. `.sync` needs the starting call alone, not `states:DescribeExecution`, `states:StopExecution`
|
||||
or the EventBridge permissions the CDK grants for its wait. With `Credentials`, a nested task other than
|
||||
the `.waitForTaskToken` form keeps the checks and errors of
|
||||
[nested task credentials](#nested-task-credentials).
|
||||
[task credentials](#task-credentials).
|
||||
|
||||
Every integration that evaluates a role is refused on its `.waitForTaskToken` form the same way: the refused
|
||||
task starts nothing and waits for nothing. With the permission, it calls its service and then waits on its
|
||||
|
||||
@@ -987,11 +987,11 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
JsonNode effectiveInput;
|
||||
// Read Credentials for IAM checks and nested account routing.
|
||||
boolean nestedTask = NestedTaskCredentials.isNested(StatesIntegration.parse(resource).orElse(null));
|
||||
// Read Credentials for IAM checks and for the account a Lambda or service task's calls run in.
|
||||
boolean routedTask = NestedTaskCredentials.routes(resource);
|
||||
JsonNode credentials = null;
|
||||
boolean readCredentials = stateDef.has("Credentials")
|
||||
&& (iamEnforcementEnabled() || (mockedInvocation == null && nestedTask));
|
||||
&& (iamEnforcementEnabled() || (mockedInvocation == null && routedTask));
|
||||
// Otherwise only the scheduled event reads them, and what it cannot read it leaves out.
|
||||
boolean recordCredentialsOnly = stateDef.has("Credentials") && !readCredentials && !isActivity;
|
||||
JsonNode recordedCredentials = null;
|
||||
@@ -1040,7 +1040,7 @@ public class AslExecutor {
|
||||
addTaskStartedEvent(chain, profile);
|
||||
try {
|
||||
String taskAccount = null;
|
||||
if (mockedInvocation == null && credentials != null && nestedTask) {
|
||||
if (mockedInvocation == null && credentials != null && routedTask) {
|
||||
taskAccount = nestedTaskCredentials.account(credentials, resource, effectiveInput, sm);
|
||||
}
|
||||
if (mockedInvocation == null) {
|
||||
@@ -1048,13 +1048,14 @@ public class AslExecutor {
|
||||
}
|
||||
JsonNode resourceInput = effectiveInput;
|
||||
String resourceToken = taskToken;
|
||||
String resourceAccount = taskAccount;
|
||||
taskResult = mockedInvocation != null
|
||||
? mockedTaskResult(mockedInvocation.steps(), stateName, mockedInvocation.responseIndex())
|
||||
: RequestScopes.callAsChecked(taskAccount, () -> invokeResource(
|
||||
effectiveResource, resourceInput, sm, resourceToken,
|
||||
context.path("Execution").path("Id").asText(null),
|
||||
executionDeadlineNanos, taskDeadlineNanos,
|
||||
jsonata ? null : stateDef.path("Parameters"), taskCredentials,
|
||||
jsonata ? null : stateDef.path("Parameters"), taskCredentials, resourceAccount,
|
||||
jobResponse -> RequestScopes.runAs(
|
||||
AwsArnUtils.parse(sm.getStateMachineArn()).accountId(),
|
||||
() -> addTaskSubmittedEvent(chain, profile, jobResponse))));
|
||||
@@ -1268,18 +1269,19 @@ public class AslExecutor {
|
||||
|
||||
/** Integrations {@link TaskPermissions} does not map stay unchecked, Lambda and API Gateway check their own. */
|
||||
private void authorizeTask(StatesIntegration integration, JsonNode input, StateMachine sm, JsonNode credentials,
|
||||
String taskToken) {
|
||||
String taskToken, String taskAccount) {
|
||||
// NestedTaskCredentials has decided this one. Its callback form does not reach it, so it is decided here.
|
||||
if (credentials != null && taskToken == null && NestedTaskCredentials.isNested(integration)) {
|
||||
return;
|
||||
}
|
||||
Optional<TaskPermissions> required = TaskPermissions.of(integration, input, sm,
|
||||
Optional<TaskPermissions> required = TaskPermissions.of(integration, input,
|
||||
NestedTaskCredentials.inAccount(sm, taskAccount),
|
||||
redshiftDataHandler == null ? null : redshiftDataHandler.storedResourceArns(), ecsService,
|
||||
taskToken != null, new TaskPermissions.ControlServices(
|
||||
cloudFormationHandler == null ? null : cloudFormationHandler.storedResourceArns(),
|
||||
sdkManagementTaskInvoker == null ? null : sdkManagementTaskInvoker.secretsStoredResourceArns(),
|
||||
sfnService == null || !sfnService.isResolvable() ? null : sfnService.get(),
|
||||
schedulerService));
|
||||
schedulerService), AwsArnUtils.parse(sm.getStateMachineArn()).accountId());
|
||||
if (required.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
@@ -1306,7 +1308,7 @@ public class AslExecutor {
|
||||
&& config.services().iam().enforcementEnabled();
|
||||
}
|
||||
|
||||
/** {@code accountId} is null for the state machine's own account, the account the execution runs in. */
|
||||
/** {@code accountId} is null for the account the task's calls run in, the state machine's or its role's. */
|
||||
private LambdaFunction resolveLambdaFunction(String accountId, String region, String name, String qualifier) {
|
||||
try {
|
||||
return accountId == null
|
||||
@@ -1362,13 +1364,15 @@ public class AslExecutor {
|
||||
|
||||
/**
|
||||
* @param credentials the task's resolved {@code Credentials}, read only under IAM enforcement or
|
||||
* for a nested execution, or null when the task runs as the execution role
|
||||
* for a Lambda or service task, or null when the task runs as the execution role
|
||||
* @param taskAccount the account of the {@code Credentials} role the task's calls run in, or null for the
|
||||
* state machine's
|
||||
* @param jobSubmitted called with the response of the call that started a {@code .sync} job,
|
||||
* once it has returned and before the job is waited on
|
||||
*/
|
||||
private JsonNode invokeResource(String resource, JsonNode input, StateMachine sm, String taskToken,
|
||||
String executionArn, long executionDeadlineNanos, long taskDeadlineNanos,
|
||||
JsonNode rawParameters, JsonNode credentials,
|
||||
JsonNode rawParameters, JsonNode credentials, String taskAccount,
|
||||
Consumer<JsonNode> jobSubmitted) throws Exception {
|
||||
String credentialsRoleArn = credentials == null ? null : credentials.path("RoleArn").asText(null);
|
||||
// Support Lambda resources: direct ARN or optimized integration
|
||||
@@ -1414,8 +1418,9 @@ public class AslExecutor {
|
||||
+ stateMachineArn.region() + "'");
|
||||
}
|
||||
String region = ref.region() != null ? ref.region() : stateMachineArn.region();
|
||||
String accountId = ref.account() == null || ref.account().equals(stateMachineArn.accountId())
|
||||
? null : ref.account();
|
||||
// A function named without its account is the one of the account the task's calls run in.
|
||||
String callerAccount = taskAccount != null ? taskAccount : stateMachineArn.accountId();
|
||||
String accountId = ref.account() == null || ref.account().equals(callerAccount) ? null : ref.account();
|
||||
String invokedQualifier = ref.qualifier();
|
||||
// The task invokes the function as its role: the execution role, or the role its
|
||||
// Credentials name once the execution role has assumed it. The role's policies or the
|
||||
@@ -1431,7 +1436,7 @@ public class AslExecutor {
|
||||
invokingRoleArn = credentialsRoleArn;
|
||||
}
|
||||
String functionArn = LambdaArnUtils.functionArn(functionRef, stateMachineArn.partition(), region,
|
||||
stateMachineArn.accountId());
|
||||
callerAccount);
|
||||
if (invokedQualifier != null && extractLambdaQualifier(functionRef) == null) {
|
||||
functionArn += ":" + invokedQualifier;
|
||||
}
|
||||
@@ -1485,7 +1490,7 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
if (iamEnforcementEnabled()) {
|
||||
authorizeTask(integration, input, sm, credentials, taskToken);
|
||||
authorizeTask(integration, input, sm, credentials, taskToken, taskAccount);
|
||||
}
|
||||
|
||||
if (integration.is("apigateway", "invoke") && integration.suffix().isEmpty()) {
|
||||
@@ -1631,7 +1636,7 @@ public class AslExecutor {
|
||||
// EventBridge optimized integration
|
||||
if (integration.is("events", "putEvents")) {
|
||||
String region = regionResolver.regionOf(sm.getStateMachineArn());
|
||||
return invokeOptimizedPutEvents(input, region);
|
||||
return invokeOptimizedPutEvents(input, region, AwsArnUtils.parse(sm.getStateMachineArn()).accountId());
|
||||
}
|
||||
|
||||
// Nested state machine integration
|
||||
@@ -1991,16 +1996,57 @@ public class AslExecutor {
|
||||
* {@code EventBridge.FailedEntry}, carrying the response as the cause so the caller can see
|
||||
* which entry it was.
|
||||
*/
|
||||
private JsonNode invokeOptimizedPutEvents(JsonNode input, String region) throws Exception {
|
||||
private JsonNode invokeOptimizedPutEvents(JsonNode input, String region, String machineAccount) throws Exception {
|
||||
JsonNode request = normalizeOptimizedPutEventsInput(input);
|
||||
JsonNode entries = request.path("Entries");
|
||||
Map<String, List<Integer>> byAccount = new LinkedHashMap<>();
|
||||
if (entries.isArray()) {
|
||||
for (int i = 0; i < entries.size(); i++) {
|
||||
byAccount.computeIfAbsent(NestedTaskCredentials.putEventsAccount(entries.get(i), machineAccount),
|
||||
account -> new ArrayList<>()).add(i);
|
||||
}
|
||||
}
|
||||
if (byAccount.size() < 2) {
|
||||
String account = byAccount.isEmpty() ? null : byAccount.keySet().iterator().next();
|
||||
return putEventsResult(RequestScopes.callAsChecked(account, () -> putEvents(request, region)));
|
||||
}
|
||||
// Entries reaching buses of different accounts: each account's go there, answered in request order.
|
||||
ObjectNode result = objectMapper.createObjectNode();
|
||||
ArrayNode resultEntries = objectMapper.createArrayNode();
|
||||
JsonNode[] answered = new JsonNode[entries.size()];
|
||||
int failed = 0;
|
||||
for (Map.Entry<String, List<Integer>> group : byAccount.entrySet()) {
|
||||
ObjectNode part = ((ObjectNode) request).deepCopy();
|
||||
ArrayNode partEntries = part.putArray("Entries");
|
||||
group.getValue().forEach(index -> partEntries.add(entries.get(index)));
|
||||
JsonNode partResult = RequestScopes.callAsChecked(group.getKey(), () -> putEvents(part, region));
|
||||
failed += partResult.path("FailedEntryCount").asInt();
|
||||
for (int i = 0; i < group.getValue().size(); i++) {
|
||||
answered[group.getValue().get(i)] = partResult.path("Entries").path(i);
|
||||
}
|
||||
}
|
||||
for (JsonNode entry : answered) {
|
||||
resultEntries.add(entry);
|
||||
}
|
||||
result.put("FailedEntryCount", failed);
|
||||
result.set("Entries", resultEntries);
|
||||
return putEventsResult(result);
|
||||
}
|
||||
|
||||
private JsonNode putEvents(JsonNode request, String region) {
|
||||
Response response;
|
||||
try {
|
||||
response = eventBridgeHandler.handle("PutEvents", normalizeOptimizedPutEventsInput(input), region);
|
||||
response = eventBridgeHandler.handle("PutEvents", request, region);
|
||||
} catch (AwsException e) {
|
||||
throw new FailStateException(sdkExceptionName("EventBridge", e.getErrorCode()), e.getMessage());
|
||||
}
|
||||
if (!(response.getEntity() instanceof JsonNode result)) {
|
||||
throw new FailStateException("EventBridge.SdkClientException", "PutEvents returned no response body");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private JsonNode putEventsResult(JsonNode result) throws JsonProcessingException {
|
||||
if (result.path("FailedEntryCount").asInt() > 0) {
|
||||
throw new FailStateException("EventBridge.FailedEntry", objectMapper.writeValueAsString(result));
|
||||
}
|
||||
@@ -2911,9 +2957,13 @@ public class AslExecutor {
|
||||
request.put("Message", message.toString());
|
||||
}
|
||||
|
||||
// A topic or endpoint ARN names its account, whichever account the task's calls run in.
|
||||
String arn = request.path("TopicArn").isTextual() ? request.path("TopicArn").asText()
|
||||
: request.path("TargetArn").asText(null);
|
||||
String account = AwsArnUtils.isArnFor(arn, "sns") ? AwsArnUtils.parse(arn).accountId() : null;
|
||||
Response response;
|
||||
try {
|
||||
response = snsJsonHandler.handle("Publish", request, region);
|
||||
response = RequestScopes.callAsChecked(account, () -> snsJsonHandler.handle("Publish", request, region));
|
||||
} catch (AwsException e) {
|
||||
throw new FailStateException(errorPrefix + snsExceptionName(e.getErrorCode()), e.getMessage());
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -11,6 +11,14 @@ import jakarta.inject.Inject;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The account a task's calls run in when its {@code Credentials} name a role. The execution role assumes that role
|
||||
* "before invoking the specified Resource", which Task types using Lambda functions and supported AWS services allow
|
||||
* (Developer Guide, Task state), and the calls then reach "resources that the target account owns", the role being
|
||||
* in one partition with the state machine (Developer Guide, "Accessing cross-account AWS resources in Step
|
||||
* Functions"). Activities take no {@code Credentials}; HTTP tasks, for which AWS does not say, keep the state
|
||||
* machine's account. The class keeps its name from when only nested executions were routed.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class NestedTaskCredentials {
|
||||
private final IamService iam;
|
||||
@@ -24,11 +32,19 @@ public class NestedTaskCredentials {
|
||||
this.authorizer = authorizer;
|
||||
}
|
||||
|
||||
/**
|
||||
* The account of the role {@code credentials} name, checked as the role the task's calls are made as: it has to be
|
||||
* an IAM role of the execution's partition that exists. Under IAM enforcement the execution role has to be able to
|
||||
* assume it when it is in another account or the task is a nested execution, whose target has to be in the role's
|
||||
* account and allowed to it; another task's own authorization decides an assumption within one account.
|
||||
*
|
||||
* @param resource the state's {@code Resource}, which {@link #routes} accepts
|
||||
*/
|
||||
String account(JsonNode credentials, String resource, JsonNode input, StateMachine machine) {
|
||||
StatesIntegration integration = StatesIntegration.parse(resource).orElse(null);
|
||||
if (!isNested(integration)) {
|
||||
if (!routes(resource)) {
|
||||
throw new AslExecutor.FailStateException("States.Runtime",
|
||||
"Task Credentials account routing is supported only for nested executions");
|
||||
"Task Credentials account routing is supported only for Lambda and AWS service integrations");
|
||||
}
|
||||
validateShape(credentials);
|
||||
String roleArn = credentials.path("RoleArn").asText();
|
||||
@@ -49,24 +65,87 @@ public class NestedTaskCredentials {
|
||||
if (iam.findRole(role.accountId(), name).filter(found -> IamService.roleArnMatches(roleArn, found)).isEmpty()) {
|
||||
throw assumptionDenied(machine, roleArn);
|
||||
}
|
||||
if (config.services().iam().enforcementEnabled()) {
|
||||
if (authorizer.assumeRefusal(machine.getRoleArn(), roleArn, machine.getStateMachineArn()).isPresent()) {
|
||||
throw assumptionDenied(machine, roleArn);
|
||||
}
|
||||
validateTargetAccount(resource, input, machine, role.accountId());
|
||||
String target = input.path("StateMachineArn").asText(null);
|
||||
if (AwsArnUtils.isArn(target)) {
|
||||
String action = integration.isSdk("sfn", "startSyncExecution")
|
||||
? "states:StartSyncExecution" : "states:StartExecution";
|
||||
Optional<String> refusal = authorizer.refusal(roleArn, action, target);
|
||||
if (!config.services().iam().enforcementEnabled()) {
|
||||
return role.accountId();
|
||||
}
|
||||
if (!isNested(integration)) {
|
||||
if (!role.accountId().equals(owner.accountId())) {
|
||||
Optional<String> refusal = authorizer.assumeRefusal(machine.getRoleArn(), roleArn,
|
||||
machine.getStateMachineArn());
|
||||
if (refusal.isPresent()) {
|
||||
throw accessDenied(integration, refusal.get());
|
||||
// The Lambda task's own check refuses an assumption this way, so the error stays the same.
|
||||
throw isLambda(resource, integration)
|
||||
? new AslExecutor.FailStateException("States.Permissions", refusal.get())
|
||||
: assumptionDenied(machine, roleArn);
|
||||
}
|
||||
}
|
||||
return role.accountId();
|
||||
}
|
||||
if (authorizer.assumeRefusal(machine.getRoleArn(), roleArn, machine.getStateMachineArn()).isPresent()) {
|
||||
throw assumptionDenied(machine, roleArn);
|
||||
}
|
||||
validateTargetAccount(resource, input, machine, role.accountId());
|
||||
String target = input.path("StateMachineArn").asText(null);
|
||||
if (AwsArnUtils.isArn(target)) {
|
||||
String action = integration.isSdk("sfn", "startSyncExecution")
|
||||
? "states:StartSyncExecution" : "states:StartExecution";
|
||||
Optional<String> refusal = authorizer.refusal(roleArn, action, target);
|
||||
if (refusal.isPresent()) {
|
||||
throw accessDenied(integration, refusal.get());
|
||||
}
|
||||
}
|
||||
return role.accountId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a task with {@code resource} makes its calls as its {@code Credentials} role, in that role's account: a
|
||||
* Lambda function or an AWS service integration, in any of its forms. Not an activity, nor an HTTP task, nor an
|
||||
* API Gateway task, which reaches only an API of the state machine's account and signs as its role itself.
|
||||
*/
|
||||
static boolean routes(String resource) {
|
||||
StatesIntegration integration = StatesIntegration.parse(resource).orElse(null);
|
||||
if (integration == null) {
|
||||
return isLambdaFunctionArn(resource);
|
||||
}
|
||||
return !integration.isAnySuffix("http", "invoke") && !integration.isAnySuffix("apigateway", "invoke");
|
||||
}
|
||||
|
||||
/**
|
||||
* The state machine's account for a {@code PutEvents} entry whose {@code EventBusName} is the ARN of a bus of that
|
||||
* account, which it reaches even when a {@code Credentials} role's account is the one the task's calls run in;
|
||||
* null for any other entry, which goes to the bus of the account the calls run in. The task's permission check
|
||||
* and its delivery both read it, so they reach the same bus.
|
||||
*/
|
||||
static String putEventsAccount(JsonNode entry, String machineAccount) {
|
||||
String bus = entry.path("EventBusName").asText(null);
|
||||
return AwsArnUtils.isArnFor(bus, "events") && machineAccount.equals(AwsArnUtils.parse(bus).accountId())
|
||||
? machineAccount : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The machine as the account a task's calls run in sees it, so a resource the task names without its account is
|
||||
* the one of that account. The role and the rest stay the state machine's.
|
||||
*/
|
||||
static StateMachine inAccount(StateMachine machine, String account) {
|
||||
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
|
||||
if (account == null || account.equals(owner.accountId())) {
|
||||
return machine;
|
||||
}
|
||||
StateMachine view = new StateMachine();
|
||||
view.setStateMachineArn(new AwsArnUtils.Arn(owner.partition(), owner.service(), owner.region(), account,
|
||||
owner.resource()).toString());
|
||||
view.setRoleArn(machine.getRoleArn());
|
||||
return view;
|
||||
}
|
||||
|
||||
private static boolean isLambda(String resource, StatesIntegration integration) {
|
||||
return integration == null ? isLambdaFunctionArn(resource) : integration.isAnySuffix("lambda", "invoke");
|
||||
}
|
||||
|
||||
private static boolean isLambdaFunctionArn(String resource) {
|
||||
return AwsArnUtils.isArnFor(resource, "lambda") && resource.contains(":function:");
|
||||
}
|
||||
|
||||
static void validateShape(JsonNode credentials) {
|
||||
if (!credentials.isObject() || credentials.size() != 1 || !credentials.path("RoleArn").isTextual()) {
|
||||
throw new AslExecutor.FailStateException("States.Runtime",
|
||||
|
||||
@@ -150,6 +150,19 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|
||||
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
|
||||
StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback,
|
||||
ControlServices control) {
|
||||
return of(integration, input, machine, redshiftData, ecs, callback, control, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #of(StatesIntegration, JsonNode, StateMachine, StoredResourceArns, StoredResourceArns, boolean,
|
||||
* ControlServices)}, for a task whose calls run in the account of {@code machine}, which a {@code Credentials}
|
||||
* role may have moved from the state machine's own.
|
||||
*
|
||||
* @param machineAccount the state machine's own account, or null when {@code machine} is in it
|
||||
*/
|
||||
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine,
|
||||
StoredResourceArns redshiftData, StoredResourceArns ecs, boolean callback,
|
||||
ControlServices control, String machineAccount) {
|
||||
if (integration.isSdkService("scheduler") && SCHEDULER.contains(integration.api())) {
|
||||
return Optional.of(scheduler(integration.api(), input, machine, control.scheduler()));
|
||||
}
|
||||
@@ -204,7 +217,7 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|
||||
return Optional.of(snsPublish("Sns.", input));
|
||||
}
|
||||
if (integration.is("events", "putEvents")) {
|
||||
return Optional.of(eventsPutEvents(input, machine));
|
||||
return Optional.of(eventsPutEvents(input, machine, machineAccount));
|
||||
}
|
||||
if (integration.isOptimizedService("dynamodb") && DYNAMODB_OPTIMIZED.contains(integration.api())) {
|
||||
return Optional.of(dynamoDbOptimized(integration.api(), input, machine));
|
||||
@@ -258,17 +271,21 @@ record TaskPermissions(String deniedError, List<Permission> permissions, boolean
|
||||
/**
|
||||
* One permission for each distinct bus the entries reach, read as {@code PutEvents}' handler reads
|
||||
* the member: an entry naming none goes to the default bus. An entry that is not an object or whose
|
||||
* member is a malformed ARN reaches no bus, so EventBridge answers it.
|
||||
* member is a malformed ARN reaches no bus, so EventBridge answers it. The bus is the one of the account
|
||||
* the entry is sent in ({@link NestedTaskCredentials#putEventsAccount}), so the check and the delivery
|
||||
* reach the same bus.
|
||||
*/
|
||||
private static TaskPermissions eventsPutEvents(JsonNode input, StateMachine machine) {
|
||||
private static TaskPermissions eventsPutEvents(JsonNode input, StateMachine machine, String machineAccount) {
|
||||
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
|
||||
String ownAccount = machineAccount != null ? machineAccount : owner.accountId();
|
||||
Set<String> buses = new LinkedHashSet<>();
|
||||
JsonNode entries = input.path("Entries");
|
||||
if (entries.isArray()) {
|
||||
for (JsonNode entry : entries) {
|
||||
if (entry.isObject()) {
|
||||
String account = NestedTaskCredentials.putEventsAccount(entry, ownAccount);
|
||||
EventBridgeService.eventBusArn(entry.path("EventBusName").asText(null), owner.partition(),
|
||||
owner.region(), owner.accountId()).ifPresent(buses::add);
|
||||
owner.region(), account != null ? account : owner.accountId()).ifPresent(buses::add);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -306,7 +306,8 @@ final class AslExecutorFixture {
|
||||
schedulerService, schedulerController, rdsDataService, objectMapper,
|
||||
jsonataEvaluator != null ? jsonataEvaluator : new JsonataEvaluator(objectMapper),
|
||||
sfnService, config, vertx, customResourceLiveness, clock, sleeper, maxWaitSeconds,
|
||||
redshiftDataHandler, serviceRegistry, null, lambdaTaskAuthorizer, expressMaxExecutionTime,
|
||||
redshiftDataHandler, serviceRegistry, mock(NestedTaskCredentials.class), lambdaTaskAuthorizer,
|
||||
expressMaxExecutionTime,
|
||||
nanoTime, null, emrTaskInvoker, emrServerlessTaskInvoker, null, nestedWaiter,
|
||||
eventBridgeInvoker, null);
|
||||
}
|
||||
|
||||
@@ -4,18 +4,24 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.services.iam.IamService;
|
||||
import io.floci.aws.services.stepfunctions.model.StateMachine;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
class NestedTaskCredentialsTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"lambda:invoke", "states:startExecution.waitForTaskToken", "aws-sdk:sfn:sendTaskSuccess"})
|
||||
void unsupportedIntegrationFailsBeforeRoleLookup(String resource) {
|
||||
@ValueSource(strings = {"arn:aws:states:::http:invoke", "arn:aws:states:us-east-1:000000000111:activity:work",
|
||||
"arn:aws:sqs:us-east-1:000000000111:queue"})
|
||||
void aTaskThatIsNotALambdaOrServiceIntegrationFailsBeforeRoleLookup(String resource) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
IamService iam = mock(IamService.class);
|
||||
LambdaTaskAuthorizer authorizer = mock(LambdaTaskAuthorizer.class);
|
||||
@@ -23,7 +29,41 @@ class NestedTaskCredentialsTest {
|
||||
assertThrows(AslExecutor.FailStateException.class,
|
||||
() -> credentials.account(new ObjectMapper().createObjectNode().put(
|
||||
"RoleArn", "arn:aws:iam::000000000222:role/target"),
|
||||
"arn:aws:states:::" + resource, new ObjectMapper().createObjectNode(), new StateMachine()));
|
||||
resource, new ObjectMapper().createObjectNode(), new StateMachine()));
|
||||
verifyNoInteractions(iam, authorizer);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"arn:aws:states:::lambda:invoke", "arn:aws:lambda:us-east-1:000000000111:function:f",
|
||||
"arn:aws:states:::sqs:sendMessage.waitForTaskToken", "arn:aws:states:::aws-sdk:sfn:sendTaskSuccess",
|
||||
"arn:aws:states:::states:startExecution.sync:2", "arn:aws-cn:states:::dynamodb:putItem"})
|
||||
void lambdaAndServiceTasksRunInTheirRolesAccount(String resource) {
|
||||
assertTrue(NestedTaskCredentials.routes(resource));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anActivityAndAnHttpTaskKeepTheMachinesAccount() {
|
||||
assertFalse(NestedTaskCredentials.routes("arn:aws:states:us-east-1:000000000111:activity:work"));
|
||||
assertFalse(NestedTaskCredentials.routes("arn:aws:states:::http:invoke"));
|
||||
}
|
||||
|
||||
/** An API Gateway task reaches only an API of the state machine's account, whose lookup stays there. */
|
||||
@Test
|
||||
void anApiGatewayTaskKeepsTheMachinesAccount() {
|
||||
assertFalse(NestedTaskCredentials.routes("arn:aws:states:::apigateway:invoke"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theMachineInAnotherAccountKeepsItsNameRegionAndRole() {
|
||||
StateMachine machine = new StateMachine();
|
||||
machine.setStateMachineArn("arn:aws:states:eu-west-1:000000000111:stateMachine:m");
|
||||
machine.setRoleArn("arn:aws:iam::000000000111:role/execution");
|
||||
|
||||
StateMachine view = NestedTaskCredentials.inAccount(machine, "000000000222");
|
||||
|
||||
assertEquals("arn:aws:states:eu-west-1:000000000222:stateMachine:m", view.getStateMachineArn());
|
||||
assertEquals(machine.getRoleArn(), view.getRoleArn());
|
||||
assertSame(machine, NestedTaskCredentials.inAccount(machine, null));
|
||||
assertSame(machine, NestedTaskCredentials.inAccount(machine, "000000000111"));
|
||||
}
|
||||
}
|
||||
+23
@@ -211,6 +211,29 @@ class StepFunctionsLambdaTaskAuthorizationIntegrationTest {
|
||||
verify(executor).invoke(argThat(isFunction(functionArn)), any(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
* The call runs in the Credentials role's account, so a function named without its ARN is the one of that account,
|
||||
* which the role's own permission is enough to invoke; the same-named function of the state machine's is not called.
|
||||
*/
|
||||
@Test
|
||||
void aForeignCredentialsRoleInvokesTheSameNamedFunctionOfItsOwnAccount() {
|
||||
String executionRoleArn = createRole("sfn-exec-" + suffix(), ASSUME_ANY_ROLE);
|
||||
String taskRoleArn = createRole(FUNCTION_ACCOUNT, "LambdaRole-" + suffix(), "/", trusting(executionRoleArn),
|
||||
INVOKE_ANYTHING);
|
||||
String name = "worker-" + suffix();
|
||||
String own = createFunction(SFN_ACCOUNT, name);
|
||||
String foreign = createFunction(FUNCTION_ACCOUNT, name);
|
||||
|
||||
run(executionRoleArn, "cross-account-" + suffix(), """
|
||||
{"StartAt":"Call","States":{"Call":{"Type":"Task","Resource":"arn:aws:states:::lambda:invoke",
|
||||
"Parameters":{"FunctionName":"%s"},"Credentials":{"RoleArn":"%s"},"End":true}}}"""
|
||||
.formatted(name, taskRoleArn), "{}")
|
||||
.body("status", equalTo("SUCCEEDED"));
|
||||
|
||||
verify(executor).invoke(argThat(isFunction(foreign)), any(), any());
|
||||
verify(executor, never()).invoke(argThat(isFunction(own)), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inItsOwnAccountATaskWithCredentialsNeedsOnlyThatRoleToInvoke() {
|
||||
String executionRoleArn = createRole("sfn-exec-" + suffix(), ASSUME_ANY_ROLE);
|
||||
|
||||
+86
-18
@@ -427,26 +427,84 @@ class StepFunctionsMessagingTaskIamIntegrationTest {
|
||||
assertNothingDelivered(target);
|
||||
}
|
||||
|
||||
/** Another account's role needs the bus's grant as well as its own, which {@code PutPermission} gives. */
|
||||
/**
|
||||
* A bus named by its name is the one of the account the task's calls run in, a foreign Credentials role's own
|
||||
* (Developer Guide, "Accessing cross-account AWS resources in Step Functions"), where the role's identity policy
|
||||
* is enough: the same-named bus of the state machine's account receives nothing.
|
||||
*/
|
||||
@Test
|
||||
void aForeignCredentialsRoleNeedsTheBusPolicyToo() throws Exception {
|
||||
void aForeignCredentialsRoleSendsToTheSameNamedBusOfItsOwnAccount() throws Exception {
|
||||
Target target = target("events:putEvents");
|
||||
String name = busName(target.resourceArn());
|
||||
events(OTHER_ACCOUNT, "CreateEventBus", Map.of("Name", name));
|
||||
cleanup.register(() -> events(OTHER_ACCOUNT, "DeleteEventBus", Map.of("Name", name)));
|
||||
SqsTestQueue foreignSink = eventSink(OTHER_ACCOUNT, name, target.source());
|
||||
String executionRole = role(STATES_TRUST, ASSUME);
|
||||
String foreignRole = sfn().role(OTHER_ACCOUNT, "sfn-msg-", trusting(executionRole), PUBLISH_ANY);
|
||||
String machine = machine(jsonPathTask(target, foreignRole), executionRole);
|
||||
|
||||
Response refused = terminal(start(machine, "{}"));
|
||||
Response completed = terminal(start(machine(jsonPathTask(target, foreignRole), executionRole), "{}"));
|
||||
|
||||
assertFailed(refused, "EventBridge.AccessDeniedException");
|
||||
String cause = refused.jsonPath().getString("cause");
|
||||
assertTrue(cause.contains("arn:aws:sts::" + OTHER_ACCOUNT + ":assumed-role/"), cause);
|
||||
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
|
||||
JsonNode delivered = foreignSink.awaitJson(Duration.ofSeconds(5));
|
||||
assertTrue(delivered.toString().contains("hello"), delivered.toString());
|
||||
assertNothingDelivered(target);
|
||||
}
|
||||
|
||||
/**
|
||||
* A bus named by its ARN is the one the ARN names, whichever account the task's calls run in: a foreign
|
||||
* Credentials role allowed to send to the state machine's bus reaches that bus, not a same-named one of its own.
|
||||
*/
|
||||
@Test
|
||||
void aForeignCredentialsRoleSendsToTheBusItsArnNames() throws Exception {
|
||||
Target target = target("events:putEvents");
|
||||
String name = busName(target.resourceArn());
|
||||
events(OTHER_ACCOUNT, "CreateEventBus", Map.of("Name", name));
|
||||
cleanup.register(() -> events(OTHER_ACCOUNT, "DeleteEventBus", Map.of("Name", name)));
|
||||
SqsTestQueue foreignSink = eventSink(OTHER_ACCOUNT, name, target.source());
|
||||
String executionRole = role(STATES_TRUST, ASSUME);
|
||||
String foreignRole = sfn().role(OTHER_ACCOUNT, "sfn-msg-", trusting(executionRole), PUBLISH_ANY);
|
||||
events("PutPermission", Map.of("EventBusName", name, "StatementId", "s",
|
||||
"Action", "events:PutEvents", "Principal", OTHER_ACCOUNT));
|
||||
Map<String, Object> byArn = new LinkedHashMap<>(entry(target.resourceArn(), target.source()));
|
||||
Map<String, Object> task = new LinkedHashMap<>(jsonPathTask(target, foreignRole));
|
||||
task.put("Parameters", Map.of("Entries", List.of(byArn)));
|
||||
|
||||
Response completed = terminal(start(machine(task, executionRole), "{}"));
|
||||
|
||||
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
|
||||
assertDelivered(target);
|
||||
assertEquals(0, foreignSink.receive().size());
|
||||
}
|
||||
|
||||
/**
|
||||
* The bus an ARN entry is checked on is the bus it is sent to: a foreign role allowed only on the state machine's
|
||||
* bus sends to it by its ARN, and one allowed only on its own same-named bus is refused the state machine's.
|
||||
*/
|
||||
@Test
|
||||
void aBusArnIsCheckedOnTheBusItReaches() throws Exception {
|
||||
Target target = target("events:putEvents");
|
||||
String name = busName(target.resourceArn());
|
||||
events(OTHER_ACCOUNT, "CreateEventBus", Map.of("Name", name));
|
||||
cleanup.register(() -> events(OTHER_ACCOUNT, "DeleteEventBus", Map.of("Name", name)));
|
||||
String foreignBus = "arn:aws:events:" + REGION + ":" + OTHER_ACCOUNT + ":event-bus/" + name;
|
||||
events("PutPermission", Map.of("EventBusName", name, "StatementId", "s",
|
||||
"Action", "events:PutEvents", "Principal", OTHER_ACCOUNT));
|
||||
String executionRole = role(STATES_TRUST, ASSUME);
|
||||
String allowedHere = sfn().role(OTHER_ACCOUNT, "sfn-msg-", trusting(executionRole),
|
||||
allow(target.resourceArn(), "events:PutEvents"));
|
||||
String allowedOnItsOwn = sfn().role(OTHER_ACCOUNT, "sfn-msg-", trusting(executionRole),
|
||||
allow(foreignBus, "events:PutEvents"));
|
||||
Map<String, Object> byArn = new LinkedHashMap<>(entry(target.resourceArn(), target.source()));
|
||||
|
||||
Map<String, Object> refusedTask = new LinkedHashMap<>(jsonPathTask(target, allowedOnItsOwn));
|
||||
refusedTask.put("Parameters", Map.of("Entries", List.of(byArn)));
|
||||
assertFailed(terminal(start(machine(refusedTask, executionRole), "{}")), "EventBridge.AccessDeniedException");
|
||||
assertNothingDelivered(target);
|
||||
|
||||
events("PutPermission", Map.of("EventBusName", busName(target.resourceArn()), "StatementId", "s",
|
||||
"Action", "events:PutEvents", "Principal", OTHER_ACCOUNT));
|
||||
Response allowed = terminal(start(machine, "{}"));
|
||||
|
||||
assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString());
|
||||
Map<String, Object> allowedTask = new LinkedHashMap<>(jsonPathTask(target, allowedHere));
|
||||
allowedTask.put("Parameters", Map.of("Entries", List.of(byArn)));
|
||||
Response completed = terminal(start(machine(allowedTask, executionRole), "{}"));
|
||||
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
|
||||
assertDelivered(target);
|
||||
}
|
||||
|
||||
@@ -672,19 +730,29 @@ class StepFunctionsMessagingTaskIamIntegrationTest {
|
||||
|
||||
/** A queue receiving the events of {@code source} on {@code bus}, through a rule removed with it. */
|
||||
private SqsTestQueue eventSink(String bus, String source) {
|
||||
SqsTestQueue sink = queue();
|
||||
return eventSink(ACCOUNT, bus, source);
|
||||
}
|
||||
|
||||
/** As {@link #eventSink(String, String)}, for a bus, rule and queue of {@code account}. */
|
||||
private SqsTestQueue eventSink(String account, String bus, String source) {
|
||||
SqsTestQueue sink = sfn().queue(sqsService, account, REGION, "sfn-msg-iam-");
|
||||
String rule = "sfn-iam-" + UUID.randomUUID();
|
||||
events("PutRule", Map.of("Name", rule, "EventBusName", bus,
|
||||
events(account, "PutRule", Map.of("Name", rule, "EventBusName", bus,
|
||||
"EventPattern", "{\"source\":[\"" + source + "\"]}"));
|
||||
cleanup.register(() -> events("DeleteRule", Map.of("Name", rule, "EventBusName", bus)));
|
||||
events("PutTargets", Map.of("Rule", rule, "EventBusName", bus,
|
||||
cleanup.register(() -> events(account, "DeleteRule", Map.of("Name", rule, "EventBusName", bus)));
|
||||
events(account, "PutTargets", Map.of("Rule", rule, "EventBusName", bus,
|
||||
"Targets", List.of(Map.of("Id", "1", "Arn", sink.arn()))));
|
||||
cleanup.register(() -> events("RemoveTargets", Map.of("Rule", rule, "EventBusName", bus, "Ids", List.of("1"))));
|
||||
cleanup.register(() -> events(account, "RemoveTargets", Map.of("Rule", rule, "EventBusName", bus,
|
||||
"Ids", List.of("1"))));
|
||||
return sink;
|
||||
}
|
||||
|
||||
private Response events(String action, Map<String, ?> input) {
|
||||
Response response = given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "events"))
|
||||
return events(ACCOUNT, action, input);
|
||||
}
|
||||
|
||||
private Response events(String account, String action, Map<String, ?> input) {
|
||||
Response response = given().port(baseUri.getPort()).header("Authorization", auth(account, "events"))
|
||||
.header("X-Amz-Target", "AWSEvents." + action)
|
||||
.contentType("application/x-amz-json-1.1").body(MAPPER.valueToTree(input).toString()).post("/");
|
||||
response.then().statusCode(200);
|
||||
|
||||
+52
@@ -198,6 +198,46 @@ class StepFunctionsSqsTaskIamIntegrationTest {
|
||||
assertEquals("hello", queue.receive().getFirst().getBody());
|
||||
}
|
||||
|
||||
/**
|
||||
* The call runs in the Credentials role's account (Developer Guide, "Accessing cross-account AWS resources in Step
|
||||
* Functions"), so a queue named without its URL is the one of that account, which its own policy lets it send to.
|
||||
*/
|
||||
@Test
|
||||
void aForeignCredentialsRoleSendsToTheSameNamedQueueOfItsOwnAccount() throws Exception {
|
||||
String name = "sfn-sqs-iam-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
SqsTestQueue own = namedQueue(ACCOUNT, name);
|
||||
SqsTestQueue foreign = namedQueue(OTHER_ACCOUNT, name);
|
||||
String executionRole = role(STATES_TRUST, ASSUME);
|
||||
String foreignRole = sfn().role(OTHER_ACCOUNT, "sfn-sqs-", trusting(executionRole), allow(foreign.arn(),
|
||||
"sqs:SendMessage"));
|
||||
String machine = machine(namedQueueTask(name, foreignRole), executionRole);
|
||||
|
||||
Response completed = terminal(start(machine, "{}"));
|
||||
|
||||
assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString());
|
||||
assertEquals("hello", foreign.receive().getFirst().getBody());
|
||||
assertEquals(0, own.receive().size());
|
||||
}
|
||||
|
||||
/** The target role's trust has to name the state machine's side; one that trusts only Lambda reaches neither queue. */
|
||||
@Test
|
||||
void aForeignCredentialsRoleWhoseTrustDoesNotNameTheMachineIsRefused() throws Exception {
|
||||
String name = "sfn-sqs-iam-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
SqsTestQueue own = namedQueue(ACCOUNT, name);
|
||||
SqsTestQueue foreign = namedQueue(OTHER_ACCOUNT, name);
|
||||
String executionRole = role(STATES_TRUST, ASSUME);
|
||||
String foreignRole = sfn().role(OTHER_ACCOUNT, "sfn-sqs-", LAMBDA_TRUST, SEND);
|
||||
String machine = machine(namedQueueTask(name, foreignRole), executionRole);
|
||||
|
||||
Response completed = terminal(start(machine, "{}"));
|
||||
|
||||
assertFailed(completed, "States.TaskFailed");
|
||||
assertEquals("The role " + executionRole + " is not authorized to assume the task state's role, "
|
||||
+ foreignRole + ".", completed.jsonPath().getString("cause"));
|
||||
assertEquals(0, foreign.receive().size());
|
||||
assertEquals(0, own.receive().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aQueueInAnotherAccountNeedsItsOwnGrant() throws Exception {
|
||||
SqsTestQueue queue = sfn().queue(sqsService, OTHER_ACCOUNT, REGION, "sfn-sqs-iam-");
|
||||
@@ -387,6 +427,18 @@ class StepFunctionsSqsTaskIamIntegrationTest {
|
||||
};
|
||||
}
|
||||
|
||||
private SqsTestQueue namedQueue(String account, String name) {
|
||||
SqsTestQueue queue = SqsTestQueue.named(sqsService, account, REGION, name);
|
||||
cleanup.register(queue::delete);
|
||||
return queue;
|
||||
}
|
||||
|
||||
private static Map<String, Object> namedQueueTask(String name, String taskRole) {
|
||||
return new LinkedHashMap<>(Map.of("Type", "Task", "Resource", "arn:aws:states:::sqs:sendMessage",
|
||||
"Credentials", Map.of("RoleArn", taskRole),
|
||||
"Parameters", Map.of("QueueUrl", name, "MessageBody", "hello"), "End", true));
|
||||
}
|
||||
|
||||
private SqsTestQueue queue() {
|
||||
return sfn().queue(sqsService, ACCOUNT, REGION, "sfn-sqs-iam-");
|
||||
}
|
||||
|
||||
+84
-11
@@ -40,6 +40,7 @@ import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.clearInvocations;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
@@ -48,6 +49,7 @@ import static org.mockito.Mockito.when;
|
||||
class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
private static final String SOURCE = "000000000331";
|
||||
private static final String TARGET = "000000000332";
|
||||
private static final String FOREIGN = "222222222222";
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String PASS = """
|
||||
{"StartAt":"Done","States":{"Done":{"Type":"Pass","End":true}}}
|
||||
@@ -242,13 +244,13 @@ 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. */
|
||||
/** The execution role does not exist, and the Credentials role trusts and allows nothing: 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 taskRole = inertRole();
|
||||
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),
|
||||
@@ -262,7 +264,7 @@ class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
assertEquals(taskRole, taskScheduled(execution).path("taskCredentials").path("roleArn").asText());
|
||||
}
|
||||
|
||||
/** Nothing evaluates a role that does not exist, nor a publisher no policy allows. */
|
||||
/** Nothing evaluates a role that trusts nothing, nor a publisher no policy allows. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"})
|
||||
void messagingCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception {
|
||||
@@ -270,7 +272,7 @@ class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
? Map.of("TopicArn", EnforcementFixtures.createTopic(cleanup, baseUri.getPort(), auth(SOURCE, "sns"),
|
||||
"credentials-" + UUID.randomUUID()), "Message", "hello")
|
||||
: Map.of("Entries", List.of(Map.of("Source", "credentials", "DetailType", "t", "Detail", "{}")));
|
||||
String taskRole = "arn:aws:iam::" + TARGET + ":role/no-such-role";
|
||||
String taskRole = inertRole();
|
||||
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", arguments, "End", true))));
|
||||
@@ -282,7 +284,7 @@ class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
assertEquals(taskRole, taskScheduled(execution).path("taskCredentials").path("roleArn").asText());
|
||||
}
|
||||
|
||||
/** Nothing evaluates a role that does not exist, nor a writer no policy allows. */
|
||||
/** Nothing evaluates a role that trusts nothing, nor a writer no policy allows. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"dynamodb:putItem", "aws-sdk:dynamodb:putItem", "s3:putObject", "aws-sdk:s3:putObject"})
|
||||
void dataCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception {
|
||||
@@ -359,7 +361,7 @@ class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
|
||||
private void assertDataTaskIsNotEvaluated(String integration, Map<String, Object> arguments, String status)
|
||||
throws Exception {
|
||||
String taskRole = "arn:aws:iam::" + TARGET + ":role/no-such-role";
|
||||
String taskRole = inertRole();
|
||||
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", arguments, "End", true))));
|
||||
@@ -378,8 +380,9 @@ class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/** Read for the account the call runs in, as a nested task's are, so a path that does not resolve fails the task. */
|
||||
@Test
|
||||
void credentialsThatDoNotResolveStillPassWithEnforcementOff() throws Exception {
|
||||
void credentialsThatDoNotResolveFailTheTaskWithEnforcementOff() 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(
|
||||
@@ -387,11 +390,56 @@ class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
"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);
|
||||
Response done = terminal(SOURCE, start(machine(SOURCE, definition, "STANDARD"), "{}"));
|
||||
|
||||
assertEquals("FAILED", done.jsonPath().getString("status"), done.asString());
|
||||
assertEquals("States.Runtime", done.jsonPath().getString("error"), done.asString());
|
||||
assertTrue(queue.receive().isEmpty(), done.asString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The Credentials role is the one the execution role assumes to make the call, so the call reaches what the role's
|
||||
* account owns (Developer Guide, "Accessing cross-account AWS resources in Step Functions"): a function named
|
||||
* without its ARN is the one of the role's account, not the same-named one of the state machine's.
|
||||
*/
|
||||
@Test
|
||||
void aLambdaTaskWithAForeignRoleInvokesTheFunctionOfTheRolesAccount() throws Exception {
|
||||
String name = "credentials-worker-" + UUID.randomUUID();
|
||||
String own = function(SOURCE, name);
|
||||
String foreign = function(FOREIGN, name);
|
||||
when(lambdaExecutor.invoke(any(), any(), any())).thenReturn(
|
||||
new InvokeResult(200, null, "{\"ok\":true}".getBytes(StandardCharsets.UTF_8), null, "req"));
|
||||
String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Call", "States", Map.of("Call", Map.of(
|
||||
"Type", "Task", "Resource", "arn:aws:states:::lambda:invoke",
|
||||
"Credentials", Map.of("RoleArn", role(FOREIGN)),
|
||||
"Parameters", Map.of("FunctionName", name), "End", true))));
|
||||
|
||||
Response done = terminal(SOURCE, start(machine(SOURCE, definition, "STANDARD"), "{}"));
|
||||
|
||||
assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());
|
||||
assertTrue(taskScheduled(execution).path("taskCredentials").isMissingNode(), done.asString());
|
||||
verify(lambdaExecutor).invoke(argThat(fn -> fn != null && foreign.equals(fn.getFunctionArn())), any(), any());
|
||||
verify(lambdaExecutor, never()).invoke(argThat(fn -> fn != null && own.equals(fn.getFunctionArn())), any(), any());
|
||||
}
|
||||
|
||||
/** As for a function: a queue named without its URL is the one of the role's account. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"sqs:sendMessage", "aws-sdk:sqs:sendMessage"})
|
||||
void anSqsTaskWithAForeignRoleSendsToTheQueueOfTheRolesAccount(String integration) throws Exception {
|
||||
String name = "credentials-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
SqsTestQueue own = SqsTestQueue.named(sqsService, SOURCE, "us-east-1", name);
|
||||
cleanup.register(own::delete);
|
||||
SqsTestQueue foreign = SqsTestQueue.named(sqsService, FOREIGN, "us-east-1", name);
|
||||
cleanup.register(foreign::delete);
|
||||
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", role(FOREIGN)),
|
||||
"Parameters", Map.of("QueueUrl", name, "MessageBody", "hello"), "End", true))));
|
||||
|
||||
Response done = terminal(SOURCE, start(machine(SOURCE, definition, "STANDARD"), "{}"));
|
||||
|
||||
assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString());
|
||||
assertEquals("hello", foreign.receive().getFirst().getBody());
|
||||
assertTrue(own.receive().isEmpty());
|
||||
}
|
||||
|
||||
private JsonNode taskScheduled(String execution) throws Exception {
|
||||
@@ -466,8 +514,12 @@ class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
}
|
||||
|
||||
private String role() {
|
||||
return role(TARGET);
|
||||
}
|
||||
|
||||
private String role(String account) {
|
||||
String name = "nested-" + UUID.randomUUID();
|
||||
return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), TARGET, "/", name, """
|
||||
return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), account, "/", name, """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:root"}}]}
|
||||
""".formatted(SOURCE), """
|
||||
@@ -476,6 +528,27 @@ class StepFunctionsTaskCredentialsIntegrationTest {
|
||||
""");
|
||||
}
|
||||
|
||||
/** A role of the state machine's account that trusts nothing and is allowed nothing, which enforcement refuses. */
|
||||
private String inertRole() {
|
||||
return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), SOURCE, "/", "inert-" + UUID.randomUUID(), """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
|
||||
"Principal":{"Service":"lambda.amazonaws.com"}}]}
|
||||
""", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"*","Resource":"*"}]}
|
||||
""");
|
||||
}
|
||||
|
||||
private String function(String account, String name) {
|
||||
cleanup.register(() -> given().port(baseUri.getPort()).header("Authorization", auth(account, "lambda"))
|
||||
.delete("/2015-03-31/functions/{name}", name).then().statusCode(204));
|
||||
given().port(baseUri.getPort()).header("Authorization", auth(account, "lambda"))
|
||||
.contentType("application/json").body(Map.of(
|
||||
"FunctionName", name, "Runtime", "nodejs20.x", "Handler", "index.handler",
|
||||
"Role", "arn:aws:iam::" + account + ":role/lambda-role"))
|
||||
.post("/2015-03-31/functions").then().statusCode(201);
|
||||
return "arn:aws:lambda:us-east-1:" + account + ":function:" + name;
|
||||
}
|
||||
|
||||
private String machine(String account, String definition, String type) throws Exception {
|
||||
return sfn().createMachine(account, "credentials-", definition, type,
|
||||
"arn:aws:iam::" + account + ":role/execution");
|
||||
|
||||
@@ -39,7 +39,11 @@ public final class SqsTestQueue {
|
||||
|
||||
/** Creates a queue named {@code namePrefix} plus a random suffix. */
|
||||
public static SqsTestQueue create(SqsService sqsService, String account, String region, String namePrefix) {
|
||||
String name = namePrefix + UUID.randomUUID().toString().substring(0, 8);
|
||||
return named(sqsService, account, region, namePrefix + UUID.randomUUID().toString().substring(0, 8));
|
||||
}
|
||||
|
||||
/** Creates a queue named {@code name}, so two accounts can each hold one of the same name. */
|
||||
public static SqsTestQueue named(SqsService sqsService, String account, String region, String name) {
|
||||
String url = RequestScopes.callAs(account, () -> sqsService.createQueue(name, Map.of(), region).getQueueUrl());
|
||||
return new SqsTestQueue(sqsService, account, region, url);
|
||||
}
|
||||
@@ -48,6 +52,10 @@ public final class SqsTestQueue {
|
||||
return url;
|
||||
}
|
||||
|
||||
public String name() {
|
||||
return url.substring(url.lastIndexOf('/') + 1);
|
||||
}
|
||||
|
||||
public String arn() {
|
||||
return RequestScopes.callAs(account, () ->
|
||||
sqsService.getQueueAttributes(url, List.of("QueueArn"), region).get("QueueArn"));
|
||||
|
||||
Reference in new issue
Block a user