diff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.md index affd62aaf7..015f955e97 100644 --- a/docs/services/eventbridge.md +++ b/docs/services/eventbridge.md @@ -362,6 +362,15 @@ aws events put-targets \ - Pending retries are kept in memory and are dropped by an emulator reset or restart. - An `AWS::Events::Rule` target in a CloudFormation template keeps its `RetryPolicy`, `DeadLetterConfig`, `RoleArn`, `EcsParameters` and `AppSyncParameters`, which reach the rule as `PutTargets` would set them. A value of another type than the resource schema declares for them fails the rule before it is created, with the message CloudFormation gives. +## Event Bus Policies under IAM Enforcement + +With `floci.services.iam.enforcement-enabled` on, a bus's policy takes part in the decision as IAM's +policy evaluation logic describes. `PutPermission` with a `Principal` account id adds a statement +naming that account's root, `{"AWS": "arn:aws:iam:::root"}`, and `*` stays `*`. Within one +account a statement naming the caller's role or user, or `*`, can allow a call on its own, a statement +naming only the account leaves it to the caller's identity policies, and an explicit `Deny` in either +refuses it. Across accounts the bus policy and the caller's identity policies both have to allow it. + ## Current Behavior - `PutEvents` reports success once the source bus accepts an event. Target delivery failures are retried and dead-lettered as described above, and otherwise surface only as a `WARN` in the Floci logs. diff --git a/docs/services/iam.md b/docs/services/iam.md index 172cea70c0..8f101767ea 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -2291,7 +2291,9 @@ When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` is active, Floci also queries regi - Lambda function policies, the statements `AddPermission` adds, take part the same way. An invoke of another account's function by ARN runs it in that account, so its function policy has to allow the caller as well; see [Function policies under IAM enforcement](lambda.md#function-policies-under-iam-enforcement). - SNS topic policies take part the same way for a request that names the topic in a JSON-protocol body; a topic with no policy set has the default one AWS gives a new topic. See [SNS](sns.md). - Aurora DSQL cluster policies take part the same way for a control plane call on the cluster, and when a client connects to the cluster's endpoint. See [DSQL](dsql.md#authentication). -- SQS queue and API Gateway REST API policies are stored but not evaluated. +- SQS queue policies take part the same way for a call on the queue; see [SQS](sqs.md#queue-policies-under-iam-enforcement). +- EventBridge event bus policies, the statements `PutPermission` adds, take part the same way for a call on the bus; see [EventBridge](eventbridge.md#event-bus-policies-under-iam-enforcement). +- API Gateway REST API policies are stored but not evaluated. - A call an AWS service makes to another service's resource on its own behalf, such as SES publishing an event or a notification to an SNS topic, has no IAM principal, so the target's resource policy decides it alone and has to allow the calling service, through `{"Service": ".amazonaws.com"}` or `{"AWS": "*"}`. A target with no policy refuses it. Its request context holds `aws:PrincipalIsAWSService` (`true`), `aws:PrincipalServiceName` and `aws:PrincipalServiceNamesList`, `aws:SourceArn` and `aws:SourceAccount` for the resource whose configuration triggered the call, `aws:ResourceAccount` and `aws:RequestedRegion`, and none of the keys that describe an IAM principal. A publish to an SNS topic from SES also carries `aws:SourceOwner`, the key the SNS Developer Guide lists SES among the services setting, which is what the default topic policy checks, so that policy admits SES acting for the topic owner's account and no other. SES and Lambda, when it reads the code of a Web Function revision from S3, are the services checked this way so far; see [SES IAM enforcement](ses.md#iam-enforcement) and [Lambda Web Functions](lambda-web-functions.md#emulation-behavior). ### Service control policies (SCPs) diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md index 2605eebd40..e473f002a6 100644 --- a/docs/services/step-functions.md +++ b/docs/services/step-functions.md @@ -90,9 +90,10 @@ With IAM enforcement enabled, the existing task authorizer checks the execution 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. Lambda, API Gateway and SQS tasks evaluate `Credentials` themselves -([Lambda](#lambda-tasks-under-iam-enforcement), [SQS](#sqs-tasks-under-iam-enforcement)); other -integrations retain their existing credential handling. +are not evaluated. Lambda, API Gateway, SQS, SNS and EventBridge tasks evaluate `Credentials` +themselves ([Lambda](#lambda-tasks-under-iam-enforcement), +[messaging](#messaging-tasks-under-iam-enforcement)); other integrations retain their existing +credential handling. 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 @@ -566,11 +567,20 @@ function as `RoleArn.$`, or through JSONata. A role the execution role cannot as with `States.Permissions`, whose cause names the execution role's session and `sts:AssumeRole` on the role. -## SQS tasks under IAM enforcement +## Messaging tasks under IAM enforcement -`arn:aws:states:::sqs:sendMessage`, `arn:aws:states:::aws-sdk:sqs:sendMessage` and their -`.waitForTaskToken` forms are evaluated with [IAM enforcement](iam.md#resource-based-policies) on, -each attempt in turn, so `Retry` and `Catch` see a refusal like any other task failure: +These tasks and their `.waitForTaskToken` forms are evaluated with +[IAM enforcement](iam.md#resource-based-policies) on: + +| Resource | Action | Resource evaluated | Refused with | +|---|---|---|---| +| `arn:aws:states:::sqs:sendMessage` | `sqs:SendMessage` | The queue `QueueUrl` names | `SQS.AccessDeniedException` | +| `arn:aws:states:::aws-sdk:sqs:sendMessage` | `sqs:SendMessage` | The queue `QueueUrl` names | `Sqs.AccessDeniedException` | +| `arn:aws:states:::sns:publish` | `sns:Publish` | `TopicArn`, else `TargetArn`, or `*` for a `PhoneNumber` | `SNS.AuthorizationErrorException` | +| `arn:aws:states:::aws-sdk:sns:publish` | `sns:Publish` | `TopicArn`, else `TargetArn`, or `*` for a `PhoneNumber` | `Sns.AuthorizationErrorException` | +| `arn:aws:states:::events:putEvents` | `events:PutEvents` | Each distinct event bus the entries name | `EventBridge.AccessDeniedException` | + +Each attempt is decided in turn, so `Retry` and `Catch` see a refusal like any other task failure: 1. The execution role has to exist and to trust `states.amazonaws.com`, or the task fails with `States.Permissions`. @@ -579,19 +589,58 @@ each attempt in turn, so `Retry` and `Catch` see a refusal like any other task f exist, fails the task with `States.TaskFailed` and the cause "The role X is not authorized to assume the task state's role, Y.", the form AWS answers a nested execution with. `Credentials` that do not resolve to an object holding only `RoleArn` fail with `States.Runtime`. -3. The role the task ends up with has to be allowed `sqs:SendMessage` on the queue `QueueUrl` names, - or the task fails with `SQS.AccessDeniedException` (`Sqs.AccessDeniedException` for the - `aws-sdk` form), whose cause names the role's session and the kind of policy that refused it. The - queue is the one Floci's lookup reaches: the account and name in the URL's path, in the state - machine's Region. A request with no `QueueUrl` gets SQS's own error once the role has passed. +3. The role the task ends up with has to be allowed the action on the resource, or the task fails with + the error in the table, whose cause names the role's session and the kind of policy that refused + it. -The error names `States.Permissions` and `.AccessDeniedException` are Floci's reading: they -have not been verified against AWS. Only global condition keys are available to the policies. The -queue's own policy (`SetQueueAttributes` or `AddPermission`) takes part as it does for a direct SQS -request: within one account it or the role's policies can allow the send, and across accounts both -have to. 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. +The resource is the one Floci's lookup reaches, which is what the task then acts on: + +- **SQS:** the account and name in the URL's path, in the state machine's Region. +- **SNS:** the ARN as the request gives it. `PhoneNumber` comes first, since Floci sends the SMS + whatever else the request names. +- **EventBridge:** the bus of the name `EventBusName` gives, or the default bus without one, in the + state machine's account and Region. An ARN counts for its name only, because that is the bus + `PutEvents` reaches from a task: a bus ARN naming another account or Region is evaluated, and sent + to, as the bus of that name in the state machine's. A direct `PutEvents` request under enforcement + evaluates the ARN as given. All the buses are evaluated before any entry is sent, so one refused + bus sends nothing. An entry EventBridge would reject, such as one without `Source`, still counts, + as for a direct `PutEvents`. The EventBridge User Guide states the check on every entry, and the + refusal of the whole request, for the Custom Event Bus. It does not describe Classic buses, and + Floci applies the same reading to them. + +A request that names no resource has only the role checks in the list above, and its service then +answers it with its own error: no `QueueUrl`, a `TopicArn` or `TargetArn` that is not an SNS ARN or +neither of them, an entry that is not an object, an `EventBusName` that is a malformed ARN, or no +entries at all. + +A refused permission is named as the task's other errors from its service are: the integration's +prefix and the exception the service's SDK raises. For SNS that is `AuthorizationErrorException`, the +refusal `Publish` declares and the one a direct `Publish` under enforcement answers with, and for the +others `AccessDeniedException`. `States.Permissions`, and these names for a refusal, are Floci's +reading: they have not been verified against AWS. Only global condition keys are available to the +policies. + +Resource policies take part as they do for a direct request under enforcement, for queues, topics and +event buses: + +- **SQS:** the queue's own policy (`SetQueueAttributes` or `AddPermission`) or the role's policies + can allow the send within one account, and across accounts both have to. +- **SNS:** a topic policy can grant `sns:Publish` to a role of the topic's account with no identity + policy, a Deny in it refuses a role its identity policy allows, and the default policy of a new + topic admits no role, because no role's call carries `aws:SourceOwner`. Across accounts both the + role's policies and the topic policy have to allow the publish. +- **EventBridge:** the bus's policy (`PutPermission`) can grant `events:PutEvents` to a role of the + bus's account that it names, with no identity policy, and a Deny in it refuses a role its identity + policy allows. A statement naming only the account, the form `PutPermission` writes for a + `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. + +Floci has no `aws-sdk:eventbridge:putEvents` integration: that resource fails with +`States.TaskFailed` and "Unsupported resource" whether or not enforcement is on. Integrations other than these, Lambda, API Gateway and nested executions are not evaluated yet: they run in the state machine's account whatever the execution role's policies say. @@ -655,7 +704,7 @@ direct ECS API. Lambda mapping tasks currently return an unpaginated list; `Marker` and `MaxItems` are rejected with `Lambda.InvalidParameterValueException` instead of being silently ignored. These six integrations do not evaluate the state-machine execution role's per-action IAM policies; among the task integrations, Lambda, API -Gateway, nested executions and [SQS](#sqs-tasks-under-iam-enforcement) do. Name-based lookups use the +Gateway, nested executions and the [messaging tasks](#messaging-tasks-under-iam-enforcement) do. Name-based lookups use the execution scope; explicit ARNs retain the underlying service's cross-account lookup behavior. The underlying services' validation still applies. They implement request-response calls, without job-completion polling. diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeResourcePolicyProvider.java new file mode 100644 index 0000000000..75f6d7f350 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeResourcePolicyProvider.java @@ -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 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())); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java index f4ed870ece..3e4243048a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java @@ -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 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 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"; diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java index f0ce64f730..ed63ec821f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java @@ -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() { diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java index beb6bce10b..5f5dd82c98 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java @@ -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 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 permissions) { + void authorize(StateMachine machine, String credentialsRoleArn, String deniedError, List 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 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()); } } } diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissions.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissions.java index 0b47b4c2e6..c7ac7a1f8a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissions.java +++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissions.java @@ -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 permissions) { +record TaskPermissions(String deniedError, List permissions) { /** The permissions of a mapped integration, or nothing for one that is not checked. */ static Optional of(StatesIntegration integration, JsonNode input, StateMachine machine) { @@ -26,16 +30,66 @@ record TaskPermissions(String errorPrefix, List 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 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()); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgePermissionIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgePermissionIntegrationTest.java index 7f5d826e73..af3c90f601 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgePermissionIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgePermissionIntegrationTest.java @@ -60,6 +60,7 @@ class EventBridgePermissionIntegrationTest { .statusCode(200) .body("Policy", notNullValue()) .body("Policy", containsString("test-stmt")) + .body("Policy", containsString("\"Principal\":\"*\"")) .body("Policy", containsString("events:PutEvents")); } @@ -90,7 +91,7 @@ class EventBridgePermissionIntegrationTest { .post("/") .then() .statusCode(200) - .body("Policy", containsString("123456789012")) + .body("Policy", containsString("\"Principal\":{\"AWS\":\"arn:aws:iam::123456789012:root\"}")) .body("Policy", not(containsString("\"*\""))); } diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeResourcePolicyProviderTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeResourcePolicyProviderTest.java new file mode 100644 index 0000000000..12444e11e2 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeResourcePolicyProviderTest.java @@ -0,0 +1,53 @@ +package io.github.hectorvent.floci.services.eventbridge; + +import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class EventBridgeResourcePolicyProviderTest { + + private static final String OWNER = "111122223333"; + private static final String BUS = "arn:aws:events:us-east-1:" + OWNER + ":event-bus/orders"; + private static final String POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + + private EventBridgeService eventBridgeService; + private EventBridgeResourcePolicyProvider provider; + + @BeforeEach + void setUp() { + eventBridgeService = mock(EventBridgeService.class); + when(eventBridgeService.findBusPolicy(anyString())).thenReturn(Optional.empty()); + provider = new EventBridgeResourcePolicyProvider(eventBridgeService); + } + + @Test + void aBusComesWithItsPolicyAndTheAccountInItsArn() { + when(eventBridgeService.findBusPolicy(BUS)).thenReturn(Optional.of(POLICY)); + + assertEquals(List.of(new ResourcePolicy(POLICY, OWNER)), provider.getResourcePolicies("events", BUS)); + } + + @Test + void aBusWithNoPolicyStillHasItsOwner() { + assertEquals(List.of(new ResourcePolicy(null, OWNER)), provider.getResourcePolicies("events", BUS)); + } + + @Test + void anythingThatIsNotOneBusIsLeftToOtherProviders() { + String events = "arn:aws:events:us-east-1:" + OWNER + ":"; + assertTrue(provider.getResourcePolicies("events", "*").isEmpty()); + assertTrue(provider.getResourcePolicies("events", events + "event-bus/*").isEmpty()); + assertTrue(provider.getResourcePolicies("events", events + "rule/orders/r").isEmpty()); + assertTrue(provider.getResourcePolicies("events", "arn:aws:events:::event-bus/orders").isEmpty()); + assertTrue(provider.getResourcePolicies("sqs", "arn:aws:sqs:us-east-1:" + OWNER + ":orders").isEmpty()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java index 4188beac2f..d8aa6b5b46 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java @@ -418,7 +418,7 @@ class LambdaTaskAuthorizerTest { roleWithPolicies(STATES_DESCRIBE_ANYTHING); executionRole(STATES_TRUST); - authorizer.authorize(machine(), null, "Ec2.", List.of(new Permission("states:DescribeRegions", "*"))); + authorizer.authorize(machine(), null, "Ec2.AccessDeniedException", List.of(new Permission("states:DescribeRegions", "*"))); } @Test @@ -429,7 +429,7 @@ class LambdaTaskAuthorizerTest { executionRole(STATES_TRUST); AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, - () -> authorizer.authorize(machine(), null, "Ec2.", + () -> authorizer.authorize(machine(), null, "Ec2.AccessDeniedException", List.of(new Permission("states:DescribeRegions", "*")))); assertEquals("Ec2.AccessDeniedException", refused.error); @@ -487,10 +487,10 @@ class LambdaTaskAuthorizerTest { "Resource":"*","Condition":{"StringEquals":{"states:HTTPEndpoint":"https://example.test"}}}]}"""); executionRole(STATES_TRUST); - authorizer.authorize(machine(), null, "States.", List.of(new Permission("states:InvokeHTTPEndpoint", "*", + authorizer.authorize(machine(), null, "States.AccessDeniedException", List.of(new Permission("states:InvokeHTTPEndpoint", "*", Map.of("states:HTTPEndpoint", List.of("https://example.test"))))); AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, - () -> authorizer.authorize(machine(), null, "States.", List.of(new Permission( + () -> authorizer.authorize(machine(), null, "States.AccessDeniedException", List.of(new Permission( "states:InvokeHTTPEndpoint", "*", Map.of("states:HTTPEndpoint", List.of("https://other.test")))))); assertEquals("States.AccessDeniedException", refused.error); } @@ -503,13 +503,13 @@ class LambdaTaskAuthorizerTest { "Condition":{"StringEquals":{"aws:RequestedRegion":"us-east-1"}}}]}"""); executionRole(STATES_TRUST); - authorizer.authorize(machine(), null, "S3.", List.of(new Permission("s3:PutObject", BUCKET))); + authorizer.authorize(machine(), null, "S3.AccessDeniedException", List.of(new Permission("s3:PutObject", BUCKET))); } @Test void anExecutionRoleThatDoesNotExistRefusesTheTask() { AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, - () -> authorizer.authorize(machine(), null, "SQS.", List.of())); + () -> authorizer.authorize(machine(), null, "SQS.AccessDeniedException", List.of())); assertEquals("States.Permissions", refused.error); assertTrue(refused.cause.contains(ROLE), refused.cause); @@ -521,7 +521,7 @@ class LambdaTaskAuthorizerTest { executionRole(trust("{\"Service\":\"lambda.amazonaws.com\"}")); AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, - () -> authorizer.authorize(machine(), null, "S3.", List.of(new Permission("s3:PutObject", BUCKET)))); + () -> authorizer.authorize(machine(), null, "S3.AccessDeniedException", List.of(new Permission("s3:PutObject", BUCKET)))); assertEquals("States.Permissions", refused.error); assertTrue(refused.cause.contains(ROLE), refused.cause); @@ -535,9 +535,9 @@ class LambdaTaskAuthorizerTest { when(iamService.resolvePrincipalContext(ROLE)).thenReturn(CallerContext.of(List.of(ASSUME_ANY_ROLE))); when(iamService.resolvePrincipalContext(OWN_TASK_ROLE)).thenReturn(CallerContext.of(List.of(PUT_OBJECTS))); - authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of(new Permission("s3:PutObject", BUCKET))); + authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.AccessDeniedException", List.of(new Permission("s3:PutObject", BUCKET))); AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, - () -> authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of( + () -> authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.AccessDeniedException", List.of( new Permission("s3:PutObject", BUCKET), new Permission("s3:GetObject", BUCKET)))); assertEquals("S3.AccessDeniedException", refused.error); @@ -552,7 +552,7 @@ class LambdaTaskAuthorizerTest { taskRole(OWN_TASK_ROLE, trust("{\"Service\":\"lambda.amazonaws.com\"}")); AslExecutor.FailStateException refused = assertThrows(AslExecutor.FailStateException.class, - () -> authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.", List.of())); + () -> authorizer.authorize(machine(), OWN_TASK_ROLE, "S3.AccessDeniedException", List.of())); assertEquals("States.TaskFailed", refused.error); assertEquals("The role " + ROLE + " is not authorized to assume the task state's role, " + OWN_TASK_ROLE + ".", diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMessagingTaskIamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMessagingTaskIamIntegrationTest.java new file mode 100644 index 0000000000..9818f1123f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMessagingTaskIamIntegrationTest.java @@ -0,0 +1,777 @@ +package io.github.hectorvent.floci.services.stepfunctions; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.services.sqs.SqsService; +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testing.SqsTestQueue; +import io.github.hectorvent.floci.testing.StepFunctionsTestClient; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.Response; +import jakarta.inject.Inject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.URI; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.github.hectorvent.floci.testing.StepFunctionsTestClient.LAMBDA_TRUST; +import static io.github.hectorvent.floci.testing.StepFunctionsTestClient.STATES_TRUST; +import static io.github.hectorvent.floci.testing.StepFunctionsTestClient.trusting; +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** SNS and EventBridge tasks under IAM enforcement; each destination forwards to a queue the test reads. */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class StepFunctionsMessagingTaskIamIntegrationTest { + private static final String ACCOUNT = "000000000451"; + private static final String OTHER_ACCOUNT = "000000000452"; + private static final String REGION = "us-east-1"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String READ_ONLY = allow("*", "sns:ListTopics", "events:ListRules"); + private static final String ASSUME = allow("*", "sts:AssumeRole"); + private static final String PUBLISH_ANY = allow("*", "sns:Publish", "events:PutEvents"); + + @TestHTTPResource + URI baseUri; + + @Inject + SqsService sqsService; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @BeforeAll + static void configureRestAssured() { + RestAssuredJsonUtils.configureAwsContentTypes(); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void anExecutionRoleAllowedTheActionOnTheResourceDelivers(String integration) throws Exception { + Target target = target(integration); + String role = role(STATES_TRUST, allow(target.resourceArn(), target.action())); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertDelivered(target); + } + + @ParameterizedTest + @CsvSource({"sns:publish,jsonpath", "aws-sdk:sns:publish,jsonpath", "events:putEvents,jsonpath", + "sns:publish,jsonata", "aws-sdk:sns:publish,jsonata", "events:putEvents,jsonata"}) + void anExecutionRoleNotAllowedTheActionIsRefused(String integration, String form) throws Exception { + Target target = target(integration); + Map task = "jsonata".equals(form) ? jsonataTask(target, null) + : jsonPathTask(target, null); + String machine = machine(task, role(STATES_TRUST, READ_ONLY)); + + Response completed = terminal(start(machine, "{}")); + + assertFailed(completed, target.error()); + String cause = completed.jsonPath().getString("cause"); + assertTrue(cause.contains(target.action()), cause); + assertTrue(cause.contains(target.resourceArn()), cause); + assertNothingDelivered(target); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void theActionOnAnotherResourceDoesNotCount(String integration) throws Exception { + Target target = target(integration); + String elsewhere = target.resourceArn() + "-elsewhere"; + String machine = machine(jsonPathTask(target, null), role(STATES_TRUST, allow(elsewhere, target.action()))); + + assertFailed(terminal(start(machine, "{}")), target.error()); + assertNothingDelivered(target); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void anExecutionRoleThatDoesNotTrustStepFunctionsIsRefusedWhateverItsPolicies(String integration) throws Exception { + Target target = target(integration); + String role = role(LAMBDA_TRUST, PUBLISH_ANY); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(completed, "States.Permissions"); + assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString()); + assertNothingDelivered(target); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void anExecutionRoleThatDoesNotExistIsRefused(String integration) throws Exception { + Target target = target(integration); + String role = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID(); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(completed, "States.Permissions"); + assertTrue(completed.jsonPath().getString("cause").contains(role), completed.asString()); + assertNothingDelivered(target); + } + + @ParameterizedTest + @CsvSource({"sns:publish,jsonpath", "aws-sdk:sns:publish,jsonpath", "events:putEvents,jsonpath", + "sns:publish,jsonata", "aws-sdk:sns:publish,jsonata", "events:putEvents,jsonata"}) + void credentialsDeliverAsTheirRoleWithoutTheExecutionRolesPermission(String integration, String form) + throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, ASSUME); + String taskRole = role(trusting(executionRole), allow(target.resourceArn(), target.action())); + Map task = "jsonata".equals(form) ? jsonataTask(target, "{% $states.input.role %}") + : jsonPathTask(target, taskRole); + String machine = machine(task, executionRole); + + String execution = start(machine, MAPPER.writeValueAsString(Map.of("role", taskRole))); + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertDelivered(target); + JsonNode scheduled = eventsOfType(execution, "TaskScheduled").getFirst(); + assertEquals(taskRole, scheduled.path("taskScheduledEventDetails").path("taskCredentials").path("roleArn").asText()); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void aRoleTheExecutionRoleCannotAssumeFailsInTheNestedForm(String integration) throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, PUBLISH_ANY); + String taskRole = role(LAMBDA_TRUST, PUBLISH_ANY); + + Response completed = terminal(start(machine(jsonPathTask(target, taskRole), executionRole), "{}")); + + assertFailed(completed, "States.TaskFailed"); + assertEquals("The role " + executionRole + " is not authorized to assume the task state's role, " + taskRole + ".", + completed.jsonPath().getString("cause")); + assertNothingDelivered(target); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "events:putEvents"}) + void aCredentialsRoleThatDoesNotExistFailsAsARefusedAssumption(String integration) throws Exception { + Target target = target(integration); + String taskRole = "arn:aws:iam::" + ACCOUNT + ":role/no-such-role-" + UUID.randomUUID(); + String executionRole = role(STATES_TRUST, PUBLISH_ANY); + + assertFailed(terminal(start(machine(jsonPathTask(target, taskRole), executionRole), "{}")), "States.TaskFailed"); + assertNothingDelivered(target); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void aCredentialsRoleNotAllowedTheActionIsRefusedEvenIfTheExecutionRoleIs(String integration) throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, allow("*", "sts:AssumeRole", "sns:Publish", "events:PutEvents")); + String taskRole = role(trusting(executionRole), READ_ONLY); + + Response completed = terminal(start(machine(jsonPathTask(target, taskRole), executionRole), "{}")); + + assertFailed(completed, target.error()); + String cause = completed.jsonPath().getString("cause"); + assertTrue(cause.contains("assumed-role/" + taskRole.substring(taskRole.lastIndexOf('/') + 1)), cause); + assertNothingDelivered(target); + } + + @ParameterizedTest + @CsvSource({"sns:publish,jsonpath", "aws-sdk:sns:publish,jsonpath", "events:putEvents,jsonpath", + "sns:publish,jsonata", "events:putEvents,jsonata"}) + void waitForTaskTokenRefusedDoesNotWaitAndDeliversNothing(String integration, String form) throws Exception { + Target target = target(integration); + Map task = new LinkedHashMap<>("jsonata".equals(form) + ? jsonataTask(target, null) : jsonPathTask(target, null)); + task.put("Resource", "arn:aws:states:::" + integration + ".waitForTaskToken"); + task.put("TimeoutSeconds", 60); + + Response completed = terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + assertFailed(completed, target.error()); + assertNothingDelivered(target); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void waitForTaskTokenAllowedDeliversAndWaits(String integration) throws Exception { + Target target = target(integration); + String executionRole = role(STATES_TRUST, ASSUME); + String taskRole = role(trusting(executionRole), allow(target.resourceArn(), target.action())); + Map task = new LinkedHashMap<>(Map.of("Type", "Task", + "Resource", "arn:aws:states:::" + integration + ".waitForTaskToken", + "Credentials", Map.of("RoleArn", taskRole), + "Parameters", target.tokenArguments(), "TimeoutSeconds", 60, "End", true)); + + String execution = start(machine(task, executionRole), "{}"); + JsonNode delivered = target.sink().awaitJson(Duration.ofSeconds(5)); + String token = integration.contains("sns") + ? MAPPER.readTree(delivered.path("Message").asText()).path("token").asText() + : delivered.path("detail").path("token").asText(); + request("SendTaskSuccess", Map.of("taskToken", token, "output", "{\"done\":true}")).then().statusCode(200); + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void aRefusalCanBeRetriedAndCaught(String integration) throws Exception { + Target target = target(integration); + Map task = new LinkedHashMap<>(jsonPathTask(target, null)); + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 1, + "BackoffRate", 1.0, "MaxAttempts", 1))); + task.put("Catch", List.of(Map.of("ErrorEquals", List.of(target.error()), "Next", "Recovered"))); + String definition = MAPPER.writeValueAsString(Map.of("StartAt", "Send", "States", Map.of("Send", task, + "Recovered", Map.of("Type", "Pass", "End", true)))); + String execution = start(machineWithDefinition(definition, role(STATES_TRUST, READ_ONLY)), "{}"); + + Response completed = terminal(execution); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals(2, eventsOfType(execution, "TaskFailed").size()); + assertEquals(target.error(), eventsOfType(execution, "TaskFailed").getLast() + .path("taskFailedEventDetails").path("error").asText()); + } + + /** The retry decides again, so a role granted the action between attempts then delivers. */ + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "events:putEvents"}) + void aRetryDecidesAgain(String integration) throws Exception { + Target target = target(integration); + String roleName = "sfn-msg-" + UUID.randomUUID(); + String role = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", roleName, + STATES_TRUST, READ_ONLY); + Map task = new LinkedHashMap<>(jsonPathTask(target, null)); + task.put("Retry", List.of(Map.of("ErrorEquals", List.of(target.error()), "IntervalSeconds", 2, + "BackoffRate", 1.0, "MaxAttempts", 3))); + String execution = start(machine(task, role), "{}"); + + await(execution, "TaskFailed"); + given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "iam")) + .formParam("Action", "PutRolePolicy").formParam("Version", "2010-05-08") + .formParam("RoleName", roleName).formParam("PolicyName", "p").formParam("PolicyDocument", PUBLISH_ANY) + .post("/").then().statusCode(200); + Response completed = terminal(execution, 20); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertDelivered(target); + } + + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish"}) + void aSameAccountTopicPolicyGrantsARoleWithNoIdentityPermission(String integration) throws Exception { + Target target = target(integration); + String role = role(STATES_TRUST, READ_ONLY); + setTopicPolicy(target.resourceArn(), topicStatement("Allow", role, target.resourceArn())); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertDelivered(target); + } + + @ParameterizedTest + @CsvSource({"sns:publish,SNS.AuthorizationErrorException", "aws-sdk:sns:publish,Sns.AuthorizationErrorException"}) + void aTopicPolicyDenyRefusesARoleItsIdentityPolicyAllows(String integration, String error) throws Exception { + Target target = target(integration); + String role = role(STATES_TRUST, PUBLISH_ANY); + setTopicPolicy(target.resourceArn(), topicStatement("Deny", role, target.resourceArn())); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertFailed(completed, error); + assertNothingDelivered(target); + } + + @Test + void aForeignCredentialsRoleNeedsTheTopicPolicyToo() throws Exception { + Target target = target("sns:publish"); + String executionRole = role(STATES_TRUST, ASSUME); + String foreignRole = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), OTHER_ACCOUNT, "/", + "sfn-msg-" + UUID.randomUUID(), trusting(executionRole), PUBLISH_ANY); + String machine = machine(jsonPathTask(target, foreignRole), executionRole); + + Response refused = terminal(start(machine, "{}")); + + assertFailed(refused, "SNS.AuthorizationErrorException"); + String cause = refused.jsonPath().getString("cause"); + assertTrue(cause.contains("arn:aws:sts::" + OTHER_ACCOUNT + ":assumed-role/"), cause); + assertNothingDelivered(target); + + setTopicPolicy(target.resourceArn(), topicStatement("Allow", foreignRole, target.resourceArn())); + Response allowed = terminal(start(machine, "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertDelivered(target); + } + + /** Foreign without its identity half: the topic policy alone does not admit another account's role. */ + @Test + void aForeignCredentialsRoleNeedsItsIdentityPolicyToo() throws Exception { + Target target = target("sns:publish"); + String executionRole = role(STATES_TRUST, ASSUME); + String foreignRole = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), OTHER_ACCOUNT, "/", + "sfn-msg-" + UUID.randomUUID(), trusting(executionRole), READ_ONLY); + setTopicPolicy(target.resourceArn(), topicStatement("Allow", foreignRole, target.resourceArn())); + + Response completed = terminal(start(machine(jsonPathTask(target, foreignRole), executionRole), "{}")); + + assertFailed(completed, "SNS.AuthorizationErrorException"); + assertNothingDelivered(target); + } + + @Test + void aTargetArnNeedsThePermissionOnThatResource() throws Exception { + Target target = target("sns:publish"); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::sns:publish", + "Parameters", Map.of("TargetArn", target.resourceArn(), "Message", "hello"), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), "SNS.AuthorizationErrorException"); + assertNothingDelivered(target); + + Response allowed = terminal(start(machine(task, + role(STATES_TRUST, allow(target.resourceArn(), "sns:Publish"))), "{}")); + + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertDelivered(target); + } + + @Test + void anSmsNeedsThePermissionOnEveryResource() throws Exception { + Target target = target("sns:publish"); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::sns:publish", + "Parameters", Map.of("PhoneNumber", "+15555550100", "Message", "hello"), "End", true); + + assertFailed(terminal(start(machine(task, + role(STATES_TRUST, allow(target.resourceArn(), "sns:Publish"))), "{}")), "SNS.AuthorizationErrorException"); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, PUBLISH_ANY)), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + } + + /** No permission is checked, so a role with none reaches SNS, which answers with its own errors. */ + @ParameterizedTest + @CsvSource({"orders,SNS.NotFoundException", "arn:aws:sqs:us-east-1:000000000451:orders,SNS.NotFoundException", + "'',SNS.NotFoundException"}) + void aTopicArnThatIsNotAnSnsArnIsAnsweredBySns(String topicArn, String error) throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::sns:publish", + "Parameters", Map.of("TopicArn", topicArn, "Message", "hello"), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), error); + } + + @Test + void aPublishNamingNothingIsAnsweredBySns() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::sns:publish", + "Parameters", Map.of("Message", "hello"), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")), + "SNS.InvalidParameterException"); + } + + /** A statement naming the account leaves the decision to the account's IAM policies, as AWS does. */ + @Test + void anEventBusPolicyNamingTheAccountDoesNotGrantARoleWithNoIdentityPermission() throws Exception { + Target target = target("events:putEvents"); + String role = role(STATES_TRUST, READ_ONLY); + events("PutPermission", Map.of("EventBusName", busName(target.resourceArn()), "StatementId", "s", + "Action", "events:PutEvents", "Principal", ACCOUNT)); + + assertFailed(terminal(start(machine(jsonPathTask(target, null), role), "{}")), "EventBridge.AccessDeniedException"); + assertNothingDelivered(target); + } + + @Test + void aSameAccountBusPolicyNamingTheRoleGrantsItWithNoIdentityPermission() throws Exception { + Target target = target("events:putEvents"); + String role = role(STATES_TRUST, READ_ONLY); + putBusPolicy(target.resourceArn(), busStatement("Allow", role, target.resourceArn())); + + Response completed = terminal(start(machine(jsonPathTask(target, null), role), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertDelivered(target); + } + + @Test + void aBusPolicyDenyRefusesARoleItsIdentityPolicyAllows() throws Exception { + Target target = target("events:putEvents"); + String role = role(STATES_TRUST, PUBLISH_ANY); + putBusPolicy(target.resourceArn(), busStatement("Deny", role, target.resourceArn())); + + assertFailed(terminal(start(machine(jsonPathTask(target, null), role), "{}")), "EventBridge.AccessDeniedException"); + assertNothingDelivered(target); + } + + /** Another account's role needs the bus's grant as well as its own, which {@code PutPermission} gives. */ + @Test + void aForeignCredentialsRoleNeedsTheBusPolicyToo() throws Exception { + Target target = target("events:putEvents"); + String executionRole = role(STATES_TRUST, ASSUME); + String foreignRole = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), OTHER_ACCOUNT, "/", + "sfn-msg-" + UUID.randomUUID(), trusting(executionRole), PUBLISH_ANY); + String machine = machine(jsonPathTask(target, foreignRole), executionRole); + + Response refused = terminal(start(machine, "{}")); + + assertFailed(refused, "EventBridge.AccessDeniedException"); + String cause = refused.jsonPath().getString("cause"); + assertTrue(cause.contains("arn:aws:sts::" + OTHER_ACCOUNT + ":assumed-role/"), cause); + 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()); + assertDelivered(target); + } + + @Test + void aForeignCredentialsRoleNeedsItsIdentityPolicyOnABusToo() throws Exception { + Target target = target("events:putEvents"); + String executionRole = role(STATES_TRUST, ASSUME); + String foreignRole = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), OTHER_ACCOUNT, "/", + "sfn-msg-" + UUID.randomUUID(), trusting(executionRole), READ_ONLY); + events("PutPermission", Map.of("EventBusName", busName(target.resourceArn()), "StatementId", "s", + "Action", "events:PutEvents", "Principal", OTHER_ACCOUNT)); + + Response completed = terminal(start(machine(jsonPathTask(target, foreignRole), executionRole), "{}")); + + assertFailed(completed, "EventBridge.AccessDeniedException"); + assertNothingDelivered(target); + } + + @Test + void anEntryNamingNoBusNeedsThePermissionOnTheDefaultBus() throws Exception { + String name = "sfn-iam-default-" + UUID.randomUUID(); + SqsTestQueue sink = eventSink("default", name); + String defaultBus = "arn:aws:events:" + REGION + ":" + ACCOUNT + ":event-bus/default"; + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::events:putEvents", + "Parameters", Map.of("Entries", List.of(entry(null, name))), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow(defaultBus + "-other", "events:PutEvents"))), + "{}")), "EventBridge.AccessDeniedException"); + assertEquals(0, sink.receive().size()); + + Response allowed = terminal(start(machine(task, role(STATES_TRUST, allow(defaultBus, "events:PutEvents"))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertEquals(1, sink.receive().size()); + } + + /** The name and each ARN reach the same bus, whichever account the ARN names, so that bus decides. */ + @ParameterizedTest + @CsvSource({"name", "arn", "foreign-arn"}) + void aBusNamedByItsArnIsTheBusItsLookupReaches(String form) throws Exception { + Target target = target("events:putEvents"); + String name = busName(target.resourceArn()); + String given = switch (form) { + case "name" -> name; + case "arn" -> target.resourceArn(); + default -> "arn:aws:events:" + REGION + ":" + OTHER_ACCOUNT + ":event-bus/" + name; + }; + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::events:putEvents", + "Parameters", Map.of("Entries", List.of(entry(given, target.source()))), "End", true); + + assertFailed(terminal(start(machine(task, role(STATES_TRUST, allow(given + "-other", "events:PutEvents"))), "{}")), + "EventBridge.AccessDeniedException"); + assertEquals(0, target.sink().receive().size()); + + Response allowed = terminal(start(machine(task, + role(STATES_TRUST, allow(target.resourceArn(), "events:PutEvents"))), "{}")); + assertEquals("SUCCEEDED", allowed.jsonPath().getString("status"), allowed.asString()); + assertDelivered(target); + } + + /** Refused ahead of the call, so the entries for the bus the role may use are not sent either. */ + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void entriesForSeveralBusesAreRefusedWhenOneIsDenied(boolean deniedFirst) throws Exception { + Target allowedBus = target("events:putEvents"); + Target deniedBus = target("events:putEvents"); + List entries = deniedFirst + ? List.of(entry(busName(deniedBus.resourceArn()), deniedBus.source()), + entry(busName(allowedBus.resourceArn()), allowedBus.source())) + : List.of(entry(busName(allowedBus.resourceArn()), allowedBus.source()), + entry(busName(deniedBus.resourceArn()), deniedBus.source())); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::events:putEvents", + "Parameters", Map.of("Entries", entries), "End", true); + String role = role(STATES_TRUST, allow(allowedBus.resourceArn(), "events:PutEvents")); + + Response completed = terminal(start(machine(task, role), "{}")); + + assertFailed(completed, "EventBridge.AccessDeniedException"); + assertTrue(completed.jsonPath().getString("cause").contains(deniedBus.resourceArn()), completed.asString()); + assertEquals(0, allowedBus.sink().receive().size()); + assertEquals(0, deniedBus.sink().receive().size()); + } + + @Test + void anEntryEventBridgeWouldRejectStillNeedsItsBus() throws Exception { + Target allowedBus = target("events:putEvents"); + Target deniedBus = target("events:putEvents"); + Map rejected = entry(busName(deniedBus.resourceArn()), deniedBus.source()); + rejected.remove("Source"); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::events:putEvents", + "Parameters", Map.of("Entries", List.of(entry(busName(allowedBus.resourceArn()), allowedBus.source()), + rejected)), "End", true); + String role = role(STATES_TRUST, allow(allowedBus.resourceArn(), "events:PutEvents")); + + Response completed = terminal(start(machine(task, role), "{}")); + + assertFailed(completed, "EventBridge.AccessDeniedException"); + assertTrue(completed.jsonPath().getString("cause").contains(deniedBus.resourceArn()), completed.asString()); + assertEquals(0, allowedBus.sink().receive().size()); + } + + @Test + void entriesForSeveralBusesEachNeedAndGetTheirPermission() throws Exception { + Target first = target("events:putEvents"); + Target second = target("events:putEvents"); + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::events:putEvents", + "Parameters", Map.of("Entries", List.of(entry(first.resourceArn(), first.source()), + entry(busName(second.resourceArn()), second.source()))), "End", true); + String role = role(STATES_TRUST, MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", List.of( + Map.of("Effect", "Allow", "Action", "events:PutEvents", + "Resource", List.of(first.resourceArn(), second.resourceArn())))))); + + Response completed = terminal(start(machine(task, role), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + assertDelivered(first); + assertDelivered(second); + } + + /** A malformed member names no bus, so a role with no permission gets EventBridge's answer. */ + @Test + void aMalformedBusArnIsAnsweredByEventBridge() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::events:putEvents", + "Parameters", Map.of("Entries", List.of(entry("arn:aws:events:", "sfn-iam"))), "End", true); + + Response completed = terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString()); + assertNotEquals("EventBridge.AccessDeniedException", completed.jsonPath().getString("error"), completed.asString()); + } + + @Test + void noEntriesNeedNoPermission() throws Exception { + Map task = Map.of("Type", "Task", "Resource", "arn:aws:states:::events:putEvents", + "Parameters", Map.of("Entries", List.of()), "End", true); + + Response completed = terminal(start(machine(task, role(STATES_TRUST, READ_ONLY)), "{}")); + + assertEquals("SUCCEEDED", completed.jsonPath().getString("status"), completed.asString()); + } + + private static String allow(String resource, String... actions) { + try { + return MAPPER.writeValueAsString(Map.of("Version", "2012-10-17", "Statement", List.of( + Map.of("Effect", "Allow", "Action", List.of(actions), "Resource", resource)))); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static String topicStatement(String effect, String principal, String topicArn) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"%s"}, + "Action":"sns:Publish","Resource":"%s"}]} + """.formatted(effect, principal, topicArn); + } + + private static String busStatement(String effect, String principal, String busArn) { + return """ + {"Version":"2012-10-17","Statement":[{"Sid":"s","Effect":"%s","Principal":{"AWS":"%s"}, + "Action":"events:PutEvents","Resource":"%s"}]} + """.formatted(effect, principal, busArn); + } + + private void putBusPolicy(String busArn, String policy) { + events("PutPermission", Map.of("EventBusName", busName(busArn), "Policy", policy)); + } + + private static String busName(String busArn) { + return busArn.substring(busArn.lastIndexOf('/') + 1); + } + + private static Map entry(String bus, String source) { + Map entry = new LinkedHashMap<>(Map.of("Source", source, "DetailType", "t", + "Detail", Map.of("m", "hello"))); + if (bus != null) { + entry.put("EventBusName", bus); + } + return entry; + } + + private static void assertFailed(Response completed, String error) { + assertEquals("FAILED", completed.jsonPath().getString("status"), completed.asString()); + assertEquals(error, completed.jsonPath().getString("error"), completed.asString()); + } + + private static void assertDelivered(Target target) throws Exception { + JsonNode delivered = target.sink().awaitJson(Duration.ofSeconds(5)); + assertTrue(delivered.toString().contains("hello"), delivered.toString()); + } + + private static void assertNothingDelivered(Target target) { + assertEquals(0, target.sink().receive().size()); + } + + /** + * A topic or an event bus a task sends to, and the queue that receives what reaches it. + * + * @param source the event source its rule matches, for a bus + */ + private record Target(String error, String action, String resourceArn, Map arguments, + Map tokenArguments, SqsTestQueue sink, String source) { + } + + private Target target(String integration) { + return integration.contains("sns") ? topicTarget(integration.startsWith("aws-sdk") ? "Sns." : "SNS.") : busTarget(); + } + + private Target topicTarget(String errorPrefix) { + String topicArn = EnforcementFixtures.createTopic(cleanup, baseUri.getPort(), auth(ACCOUNT, "sns"), + "sfn-iam-" + UUID.randomUUID()); + SqsTestQueue sink = queue(); + given().port(baseUri.getPort()).header("Authorization", auth(ACCOUNT, "sns")) + .formParam("Action", "Subscribe").formParam("TopicArn", topicArn) + .formParam("Protocol", "sqs").formParam("Endpoint", sink.arn()) + .post("/").then().statusCode(200); + return new Target(errorPrefix + "AuthorizationErrorException", "sns:Publish", topicArn, + Map.of("TopicArn", topicArn, "Message", "hello"), + Map.of("TopicArn", topicArn, "Message", Map.of("token.$", "$$.Task.Token")), sink, null); + } + + private Target busTarget() { + String name = "sfn-iam-" + UUID.randomUUID(); + Response created = events("CreateEventBus", Map.of("Name", name)); + cleanup.register(() -> events("DeleteEventBus", Map.of("Name", name))); + String source = "sfn-iam-" + UUID.randomUUID(); + SqsTestQueue sink = eventSink(name, source); + Map tokenEntry = new LinkedHashMap<>(entry(name, source)); + tokenEntry.put("Detail", Map.of("token.$", "$$.Task.Token")); + return new Target("EventBridge.AccessDeniedException", "events:PutEvents", + created.jsonPath().getString("EventBusArn"), Map.of("Entries", List.of(entry(name, source))), + Map.of("Entries", List.of(tokenEntry)), sink, source); + } + + /** 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(); + String rule = "sfn-iam-" + UUID.randomUUID(); + events("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, + "Targets", List.of(Map.of("Id", "1", "Arn", sink.arn())))); + cleanup.register(() -> events("RemoveTargets", Map.of("Rule", rule, "EventBusName", bus, "Ids", List.of("1")))); + return sink; + } + + private Response events(String action, Map 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); + return response; + } + + private void setTopicPolicy(String topicArn, String policy) { + EnforcementFixtures.setTopicPolicy(baseUri.getPort(), auth(ACCOUNT, "sns"), topicArn, policy); + } + + private Map jsonPathTask(Target target, String taskRole) { + Map task = new LinkedHashMap<>(Map.of("Type", "Task", + "Resource", "arn:aws:states:::" + integrationOf(target), + "Parameters", target.arguments(), "End", true)); + if (taskRole != null) { + task.put("Credentials", Map.of("RoleArn", taskRole)); + } + return task; + } + + private Map jsonataTask(Target target, String roleExpression) { + Map task = new LinkedHashMap<>(Map.of("Type", "Task", "QueryLanguage", "JSONata", + "Resource", "arn:aws:states:::" + integrationOf(target), + "Arguments", target.arguments(), "End", true)); + if (roleExpression != null) { + task.put("Credentials", Map.of("RoleArn", roleExpression)); + } + return task; + } + + private static String integrationOf(Target target) { + return switch (target.error()) { + case "SNS.AuthorizationErrorException" -> "sns:publish"; + case "Sns.AuthorizationErrorException" -> "aws-sdk:sns:publish"; + default -> "events:putEvents"; + }; + } + + private SqsTestQueue queue() { + SqsTestQueue queue = SqsTestQueue.create(sqsService, ACCOUNT, REGION, "sfn-msg-iam-"); + cleanup.register(queue::delete); + return queue; + } + + private String role(String trust, String policy) { + return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", + "sfn-msg-" + UUID.randomUUID(), trust, policy); + } + + private String machine(Map task, String role) throws Exception { + return machineWithDefinition(MAPPER.writeValueAsString( + Map.of("StartAt", "Send", "States", Map.of("Send", task))), role); + } + + private String machineWithDefinition(String definition, String role) { + return sfn().createMachine(ACCOUNT, "sfn-msg-iam-", definition, "STANDARD", role); + } + + private String start(String machine, String input) { + return sfn().start(ACCOUNT, machine, input); + } + + private Response terminal(String execution) throws Exception { + return terminal(execution, 5); + } + + private Response terminal(String execution, int seconds) throws Exception { + return sfn().terminal(ACCOUNT, execution, seconds); + } + + private void await(String execution, String eventType) throws Exception { + sfn().await(ACCOUNT, execution, eventType, 5); + } + + private List eventsOfType(String execution, String type) throws Exception { + return sfn().eventsOfType(ACCOUNT, execution, type); + } + + private Response request(String action, Map input) { + return sfn().request(ACCOUNT, action, input); + } + + private StepFunctionsTestClient sfn() { + return new StepFunctionsTestClient(baseUri.getPort(), cleanup); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java index ba9213678c..1d3da9a0c2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsSqsTaskIamIntegrationTest.java @@ -27,13 +27,14 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.concurrent.TimeUnit; import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth; +import static io.github.hectorvent.floci.testing.StepFunctionsTestClient.LAMBDA_TRUST; +import static io.github.hectorvent.floci.testing.StepFunctionsTestClient.STATES_TRUST; +import static io.github.hectorvent.floci.testing.StepFunctionsTestClient.trusting; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; @QuarkusTest @TestProfile(IamEnforcementProfile.class) @@ -42,14 +43,6 @@ class StepFunctionsSqsTaskIamIntegrationTest { private static final String OTHER_ACCOUNT = "000000000442"; private static final String REGION = "us-east-1"; private static final ObjectMapper MAPPER = new ObjectMapper(); - private static final String STATES_TRUST = """ - {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", - "Principal":{"Service":"states.amazonaws.com"}}]} - """; - private static final String LAMBDA_TRUST = """ - {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", - "Principal":{"Service":"lambda.amazonaws.com"}}]} - """; private static final String SEND = allow("sqs:SendMessage"); private static final String READ_ONLY = allow("sqs:GetQueueUrl"); private static final String ASSUME = allow("sts:AssumeRole"); @@ -360,13 +353,6 @@ class StepFunctionsSqsTaskIamIntegrationTest { } } - private static String trusting(String role) { - return """ - {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", - "Principal":{"AWS":"%s"}}]} - """.formatted(role); - } - private static String queuePolicy(String effect, String principal, String queueArn) { return """ {"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"%s"}, @@ -437,14 +423,7 @@ class StepFunctionsSqsTaskIamIntegrationTest { } private void await(String execution, String eventType) throws Exception { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); - do { - if (!eventsOfType(execution, eventType).isEmpty()) { - return; - } - Thread.sleep(25); - } while (System.nanoTime() < deadline); - fail("No " + eventType + " event in " + execution); + sfn().await(ACCOUNT, execution, eventType, 5); } private List eventsOfType(String execution, String type) throws Exception { diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java index 24b260101b..b04c85124b 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsTaskCredentialsIntegrationTest.java @@ -26,6 +26,7 @@ import org.junit.jupiter.params.provider.ValueSource; import java.net.URI; import java.nio.charset.StandardCharsets; +import java.util.List; import java.util.Map; import java.util.UUID; @@ -235,6 +236,26 @@ 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. */ + @ParameterizedTest + @ValueSource(strings = {"sns:publish", "aws-sdk:sns:publish", "events:putEvents"}) + void messagingCredentialsRetainDefaultIamDisabledBehavior(String integration) throws Exception { + Map arguments = integration.contains("sns") + ? 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 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)))); + + String execution = start(machine(SOURCE, definition, "STANDARD"), "{}"); + Response done = terminal(SOURCE, execution); + + assertEquals("SUCCEEDED", done.jsonPath().getString("status"), done.asString()); + assertEquals(taskRole, taskScheduled(execution).path("taskCredentials").path("roleArn").asText()); + } + @Test void credentialsThatDoNotResolveStillPassWithEnforcementOff() throws Exception { SqsTestQueue queue = SqsTestQueue.create(sqsService, SOURCE, "us-east-1", "credentials-"); diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissionsTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissionsTest.java index cf74b33ca6..f18aef914a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissionsTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/TaskPermissionsTest.java @@ -19,6 +19,8 @@ class TaskPermissionsTest { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String ACCOUNT = "111122223333"; + private static final String TOPIC = "arn:aws:sns:eu-west-1:111122223333:orders"; + private static final String ENDPOINT = "arn:aws:sns:eu-west-1:111122223333:endpoint/GCM/app/id"; /** Each form resolves in the state machine's Region, whichever host it names, as the queue lookup does. */ @ParameterizedTest @@ -30,7 +32,7 @@ class TaskPermissionsTest { "444455556666/orders, 444455556666", "http://localhost:4566/not-an-account/orders, 111122223333"}) void aQueueUrlNamesTheQueueItsLookupReaches(String queueUrl, String account) { - assertEquals(new TaskPermissions("SQS.", List.of(new Permission("sqs:SendMessage", + assertEquals(new TaskPermissions("SQS.AccessDeniedException", List.of(new Permission("sqs:SendMessage", "arn:aws:sqs:eu-west-1:" + account + ":orders"))), TaskPermissions.of(integration("sqs:sendMessage"), input(queueUrl), machine("aws")).orElseThrow()); } @@ -44,25 +46,144 @@ class TaskPermissionsTest { @Test void theSdkFormNamesItsOwnErrorPrefix() { - assertEquals("Sqs.", TaskPermissions.of(integration("aws-sdk:sqs:sendMessage"), input("orders"), machine("aws")) - .orElseThrow().errorPrefix()); + assertEquals("Sqs.AccessDeniedException", TaskPermissions.of(integration("aws-sdk:sqs:sendMessage"), + input("orders"), machine("aws")).orElseThrow().deniedError()); } /** SQS answers these with its own validation error once the role has passed. */ @ParameterizedTest @ValueSource(strings = {"{}", "{\"QueueUrl\":\" \"}", "{\"QueueUrl\":7}"}) void aRequestNamingNoQueueNeedsNoPermission(String request) throws Exception { - assertEquals(new TaskPermissions("SQS.", List.of()), + assertEquals(new TaskPermissions("SQS.AccessDeniedException", List.of()), TaskPermissions.of(integration("sqs:sendMessage"), MAPPER.readTree(request), machine("aws")).orElseThrow()); } @ParameterizedTest - @ValueSource(strings = {"lambda:invoke", "apigateway:invoke", "sns:publish", "aws-sdk:sqs:receiveMessage", - "states:startExecution", "dynamodb:putItem", "http:invoke"}) + @ValueSource(strings = {"lambda:invoke", "apigateway:invoke", "aws-sdk:sqs:receiveMessage", "aws-sdk:sns:listTopics", + "sns:publishBatch", "aws-sdk:eventbridge:putEvents", "events:listRules", "states:startExecution", + "dynamodb:putItem", "http:invoke"}) void integrationsNotMappedStayUnchecked(String integration) { assertEquals(Optional.empty(), TaskPermissions.of(integration(integration), input("orders"), machine("aws"))); } + @ParameterizedTest + @CsvSource({"sns:publish,SNS.AuthorizationErrorException", "aws-sdk:sns:publish,Sns.AuthorizationErrorException"}) + void aPublishNeedsThePermissionOnItsTopicAndIsRefusedAsSnsRefuses(String integration, String deniedError) throws Exception { + assertEquals(new TaskPermissions(deniedError, List.of(new Permission("sns:Publish", TOPIC))), + TaskPermissions.of(integration(integration), json("{\"TopicArn\":\"" + TOPIC + "\"}"), machine("aws")) + .orElseThrow()); + } + + @Test + void aPublishToATargetNeedsThePermissionOnTheTarget() throws Exception { + assertEquals(List.of(new Permission("sns:Publish", ENDPOINT)), snsPermissions("{\"TargetArn\":\"" + ENDPOINT + "\"}")); + } + + /** {@code SnsService.publish} takes the topic before the target, so that is what it sends to. */ + @Test + void aPublishNamingBothNeedsThePermissionOnTheTopic() throws Exception { + assertEquals(List.of(new Permission("sns:Publish", TOPIC)), + snsPermissions("{\"TargetArn\":\"" + ENDPOINT + "\",\"TopicArn\":\"" + TOPIC + "\"}")); + assertEquals(List.of(new Permission("sns:Publish", ENDPOINT)), + snsPermissions("{\"TopicArn\":null,\"TargetArn\":\"" + ENDPOINT + "\"}")); + } + + /** {@code SnsService.publish} takes a phone number before any ARN, so a topic in the request is not reached. */ + @ParameterizedTest + @ValueSource(strings = {"{\"PhoneNumber\":\"+15555550100\"}", + "{\"PhoneNumber\":\"+15555550100\",\"TopicArn\":\"" + TOPIC + "\"}"}) + void anSmsNeedsThePermissionOnAnyResource(String request) throws Exception { + assertEquals(List.of(new Permission("sns:Publish", "*")), snsPermissions(request)); + } + + /** SNS answers these with its own error once the role has passed: none of them reaches a topic. */ + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"TopicArn\":\"orders\"}", "{\"TopicArn\":\"\"}", "{\"TopicArn\":7}", + "{\"TopicArn\":\"arn:aws:sns\"}", "{\"TopicArn\":\"arn:aws:sqs:eu-west-1:111122223333:orders\"}", + "{\"TargetArn\":\"orders\"}", "{\"PhoneNumber\":null}", + "{\"TopicArn\":\"orders\",\"TargetArn\":\"" + ENDPOINT + "\"}"}) + void aPublishNamingNoSnsResourceNeedsNoPermission(String request) throws Exception { + assertEquals(List.of(), snsPermissions(request)); + } + + @Test + void anEntryNamingNoBusNeedsThePermissionOnTheDefaultBus() throws Exception { + assertEquals(new TaskPermissions("EventBridge.AccessDeniedException", List.of(new Permission("events:PutEvents", bus("default")))), + TaskPermissions.of(integration("events:putEvents"), json("{\"Entries\":[{\"Source\":\"a\"}]}"), + machine("aws")).orElseThrow()); + } + + /** Each form reaches the bus of that name where the call runs, whichever account and Region an ARN names. */ + @ParameterizedTest + @CsvSource({ + "orders, orders", + "arn:aws:events:eu-west-1:111122223333:event-bus/orders, orders", + "arn:aws-cn:events:cn-north-1:444455556666:event-bus/orders, orders", + "arn:aws:events:eu-west-1:111122223333:event-bus/default, default", + "'', default", + "' ', default", + "arn:aws:s3:::orders, arn:aws:s3:::orders"}) + void aBusNameOrArnNamesTheBusItsLookupReaches(String busName, String reached) throws Exception { + assertEquals(List.of(new Permission("events:PutEvents", bus(reached))), + eventsPermissions(MAPPER.writeValueAsString(Map.of("Entries", List.of(Map.of("EventBusName", busName)))))); + } + + @Test + void aNullOrNonTextBusIsReadAsTheHandlerReadsIt() throws Exception { + assertEquals(List.of(new Permission("events:PutEvents", bus("default"))), + eventsPermissions("{\"Entries\":[{\"EventBusName\":null},{\"EventBusName\":{\"a\":1}}]}")); + assertEquals(List.of(new Permission("events:PutEvents", bus("7"))), + eventsPermissions("{\"Entries\":[{\"EventBusName\":7}]}")); + } + + @Test + void entriesNeedOnePermissionForEachDistinctBusInOrder() throws Exception { + assertEquals(List.of(new Permission("events:PutEvents", bus("b")), new Permission("events:PutEvents", bus("default")), + new Permission("events:PutEvents", bus("a"))), + eventsPermissions("{\"Entries\":[{\"EventBusName\":\"b\"},{},{\"EventBusName\":\"a\"}," + + "{\"EventBusName\":\"" + bus("b") + "\"},{\"EventBusName\":\"default\"}]}")); + } + + @Test + void theBusIsInTheStateMachinesPartition() throws Exception { + assertEquals(List.of(new Permission("events:PutEvents", + "arn:aws-cn:events:eu-west-1:" + ACCOUNT + ":event-bus/default")), + TaskPermissions.of(integration("events:putEvents"), json("{\"Entries\":[{}]}"), machine("aws-cn")) + .orElseThrow().permissions()); + } + + /** A malformed member names no bus, so EventBridge answers it, and the others are still checked. */ + @ParameterizedTest + @ValueSource(strings = {"{}", "{\"Entries\":[]}", "{\"Entries\":{\"EventBusName\":\"a\"}}", "{\"Entries\":{\"x\":{\"EventBusName\":\"a\"}}}", "{\"Entries\":\"a\"}", + "{\"Entries\":[7]}", "{\"Entries\":[[{\"EventBusName\":\"a\"}]]}", + "{\"Entries\":[{\"EventBusName\":\"arn:aws:events:\"}]}", + "{\"Entries\":[{\"EventBusName\":\"arn:aws:events:eu-west-1:111122223333:rule/orders\"}]}"}) + void entriesNamingNoBusNeedNoPermission(String request) throws Exception { + assertEquals(List.of(), eventsPermissions(request)); + } + + @Test + void aMalformedEntryLeavesTheOthersChecked() throws Exception { + assertEquals(List.of(new Permission("events:PutEvents", bus("a"))), + eventsPermissions("{\"Entries\":[7,{\"EventBusName\":\"arn:aws:events:\"},{\"EventBusName\":\"a\"}]}")); + } + + private static List snsPermissions(String request) throws Exception { + return TaskPermissions.of(integration("sns:publish"), json(request), machine("aws")).orElseThrow().permissions(); + } + + private static List eventsPermissions(String request) throws Exception { + return TaskPermissions.of(integration("events:putEvents"), json(request), machine("aws")).orElseThrow().permissions(); + } + + private static String bus(String name) { + return "arn:aws:events:eu-west-1:" + ACCOUNT + ":event-bus/" + name; + } + + private static JsonNode json(String request) throws Exception { + return MAPPER.readTree(request); + } + private static StatesIntegration integration(String tail) { return StatesIntegration.parse("arn:aws:states:::" + tail).orElseThrow(); } diff --git a/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsTestClient.java b/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsTestClient.java index 484d60a399..f8902f52a3 100644 --- a/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsTestClient.java +++ b/src/test/java/io/github/hectorvent/floci/testing/StepFunctionsTestClient.java @@ -17,6 +17,17 @@ import static org.junit.jupiter.api.Assertions.fail; /** Step Functions calls a test makes as one account, and the state machines it leaves to {@code cleanup}. */ public final class StepFunctionsTestClient { + /** A trust policy letting Step Functions assume the role: what an execution role needs. */ + public static final String STATES_TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"states.amazonaws.com"}}]} + """; + /** A trust policy naming another service, so Step Functions may not assume the role. */ + public static final String LAMBDA_TRUST = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"Service":"lambda.amazonaws.com"}}]} + """; + private static final ObjectMapper MAPPER = new ObjectMapper(); private static final long POLL_MILLIS = 25; @@ -66,6 +77,18 @@ public final class StepFunctionsTestClient { return null; } + /** Polls until the execution's history holds an event of {@code eventType}. */ + public void await(String account, String execution, String eventType, int seconds) throws Exception { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds); + do { + if (!eventsOfType(account, execution, eventType).isEmpty()) { + return; + } + Thread.sleep(POLL_MILLIS); + } while (System.nanoTime() < deadline); + fail("No " + eventType + " event in " + execution); + } + public List eventsOfType(String account, String execution, String type) throws Exception { Response history = request(account, "GetExecutionHistory", Map.of("executionArn", execution)); history.then().statusCode(200); @@ -78,6 +101,14 @@ public final class StepFunctionsTestClient { return events; } + /** A trust policy letting {@code roleArn} assume the role, as a task's {@code Credentials} role needs. */ + public static String trusting(String roleArn) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole", + "Principal":{"AWS":"%s"}}]} + """.formatted(roleArn); + } + private void removeMachine(String account, String arn) { Response executions = request(account, "ListExecutions", Map.of("stateMachineArn", arn)); if (executions.statusCode() == 200) {