mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -05:00
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:
1 parent
4b09c3cf2b
commit
bd65477927
21 files changed
+1489
-108
No files matched your search
@@ -22,6 +22,7 @@ import io.github.hectorvent.floci.services.lambda.durable.DurableTokens;
|
||||
import io.github.hectorvent.floci.services.lambdamicrovms.LambdaMicrovmsService;
|
||||
import io.github.hectorvent.floci.services.s3.S3ControlArnUtils;
|
||||
import io.github.hectorvent.floci.services.secretsmanager.SecretsManagerService;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
@@ -1550,8 +1551,7 @@ public class ResourceArnBuilder {
|
||||
}
|
||||
}
|
||||
if (queueUrl != null && !queueUrl.isEmpty()) {
|
||||
String queueName = queueUrl.substring(queueUrl.lastIndexOf('/') + 1);
|
||||
return AwsArnUtils.Arn.of("sqs", region, accountId, queueName).toString();
|
||||
return SqsService.queueArn(queueUrl, AwsRegions.partitionFor(region), region, accountId);
|
||||
}
|
||||
return AwsArnUtils.Arn.of("sqs", region, accountId, "*").toString();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.github.hectorvent.floci.services.sqs;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Supplies SQS queue policies to IAM policy evaluation, together with the account that owns the
|
||||
* queue: the one in its ARN, also when the queue does not exist or has no policy, so a call to
|
||||
* another account's queue is judged as cross-account.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SqsResourcePolicyProvider implements ResourcePolicyProvider {
|
||||
|
||||
private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
|
||||
|
||||
private final SqsService sqsService;
|
||||
|
||||
@Inject
|
||||
public SqsResourcePolicyProvider(SqsService sqsService) {
|
||||
this.sqsService = sqsService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
|
||||
if (!AwsArnUtils.isArnFor(resourceArn, "sqs")) {
|
||||
return List.of();
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
|
||||
// ListQueues and a request with no QueueUrl name every queue, which is not one queue's call.
|
||||
if (!ACCOUNT_ID.matcher(arn.accountId()).matches() || arn.region().isBlank()
|
||||
|| arn.resource().isBlank() || arn.resource().contains("*")) {
|
||||
return List.of();
|
||||
}
|
||||
return List.of(new ResourcePolicy(sqsService.findQueuePolicy(resourceArn).orElse(null), arn.accountId()));
|
||||
}
|
||||
}
|
||||
@@ -2241,6 +2241,31 @@ public class SqsService implements Resettable, ResourceProvider {
|
||||
return baseUrl + "/" + regionResolver.getAccountId() + "/" + queueUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ARN of the queue {@code queueUrl} reaches from {@code region}, read as the lookups read it:
|
||||
* the path names the account and the queue, the host does not count, and a value that names no
|
||||
* account is in {@code defaultAccount}.
|
||||
*/
|
||||
public static String queueArn(String queueUrl, String partition, String region, String defaultAccount) {
|
||||
String url = queueUrl.contains("://") ? queueUrl : "sqs://queue/" + defaultAccount + "/" + queueUrl;
|
||||
String path = extractQueuePath(url);
|
||||
String account = accountFromQueueUrl(url);
|
||||
return new AwsArnUtils.Arn(partition, "sqs", region, account != null ? account : defaultAccount,
|
||||
path.substring(path.lastIndexOf('/') + 1)).toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The {@code Policy} attribute of the queue {@code queueArn} names, read from its account and
|
||||
* Region whichever account the caller is in. Empty when the queue does not exist or has no policy.
|
||||
*/
|
||||
public Optional<String> findQueuePolicy(String queueArn) {
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(queueArn);
|
||||
String queueUrl = "sqs://queue/" + arn.accountId() + "/" + arn.resource();
|
||||
return getQueueByUrl(regionKey(arn.region(), queueUrl), queueUrl)
|
||||
.map(queue -> queue.getAttributes().get("Policy"))
|
||||
.filter(policy -> !policy.isBlank());
|
||||
}
|
||||
|
||||
private String regionKey(String region, String queueUrl) {
|
||||
return region + "::" + extractQueuePath(normalizeQueueUrl(queueUrl));
|
||||
}
|
||||
|
||||
@@ -982,6 +982,9 @@ public class AslExecutor {
|
||||
JsonNode credentials = null;
|
||||
boolean readCredentials = stateDef.has("Credentials")
|
||||
&& (iamEnforcementEnabled() || (mockedInvocation == null && nestedTask));
|
||||
// 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;
|
||||
if (jsonata) {
|
||||
effectiveInput = input;
|
||||
if (stateDef.has("Arguments")) {
|
||||
@@ -992,17 +995,26 @@ public class AslExecutor {
|
||||
if (readCredentials) {
|
||||
credentials = jsonataEvaluator.resolveTemplate(stateDef.get("Credentials"), "Credentials",
|
||||
buildStatesVar(input, null, context), variables);
|
||||
} else if (recordCredentialsOnly) {
|
||||
recordedCredentials = credentialsOrNull(stateName,
|
||||
() -> jsonataEvaluator.resolveTemplate(stateDef.get("Credentials"), "Credentials",
|
||||
buildStatesVar(input, null, context), variables));
|
||||
}
|
||||
} else {
|
||||
effectiveInput = applyInputPath(stateDef, input, context);
|
||||
if (readCredentials) {
|
||||
credentials = resolveParameters(stateDef.get("Credentials"), effectiveInput, context);
|
||||
} else if (recordCredentialsOnly) {
|
||||
JsonNode credentialsInput = effectiveInput;
|
||||
recordedCredentials = credentialsOrNull(stateName,
|
||||
() -> resolveParameters(stateDef.get("Credentials"), credentialsInput, context));
|
||||
}
|
||||
if (stateDef.has("Parameters")) {
|
||||
effectiveInput = resolveParameters(stateDef.get("Parameters"), effectiveInput, context);
|
||||
}
|
||||
}
|
||||
String credentialsRoleArn = credentials == null ? null : credentials.path("RoleArn").asText(null);
|
||||
JsonNode taskCredentials = credentials;
|
||||
JsonNode scheduledCredentials = credentials != null ? credentials : recordedCredentials;
|
||||
|
||||
// Registered after the input template resolved, so a template failure leaves no token behind.
|
||||
CompletableFuture<JsonNode> tokenFuture = needsToken ? sfnService.get().registerPendingToken(taskToken,
|
||||
@@ -1014,7 +1026,7 @@ public class AslExecutor {
|
||||
// does not extend the Task's own TimeoutSeconds.
|
||||
long taskDeadlineNanos = taskDeadlineNanos(stateDef);
|
||||
try {
|
||||
addTaskScheduledEvent(chain, profile, stateDef, effectiveInput, sm);
|
||||
addTaskScheduledEvent(chain, profile, stateDef, effectiveInput, sm, scheduledCredentials);
|
||||
addTaskStartedEvent(chain, profile);
|
||||
try {
|
||||
String taskAccount = null;
|
||||
@@ -1032,7 +1044,7 @@ public class AslExecutor {
|
||||
effectiveResource, resourceInput, sm, resourceToken,
|
||||
context.path("Execution").path("Id").asText(null),
|
||||
executionDeadlineNanos, taskDeadlineNanos,
|
||||
jsonata ? null : stateDef.path("Parameters"), credentialsRoleArn,
|
||||
jsonata ? null : stateDef.path("Parameters"), taskCredentials,
|
||||
jobResponse -> RequestScopes.runAs(
|
||||
AwsArnUtils.parse(sm.getStateMachineArn()).accountId(),
|
||||
() -> addTaskSubmittedEvent(chain, profile, jobResponse))));
|
||||
@@ -1092,6 +1104,17 @@ public class AslExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/** A task's {@code Credentials} when only the history reads them, so a failure is not the task's. */
|
||||
private JsonNode credentialsOrNull(String stateName, Callable<JsonNode> resolve) throws Exception {
|
||||
try {
|
||||
return resolve.call();
|
||||
} catch (FailStateException e) {
|
||||
LOG.debugv("Task state {0}: Credentials did not resolve, so its history omits them: {1}",
|
||||
stateName, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private MockedTaskInvocation findMockedInvocation(JsonNode context, String stateName) {
|
||||
if (activeMocks.isEmpty()) {
|
||||
return null;
|
||||
@@ -1233,6 +1256,19 @@ public class AslExecutor {
|
||||
return colon >= 0 ? fn.substring(colon + 1) : null;
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
Optional<TaskPermissions> required = TaskPermissions.of(integration, input, sm);
|
||||
if (required.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if (credentials != null) {
|
||||
NestedTaskCredentials.validateShape(credentials);
|
||||
}
|
||||
lambdaTaskAuthorizer.authorize(sm, credentials == null ? null : credentials.path("RoleArn").asText(),
|
||||
required.get().errorPrefix(), required.get().permissions());
|
||||
}
|
||||
|
||||
private boolean iamEnforcementEnabled() {
|
||||
return config != null && config.services() != null && config.services().iam() != null
|
||||
&& config.services().iam().enforcementEnabled();
|
||||
@@ -1293,15 +1329,16 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param credentialsRoleArn the role the task's {@code Credentials} name, read only under IAM
|
||||
* enforcement, or null when the task runs as the execution role
|
||||
* @param 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
|
||||
* @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, String credentialsRoleArn,
|
||||
JsonNode rawParameters, JsonNode credentials,
|
||||
Consumer<JsonNode> jobSubmitted) throws Exception {
|
||||
String credentialsRoleArn = credentials == null ? null : credentials.path("RoleArn").asText(null);
|
||||
// Support Lambda resources: direct ARN or optimized integration
|
||||
String functionName = null;
|
||||
String functionRef = null;
|
||||
@@ -1415,6 +1452,10 @@ public class AslExecutor {
|
||||
return invokeNonIntegrationResource(resource, input, taskToken);
|
||||
}
|
||||
|
||||
if (iamEnforcementEnabled()) {
|
||||
authorizeTask(integration, input, sm, credentials);
|
||||
}
|
||||
|
||||
if (integration.is("apigateway", "invoke") && integration.suffix().isEmpty()) {
|
||||
try {
|
||||
return apiGatewayTaskInvoker.invoke(input, sm, credentialsRoleArn);
|
||||
@@ -6125,7 +6166,7 @@ public class AslExecutor {
|
||||
}
|
||||
|
||||
private void addTaskScheduledEvent(HistoryChain chain, TaskEventProfile profile, JsonNode stateDef,
|
||||
JsonNode effectiveInput, StateMachine sm) {
|
||||
JsonNode effectiveInput, StateMachine sm, JsonNode credentials) {
|
||||
LinkedHashMap<String, Object> details = new LinkedHashMap<>();
|
||||
if (profile.resourceType() != null) {
|
||||
details.put("resourceType", profile.resourceType());
|
||||
@@ -6144,6 +6185,10 @@ public class AslExecutor {
|
||||
if (stateDef.path("HeartbeatSeconds").isNumber()) {
|
||||
details.put("heartbeatInSeconds", stateDef.path("HeartbeatSeconds").asLong());
|
||||
}
|
||||
// ActivityScheduledEventDetails has no taskCredentials member.
|
||||
if (credentials != null && credentials.path("RoleArn").isTextual() && !"Activity".equals(profile.prefix())) {
|
||||
details.put("taskCredentials", Map.of("roleArn", credentials.path("RoleArn").asText()));
|
||||
}
|
||||
chain.publish(profile.prefix() + "Scheduled", details);
|
||||
}
|
||||
|
||||
|
||||
+84
-11
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServicePrincipals;
|
||||
import io.github.hectorvent.floci.services.iam.AccessDeniedMessages;
|
||||
import io.github.hectorvent.floci.services.iam.AccessDeniedMessages.PolicyType;
|
||||
import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
|
||||
@@ -14,16 +15,19 @@ import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.SimulationDeci
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.IamService.CallerArns;
|
||||
import io.github.hectorvent.floci.services.iam.RequestPrincipal;
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy;
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProviders;
|
||||
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.context.ApplicationScoped;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -37,6 +41,9 @@ import java.util.Optional;
|
||||
* resource's policy can allow a call; across accounts, both have to (IAM User Guide, cross-account
|
||||
* policy evaluation logic). The role's permissions boundary and its account's service control
|
||||
* policies limit it, and an explicit Deny in any of them refuses it.
|
||||
*
|
||||
* <p>{@link #authorize} is the same decision for any other integration's call, ahead of which it
|
||||
* requires the execution role to exist and to trust Step Functions.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class LambdaTaskAuthorizer {
|
||||
@@ -44,24 +51,79 @@ public class LambdaTaskAuthorizer {
|
||||
private static final Logger LOG = Logger.getLogger(LambdaTaskAuthorizer.class);
|
||||
private static final String INVOKE = "lambda:InvokeFunction";
|
||||
private static final String ASSUME_ROLE = "sts:AssumeRole";
|
||||
private static final String ANY_RESOURCE = "*";
|
||||
|
||||
private final IamService iamService;
|
||||
private final IamPolicyEvaluator evaluator;
|
||||
private final AssumeRolePolicyEvaluator trustEvaluator;
|
||||
private final LambdaResourcePolicyProvider functionPolicies;
|
||||
private final Instance<ResourcePolicyProvider> resourcePolicies;
|
||||
private final Instance<ScpProvider> scpProvider;
|
||||
|
||||
@Inject
|
||||
public LambdaTaskAuthorizer(IamService iamService, IamPolicyEvaluator evaluator,
|
||||
AssumeRolePolicyEvaluator trustEvaluator,
|
||||
LambdaResourcePolicyProvider functionPolicies, Instance<ScpProvider> scpProvider) {
|
||||
Instance<ResourcePolicyProvider> resourcePolicies,
|
||||
Instance<ScpProvider> scpProvider) {
|
||||
this.iamService = iamService;
|
||||
this.evaluator = evaluator;
|
||||
this.trustEvaluator = trustEvaluator;
|
||||
this.functionPolicies = functionPolicies;
|
||||
this.resourcePolicies = resourcePolicies;
|
||||
this.scpProvider = scpProvider;
|
||||
}
|
||||
|
||||
/**
|
||||
* One IAM action a task's call needs.
|
||||
*
|
||||
* @param action the IAM action, such as {@code sqs:SendMessage}
|
||||
* @param resourceArn the resource it acts on, or {@code *} for an action with no resource-level
|
||||
* permissions. An S3 ARN carries no account: the bucket's owner comes from S3
|
||||
* @param conditionKeys the condition keys the integrated service adds to the global ones
|
||||
*/
|
||||
public record Permission(String action, String resourceArn, Map<String, List<String>> conditionKeys) {
|
||||
|
||||
public Permission(String action, String resourceArn) {
|
||||
this(action, resourceArn, Map.of());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decides a task's call to its integrated service, throwing the failure the task records. The
|
||||
* execution role has to exist and to trust Step Functions, then to assume the role the task's
|
||||
* {@code Credentials} name, if any, and the role the task ends up with has to be allowed every
|
||||
* permission.
|
||||
*
|
||||
* @param credentialsRoleArn the role the task's {@code Credentials} resolved to, or null
|
||||
* @param errorPrefix the integration's error prefix, dot included, such as {@code SQS.}
|
||||
* @throws AslExecutor.FailStateException {@code States.Permissions} for the execution role,
|
||||
* {@code States.TaskFailed} for a refused assumption, and
|
||||
* {@code <errorPrefix>AccessDeniedException} for a refused permission
|
||||
*/
|
||||
void authorize(StateMachine machine, String credentialsRoleArn, String errorPrefix, List<Permission> permissions) {
|
||||
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
|
||||
IamRole executionRole = role(machine.getRoleArn()).orElseThrow(
|
||||
() -> new AslExecutor.FailStateException("States.Permissions",
|
||||
"The execution role " + machine.getRoleArn() + " does not exist."));
|
||||
if (!trustEvaluator.allowsService(executionRole.getAssumeRolePolicyDocument(), ServicePrincipals.of("states"),
|
||||
machine.getStateMachineArn(), owner.accountId())) {
|
||||
throw new AslExecutor.FailStateException("States.Permissions",
|
||||
"The execution role " + machine.getRoleArn() + " does not trust Step Functions.");
|
||||
}
|
||||
String effectiveRoleArn = machine.getRoleArn();
|
||||
if (credentialsRoleArn != null) {
|
||||
if (assumeRefusal(machine.getRoleArn(), credentialsRoleArn, machine.getStateMachineArn()).isPresent()) {
|
||||
throw NestedTaskCredentials.assumptionDenied(machine, credentialsRoleArn);
|
||||
}
|
||||
effectiveRoleArn = credentialsRoleArn;
|
||||
}
|
||||
for (Permission permission : permissions) {
|
||||
Optional<String> refusal = refusal(effectiveRoleArn, permission.action(), permission.resourceArn(),
|
||||
owner.region(), permission.conditionKeys());
|
||||
if (refusal.isPresent()) {
|
||||
throw new AslExecutor.FailStateException(errorPrefix + "AccessDeniedException", refusal.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns why {@code roleArn} may not invoke {@code functionArn}, as Lambda's access denied
|
||||
* message words it, or nothing when it may.
|
||||
@@ -74,7 +136,12 @@ public class LambdaTaskAuthorizer {
|
||||
|
||||
/** Applies the task role's identity policies, boundary and SCPs to the requested action. */
|
||||
public Optional<String> refusal(String roleArn, String action, String resourceArn) {
|
||||
AwsArnUtils.Arn resource = AwsArnUtils.parse(resourceArn);
|
||||
return refusal(roleArn, action, resourceArn, AwsArnUtils.regionOrDefault(resourceArn, null), Map.of());
|
||||
}
|
||||
|
||||
private Optional<String> refusal(String roleArn, String action, String resourceArn, String requestedRegion,
|
||||
Map<String, List<String>> conditionKeys) {
|
||||
AwsArnUtils.Arn resource = ANY_RESOURCE.equals(resourceArn) ? null : AwsArnUtils.parse(resourceArn);
|
||||
Optional<IamRole> invokingRole = role(roleArn);
|
||||
if (invokingRole.isEmpty()) {
|
||||
LOG.infov("Role {0} names no existing role, so it cannot invoke {1}", roleArn, resourceArn);
|
||||
@@ -86,16 +153,18 @@ public class LambdaTaskAuthorizer {
|
||||
AwsArnUtils.Arn roleId = AwsArnUtils.parse(invokingRoleArn);
|
||||
List<List<String>> scpLevels = scpLevels(roleId.accountId());
|
||||
|
||||
List<ResourcePolicy> policies = "lambda".equals(resource.service())
|
||||
? functionPolicies.getResourcePolicies("lambda", resourceArn) : List.of();
|
||||
String ownerAccount = policies.isEmpty() ? resource.accountId() : policies.getFirst().ownerAccountId();
|
||||
List<ResourcePolicy> policies = resource == null ? List.of()
|
||||
: ResourcePolicyProviders.policiesFor(resourcePolicies, resource.service(), action, resourceArn);
|
||||
String ownerAccount = policies.isEmpty()
|
||||
? (resource == null ? null : resource.accountId()) : policies.getFirst().ownerAccountId();
|
||||
List<String> documents = policies.stream()
|
||||
.map(ResourcePolicy::policyDocument)
|
||||
.filter(document -> document != null && !document.isBlank())
|
||||
.toList();
|
||||
Map<String, List<String>> serviceContext = new LinkedHashMap<>(conditionKeys);
|
||||
serviceContext.put("aws:PrincipalArn", List.of(invokingRoleArn));
|
||||
Map<String, List<String>> context = IamConditionContextResolver.withGlobalContext(
|
||||
Map.of("aws:PrincipalArn", List.of(invokingRoleArn)), resourceArn, resource.region(),
|
||||
roleId.accountId(), ownerAccount);
|
||||
serviceContext, resourceArn, requestedRegion, roleId.accountId(), ownerAccount);
|
||||
|
||||
RequestPrincipal session = RequestPrincipal.roleSession(sessionArn(invokingRoleArn), invokingRoleArn);
|
||||
ResourcePolicyDecision functionPolicy = evaluator.evaluateResourcePolicyFor(
|
||||
@@ -191,8 +260,12 @@ public class LambdaTaskAuthorizer {
|
||||
return scpProvider.isResolvable() ? scpProvider.get().effectiveScpLevels(accountId) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A resource whose account is unknown, an action on {@code *} or an S3 ARN of a bucket S3 does
|
||||
* not hold, is judged within the caller's account: nothing says it belongs to another.
|
||||
*/
|
||||
private static ResourceAccountRelationship relationship(String callerAccount, String resourceAccount) {
|
||||
return callerAccount.equals(resourceAccount)
|
||||
return resourceAccount == null || resourceAccount.isBlank() || callerAccount.equals(resourceAccount)
|
||||
? ResourceAccountRelationship.SAME_ACCOUNT : ResourceAccountRelationship.CROSS_ACCOUNT;
|
||||
}
|
||||
|
||||
|
||||
+9
-5
@@ -30,10 +30,7 @@ public class NestedTaskCredentials {
|
||||
throw new AslExecutor.FailStateException("States.Runtime",
|
||||
"Task Credentials account routing is supported only for nested executions");
|
||||
}
|
||||
if (!credentials.isObject() || credentials.size() != 1 || !credentials.path("RoleArn").isTextual()) {
|
||||
throw new AslExecutor.FailStateException("States.Runtime",
|
||||
"Task Credentials must resolve to an object containing RoleArn");
|
||||
}
|
||||
validateShape(credentials);
|
||||
String roleArn = credentials.path("RoleArn").asText();
|
||||
AwsArnUtils.Arn role;
|
||||
try {
|
||||
@@ -70,7 +67,14 @@ public class NestedTaskCredentials {
|
||||
return role.accountId();
|
||||
}
|
||||
|
||||
private static AslExecutor.FailStateException assumptionDenied(StateMachine machine, String roleArn) {
|
||||
static void validateShape(JsonNode credentials) {
|
||||
if (!credentials.isObject() || credentials.size() != 1 || !credentials.path("RoleArn").isTextual()) {
|
||||
throw new AslExecutor.FailStateException("States.Runtime",
|
||||
"Task Credentials must resolve to an object containing RoleArn");
|
||||
}
|
||||
}
|
||||
|
||||
static AslExecutor.FailStateException assumptionDenied(StateMachine machine, String roleArn) {
|
||||
return new AslExecutor.FailStateException("States.TaskFailed",
|
||||
"The role " + machine.getRoleArn() + " is not authorized to assume the task state's role, "
|
||||
+ roleArn + ".");
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsService;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.LambdaTaskAuthorizer.Permission;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* What a task's call to its integrated service needs from IAM. A request that names no resource
|
||||
* needs no permission here: the integrated service refuses it with its own validation error.
|
||||
*
|
||||
* @param errorPrefix the integration's error prefix, dot included
|
||||
* @param permissions the actions the call performs
|
||||
*/
|
||||
record TaskPermissions(String errorPrefix, List<Permission> permissions) {
|
||||
|
||||
/** The permissions of a mapped integration, or nothing for one that is not checked. */
|
||||
static Optional<TaskPermissions> of(StatesIntegration integration, JsonNode input, StateMachine machine) {
|
||||
if (integration.is("sqs", "sendMessage")) {
|
||||
return Optional.of(sqsSendMessage("SQS.", input, machine));
|
||||
}
|
||||
if (integration.isSdk("sqs", "sendMessage")) {
|
||||
return Optional.of(sqsSendMessage("Sqs.", input, machine));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static TaskPermissions sqsSendMessage(String errorPrefix, JsonNode input, StateMachine machine) {
|
||||
JsonNode queueUrl = input.path("QueueUrl");
|
||||
if (!queueUrl.isTextual() || queueUrl.asText().isBlank()) {
|
||||
return new TaskPermissions(errorPrefix, List.of());
|
||||
}
|
||||
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
|
||||
return new TaskPermissions(errorPrefix, List.of(new Permission("sqs:SendMessage",
|
||||
SqsService.queueArn(queueUrl.asText(), owner.partition(), owner.region(), owner.accountId()))));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user