feat(stepfunctions): evaluate the execution role on SNS and EventBridge tasks (#7622)

This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-06 08:34:39 -04:00
1 parent cdcb79a832
commit b1ba11c61e
16 files changed
+1255 -74

No files matched your search

@@ -0,0 +1,43 @@
package io.github.hectorvent.floci.services.eventbridge;
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 event bus policies to IAM policy evaluation, together with the account that owns the bus:
* the one in its ARN, also when the bus does not exist or has no policy, so a call to another
* account's bus is judged as cross-account.
*/
@ApplicationScoped
public class EventBridgeResourcePolicyProvider implements ResourcePolicyProvider {
private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
private static final String BUS_PREFIX = "event-bus/";
private final EventBridgeService eventBridgeService;
@Inject
public EventBridgeResourcePolicyProvider(EventBridgeService eventBridgeService) {
this.eventBridgeService = eventBridgeService;
}
@Override
public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
if (!AwsArnUtils.isArnFor(resourceArn, "events")) {
return List.of();
}
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
String name = arn.resource().startsWith(BUS_PREFIX) ? arn.resource().substring(BUS_PREFIX.length()) : "";
if (!ACCOUNT_ID.matcher(arn.accountId()).matches() || arn.region().isBlank()
|| name.isBlank() || name.contains("*") || name.contains("/")) {
return List.of();
}
return List.of(new ResourcePolicy(eventBridgeService.findBusPolicy(resourceArn).orElse(null),
arn.accountId()));
}
}
@@ -821,7 +821,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
ObjectNode statement = objectMapper.createObjectNode();
statement.put("Sid", statementId);
statement.put("Effect", "Allow");
statement.put("Principal", principal != null ? principal : "*");
statement.set("Principal", permissionPrincipal(principal, bus.getArn()));
statement.put("Action", action != null ? action : "events:PutEvents");
statement.put("Resource", bus.getArn());
if (conditionJson != null && !conditionJson.isBlank()) {
@@ -840,6 +840,20 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
LOG.infov("Put permission on bus {0}, statement {1}", effectiveBus, statementId);
}
/**
* The principal a {@code PutPermission} statement grants: every account for {@code *}, and otherwise the
* account the request names, as its root in the bus's partition.
*/
private static JsonNode permissionPrincipal(String principal, String busArn) {
if (principal == null || "*".equals(principal)) {
return TextNode.valueOf("*");
}
ObjectNode aws = JsonNodeFactory.instance.objectNode();
aws.put("AWS", AwsArnUtils.Arn.global(AwsArnUtils.parse(busArn).partition(), "iam", principal, "root")
.toString());
return aws;
}
/**
* Parses client-supplied JSON (PutPermission Policy/Condition). Malformed input is a
* client error; without this it fell into the catch-all and surfaced as a 500.
@@ -1424,6 +1438,34 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
return !(value instanceof String s) || s.isBlank();
}
/**
* The ARN of the event bus a {@code PutEvents} entry's {@code EventBusName} reaches: the bus of that
* name, or of the name its ARN gives, in the {@code account} and {@code region} the call runs in, as
* {@link #putEventsFromRequest} looks it up whatever account and Region the ARN names. Empty for an
* ARN that request refuses as malformed.
*/
public static Optional<String> eventBusArn(String eventBusName, String partition, String region, String account) {
try {
return Optional.of(new AwsArnUtils.Arn(partition, "events", region, account,
"event-bus/" + resolvedBusName(eventBusName)).toString());
} catch (AwsException e) {
LOG.debugv("EventBusName {0} is malformed, so it names no bus: {1}", eventBusName, e.getMessage());
return Optional.empty();
}
}
/**
* The resource policy of the event bus {@code busArn} names, in the account and Region of that ARN.
* Empty when the bus does not exist or has no policy; the default bus has none until one is put on it.
*/
public Optional<String> findBusPolicy(String busArn) {
AwsArnUtils.Arn arn = AwsArnUtils.parse(busArn);
String name = arn.resource().substring("event-bus/".length());
return accountGet(busStore, arn.accountId(), busKey(arn.region(), name))
.map(EventBus::getPolicy)
.filter(policy -> !policy.isBlank());
}
private static String resolvedBusName(String busName) {
if (busName == null || busName.isBlank()) {
return "default";
@@ -1267,7 +1267,7 @@ public class AslExecutor {
NestedTaskCredentials.validateShape(credentials);
}
lambdaTaskAuthorizer.authorize(sm, credentials == null ? null : credentials.path("RoleArn").asText(),
required.get().errorPrefix(), required.get().permissions());
required.get().deniedError(), required.get().permissions());
}
private boolean iamEnforcementEnabled() {
@@ -93,12 +93,11 @@ public class LambdaTaskAuthorizer {
* 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.}
* @param deniedError the error a refused permission fails with, such as {@code SQS.AccessDeniedException}
* @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
* {@code States.TaskFailed} for a refused assumption, and {@code deniedError} for a refused permission
*/
void authorize(StateMachine machine, String credentialsRoleArn, String errorPrefix, List<Permission> permissions) {
void authorize(StateMachine machine, String credentialsRoleArn, String deniedError, List<Permission> permissions) {
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
IamRole executionRole = role(machine.getRoleArn()).orElseThrow(
() -> new AslExecutor.FailStateException("States.Permissions",
@@ -119,7 +118,7 @@ public class LambdaTaskAuthorizer {
Optional<String> refusal = refusal(effectiveRoleArn, permission.action(), permission.resourceArn(),
owner.region(), permission.conditionKeys());
if (refusal.isPresent()) {
throw new AslExecutor.FailStateException(errorPrefix + "AccessDeniedException", refusal.get());
throw new AslExecutor.FailStateException(deniedError, refusal.get());
}
}
}
@@ -2,21 +2,25 @@ 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.eventbridge.EventBridgeService;
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.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/**
* 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 deniedError the error a refused permission fails the task with: the integration's prefix and
* the exception the integrated service's SDK raises for an access denial
* @param permissions the actions the call performs
*/
record TaskPermissions(String errorPrefix, List<Permission> permissions) {
record TaskPermissions(String deniedError, 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) {
@@ -26,16 +30,66 @@ record TaskPermissions(String errorPrefix, List<Permission> permissions) {
if (integration.isSdk("sqs", "sendMessage")) {
return Optional.of(sqsSendMessage("Sqs.", input, machine));
}
if (integration.is("sns", "publish")) {
return Optional.of(snsPublish("SNS.", input));
}
if (integration.isSdk("sns", "publish")) {
return Optional.of(snsPublish("Sns.", input));
}
if (integration.is("events", "putEvents")) {
return Optional.of(eventsPutEvents(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());
return new TaskPermissions(errorPrefix + "AccessDeniedException", List.of());
}
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
return new TaskPermissions(errorPrefix, List.of(new Permission("sqs:SendMessage",
return new TaskPermissions(errorPrefix + "AccessDeniedException", List.of(new Permission("sqs:SendMessage",
SqsService.queueArn(queueUrl.asText(), owner.partition(), owner.region(), owner.accountId()))));
}
/**
* What {@code Publish} sends to, read as its handler reads the members and in the order
* {@code SnsService.publish} takes them: a phone number before a topic, and a topic before a target.
* Sending an SMS has no resource to check. A value that is not an SNS ARN reaches nothing, as the
* lookups need the ARN a topic or an endpoint is stored under, so SNS answers it. A refusal is SNS's
* {@code AuthorizationError}, which its SDKs raise as {@code AuthorizationErrorException}.
*/
private static TaskPermissions snsPublish(String errorPrefix, JsonNode input) {
String deniedError = errorPrefix + "AuthorizationErrorException";
if (input.path("PhoneNumber").asText(null) != null) {
return new TaskPermissions(deniedError, List.of(new Permission("sns:Publish", "*")));
}
String topicArn = input.path("TopicArn").asText(null);
String resourceArn = topicArn != null ? topicArn : input.path("TargetArn").asText(null);
if (!AwsArnUtils.isArnFor(resourceArn, "sns")) {
return new TaskPermissions(deniedError, List.of());
}
return new TaskPermissions(deniedError, List.of(new Permission("sns:Publish", resourceArn)));
}
/**
* 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.
*/
private static TaskPermissions eventsPutEvents(JsonNode input, StateMachine machine) {
AwsArnUtils.Arn owner = AwsArnUtils.parse(machine.getStateMachineArn());
Set<String> buses = new LinkedHashSet<>();
JsonNode entries = input.path("Entries");
if (entries.isArray()) {
for (JsonNode entry : entries) {
if (entry.isObject()) {
EventBridgeService.eventBusArn(entry.path("EventBusName").asText(null), owner.partition(),
owner.region(), owner.accountId()).ifPresent(buses::add);
}
}
}
return new TaskPermissions("EventBridge.AccessDeniedException",
buses.stream().map(bus -> new Permission("events:PutEvents", bus)).toList());
}
}