diff --git a/README.md b/README.md index 4b8bf1a245..48b5aa2eaf 100644 --- a/README.md +++ b/README.md @@ -297,7 +297,7 @@ Floci supports local emulation for application services, data services, eventing | Category | Services | |---|---| | Core app services | S3, SQS, SNS, DynamoDB, Lambda, Lambda MicroVMs, Lambda Web Functions, IAM, STS, KMS, Secrets Manager, SSM | -| Events and workflows | EventBridge, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch OAM, CloudWatch RUM, Managed Prometheus (AMP) | +| Events and workflows | EventBridge, EventBridge V2, EventBridge Pipes, EventBridge Scheduler, Step Functions, SWF, CloudWatch Logs, CloudWatch Metrics, CloudWatch OAM, CloudWatch RUM, Managed Prometheus (AMP) | | API and identity | API Gateway REST, API Gateway v2, AppSync, Cognito, Cognito Identity, ACM, Route53, Route 53 Resolver, Cloud Map, Global Accelerator | | Containers and compute | ECS, EC2, Lightsail, EKS, MWAA, ECR, EFS, CodeBuild, CodeDeploy, CodePipeline, CodeGuru Reviewer, CodeArtifact, AWS Batch, Auto Scaling, Application Auto Scaling, Elastic Beanstalk, ELB v2, ELB Classic | | Data, analytics, and AI | Athena, Glue, Lake Formation, EMR, EMR Serverless, Redshift, Redshift Data API, Redshift Serverless, Firehose, Managed Service for Apache Flink, OpenSearch, S3 Tables, S3 Vectors, Textract, Transcribe, Comprehend, Rekognition, Translate, Bedrock, Bedrock Runtime, Bedrock AgentCore, Bedrock AgentCore Control, SageMaker | @@ -333,6 +333,7 @@ For operation-level compatibility, see the [Services Overview](https://floci.io/ | SWF | In-process | Decision and activity tasks, timers, child workflows, timeouts, real Lambda invocation | | CloudFormation | In-process | Stacks, change sets, resource provisioning, StackSets (cross-account instances) | | EventBridge | In-process | Custom buses, rules, SQS, SNS and Lambda targets | +| EventBridge V2 | In-process | Event buses and filtered subscribers delivering to SQS | | EventBridge Pipes | In-process | Poller-based integration connecting SQS, Kinesis, DynamoDB, and MSK sources to targets with optional filtering | | EventBridge Scheduler | In-process | Schedule groups, schedules, flexible time windows, retry policies, DLQs | | CloudWatch Logs | In-process | Log groups, streams, ingestion, filtering | diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 28924d1ba8..3c2a04dfff 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -257,6 +257,11 @@ software.amazon.awssdk eventbridge + + + software.amazon.awssdk + eventbridgev2 + software.amazon.awssdk diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index 3bb1ed5b40..95d674b958 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -66,6 +66,7 @@ import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalanci import software.amazon.awssdk.services.emr.EmrClient; import software.amazon.awssdk.services.emrserverless.EmrServerlessClient; import software.amazon.awssdk.services.eventbridge.EventBridgeClient; +import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; import software.amazon.awssdk.services.firehose.FirehoseClient; import software.amazon.awssdk.services.fis.FisClient; import software.amazon.awssdk.services.globalaccelerator.GlobalAcceleratorClient; @@ -1166,6 +1167,14 @@ public final class TestFixtures { .build(); } + public static EventBridgeV2Client eventBridgeV2Client() { + return EventBridgeV2Client.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .build(); + } + public static ServiceDiscoveryClient serviceDiscoveryClient() { return ServiceDiscoveryClient.builder() .endpointOverride(ENDPOINT) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EventBridgeV2Test.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EventBridgeV2Test.java new file mode 100644 index 0000000000..341e7adabb --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/EventBridgeV2Test.java @@ -0,0 +1,108 @@ +package com.floci.test; + +import org.jboss.logging.Logger; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; +import software.amazon.awssdk.services.eventbridgev2.model.BusState; +import software.amazon.awssdk.services.eventbridgev2.model.CreateEventBusResponse; +import software.amazon.awssdk.services.eventbridgev2.model.FilterScope; +import software.amazon.awssdk.services.eventbridgev2.model.InvalidInputException; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceAlreadyExistsException; +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.Message; +import software.amazon.awssdk.services.sqs.model.QueueAttributeName; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assumptions.assumeFalse; + +@DisplayName("EventBridge V2 event buses") +class EventBridgeV2Test { + + private static final Logger LOG = Logger.getLogger(EventBridgeV2Test.class); + + @Test + @DisplayName("CreateEventBus returns an event-busv2 ARN and refuses a second bus of the same name") + void createEventBus() { + String name = TestFixtures.uniqueName("sdk-busv2"); + try (EventBridgeV2Client client = TestFixtures.eventBridgeV2Client()) { + String arn = null; + try { + CreateEventBusResponse created = client.createEventBus(request -> request.name(name) + .description("Order events") + .storageConfiguration(storage -> storage.retentionPeriodInDays(7)) + .tags(Map.of("team", "orders"))); + arn = created.eventBusArn(); + + assertThat(arn).matches("arn:aws[a-z-]*:events:[a-z0-9-]+:\\d{12}:event-busv2/" + name + "/[a-z0-9]{25}"); + assertThat(created.name()).isEqualTo(name); + assertThat(created.description()).isEqualTo("Order events"); + assertThat(created.storageConfiguration().retentionPeriodInDays()).isEqualTo(7); + assertThat(created.state()).isIn(BusState.CREATING, BusState.ACTIVE); + assertThat(created.creationTime()).isBefore(Instant.now().plusSeconds(60)); + + assertThatThrownBy(() -> client.createEventBus(request -> request.name(name))) + .isInstanceOf(ResourceAlreadyExistsException.class); + } finally { + deleteBestEffort(client, arn); + } + } + } + + @Test + @DisplayName("CreateEventBus refuses an invalid name") + void createEventBusRejectsAnInvalidName() { + try (EventBridgeV2Client client = TestFixtures.eventBridgeV2Client()) { + assertThatThrownBy(() -> client.createEventBus(request -> request.name("not a valid name"))) + .isInstanceOf(InvalidInputException.class); + } + } + + @Test + @DisplayName("A subscriber delivers the events its FilterConfiguration matches to an SQS queue") + void subscriberDeliversFilteredEventsToSqs() throws Exception { + assumeFalse(TestFixtures.isRealAws(), "Needs a delivery role with sqs:SendMessage on real AWS"); + String suffix = TestFixtures.uniqueName("busv2"); + try (EventBridgeV2Client events = TestFixtures.eventBridgeV2Client(); + SqsClient sqs = TestFixtures.sqsClient()) { + String queueUrl = sqs.createQueue(request -> request.queueName(suffix)).queueUrl(); + String queueArn = sqs.getQueueAttributes(request -> request.queueUrl(queueUrl) + .attributeNames(QueueAttributeName.QUEUE_ARN)).attributes().get(QueueAttributeName.QUEUE_ARN); + String bus = events.createEventBus(request -> request.name(suffix)).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("large-orders").eventBusArn(bus) + .invokeConfiguration(invoke -> invoke.targetArn(queueArn) + .roleArn("arn:aws:iam::000000000000:role/EventBusDelivery")) + .filterConfiguration(filters -> filters.filters(filter -> filter.scope(FilterScope.DATA) + .pattern("{\"detail\":{\"total\":[{\"numeric\":[\">\",500]}]}}")))).subscriberArn(); + try { + events.putEvents(request -> request.eventBusArn(bus).entries( + entry -> entry.source("com.shop").detailType("Order Placed").detail("{\"total\":750}"), + entry -> entry.source("com.shop").detailType("Order Placed").detail("{\"total\":5}"))); + + List messages = sqs.receiveMessage(request -> request.queueUrl(queueUrl) + .maxNumberOfMessages(10).waitTimeSeconds(2)).messages(); + assertThat(messages).hasSize(1); + assertThat(messages.get(0).body()).contains("\"total\":750").contains("\"detail-type\":\"Order Placed\""); } finally { + events.deleteSubscriber(request -> request.subscriberArn(subscriber)); + events.deleteEventBus(request -> request.eventBusArn(bus)); + sqs.deleteQueue(request -> request.queueUrl(queueUrl)); + } + } + } + + private static void deleteBestEffort(EventBridgeV2Client client, String arn) { + if (arn == null) { + return; + } + try { + client.deleteEventBus(request -> request.eventBusArn(arn)); + } catch (Exception cleanupError) { + LOG.warnv(cleanupError, "Best-effort cleanup failed for eventBusArn={0}", arn); + } + } +} diff --git a/docs/services/eventbridgev2.md b/docs/services/eventbridgev2.md new file mode 100644 index 0000000000..191feb3482 --- /dev/null +++ b/docs/services/eventbridgev2.md @@ -0,0 +1,135 @@ +# EventBridge V2 + +**Protocol:** Smithy RPC v2 CBOR (`smithy-protocol: rpc-v2-cbor`) +**Endpoint:** `POST http://localhost:4566/service/AWSEventsV2/operation/` + +EventBridge V2 is a separate service from [EventBridge](eventbridge.md). Its event buses are +`event-busv2` resources, `arn:aws:events:::event-busv2//`, which accept +events and deliver each one to every subscriber whose filters it matches. It signs requests with the +same `events` name as EventBridge, but nothing is shared between the two: a V2 bus is not visible to +EventBridge's `ListEventBuses`, and the reverse holds as well. + +The AWS CLI calls it `aws eventsv2` and the SDKs `EventBridgeV2`. + +## Supported Actions + + +| Action | Description | +| --- | --- | +| `CreateEventBus` | Create an event bus, with an optional description, KMS key, retention period, and tags | +| `DescribeEventBus` | Return an event bus's name, description, configuration, state and times | +| `DeleteEventBus` | Delete an event bus that has no subscribers | +| `ListEventBuses` | List the Region's event buses in name order, filtered by name prefix, a page at a time | +| `CreateSubscriber` | Create a subscriber that delivers the events its filters match to an Amazon SQS queue | +| `DescribeSubscriber` | Return a subscriber's target, filters, transformer, delivery settings, state and times | +| `ListSubscribers` | List the Region's subscribers, or one event bus's, filtered by name prefix, a page at a time | +| `UpdateSubscriber` | Change a subscriber's settings, keeping those the request leaves out | +| `DeleteSubscriber` | Delete a subscriber | +| `PutEvents` | Publish events in the EventBridge envelope to an event bus | + + +Every other EventBridge V2 operation answers `UnsupportedOperation`. + +## Event buses + +- A new bus is `ACTIVE` at once. AWS creates it in the `CREATING` state first; the `EventBusActive` + waiter accepts either. +- A bus name is unique per account and Region. Creating one that exists fails with + `ResourceAlreadyExistsException`. +- A retried `CreateEventBus` or `CreateSubscriber` with the same `ClientToken` returns what the first + call created. The same token with a different request fails with `IdempotentParameterMismatchException`. +- `DeleteEventBus` fails with `ResourceInUseException` while the bus has subscribers. +- `ListEventBuses` lists only your own buses. Floci does not share buses across accounts, so an + `EventBusAccountId` naming another account lists none. +- `EncryptionConfiguration.KmsKeyIdentifier` is stored and returned as given. AWS returns the key's ARN. +- `StorageConfiguration.RetentionPeriodInDays` is stored and returned. No default retention period + is applied when it is omitted, and `RetentionWindowStartTime` is not returned. Events are not + retained, so they cannot be replayed. + +## Subscribers and filters + +A subscriber delivers each event to one target. Floci delivers to an **Amazon SQS queue** in your +account. Any other target type is refused with `InvalidInputException`, as is a parameter block other +than `SqsParameters`. + +`FilterConfiguration.Filters` holds at most one EventBridge pattern for each scope, and an event must +match every filter. A subscriber without a `FilterConfiguration` receives every event on the bus. + +| Scope | Matches against | +| --- | --- | +| `DATA` | The event data. For `PutEvents`, the EventBridge envelope, with your `Detail` under `detail` | +| `METADATA` | The producer's metadata. Exact values only. A `PutEvents` event has none | +| `SYSTEM_METADATA` | The fields EventBridge sets: `ContentType` (`application/eventbridge+json`), `EventGroupId`, `DeduplicationId`, `aws:EventId`, `aws:IngestionTime`, `aws:SequenceNumber`, `aws:DeliveryType`, `aws:Source`, `aws:DetailType` | + +Patterns support exact values, `prefix`, `suffix`, `equals-ignore-case`, `anything-but`, `numeric`, +`exists` and `$or`. As on AWS, a wildcard is rejected, as are two filters of one scope and patterns +over 4,096 bytes in all, a field given a single value rather than a list, and a `numeric` matcher +whose operators or operands are not comparisons and numbers. A pattern naming fields the event does not +have is not an error; it matches nothing. +A matcher Floci does not evaluate, such as `cidr` or `anything-but` with `numeric`, is refused with +`InvalidInputException` when the subscriber is created or updated, where AWS would accept it. + +### Delivery + +- `Transformer.Type` `RAW`, the default, sends the event data as the message body: for `PutEvents`, + the envelope. `WITH_METADATA` sends `{"Data": ..., "Metadata": ..., "SystemMetadata": ...}`. + A `JSONATA` transformer is refused. +- `SqsParameters` (`MessageGroupId`, `MessageDeduplicationId`, `DelaySeconds`, `MessageAttributes`) + take a literal, or an expression that is a path into the event, such as + `{% $events.SystemMetadata.EventGroupId %}` or `{% $events.SystemMetadata."aws:EventId" %}`. Other + JSONata is refused when the subscriber is created. +- Delivery is immediate, one message per event, in the bus's sequence order, also across concurrent + `PutEvents` requests. A delivery that fails, for example to a queue that + does not exist, is logged and the event is dropped: `RetryPolicy` and `OnFailureConfiguration` are + stored but not applied, and neither is `BatchConfiguration`. +- A `STOPPED` subscriber receives nothing. `StartingPosition` `POINT_IN_TIME` is stored but delivers + from the latest event, since events are not retained. +- The `RoleArn` is checked for shape only; delivery does not assume it. + +### Updating a subscriber + +`UpdateSubscriber` changes only the settings the request gives. Its `InvokeConfiguration` replaces the role and +the target parameters but has no `TargetArn`: a subscriber keeps its target. An update is checked as a whole, so a +request with one invalid setting changes nothing. `ResumePosition` is accepted and has no effect, since events are +not retained. `DescribeSubscriber` and `ListSubscribers` always report `Revoked` as `false`. + +## IAM + +Under IAM enforcement, EventBridge V2 operations are authorized as the `events` actions of the same +name, as on AWS, and checked on the resource their request names: `PutEvents`, `DescribeEventBus` +and `DeleteEventBus` on the `event-busv2` ARN in `EventBusArn`, the subscriber operations on the +`subscriber` ARN in `SubscriberArn`, and `CreateSubscriber` on its bus and on +`subscriber//*`, and `CreateEventBus` on `event-busv2//*`. A V2 request is never +checked on the default [EventBridge](eventbridge.md) bus. + +Where the two APIs share an operation name, the API serving the request decides which resource is +checked, not the members the request gives. An EventBridge request that adds a V2 bus's +`EventBusArn` is still checked on the EventBridge bus it acts on. + +## Configuration + +| Variable | Default | Description | +|---|---|---| +| `FLOCI_SERVICES_EVENTBRIDGEV2_ENABLED` | `true` | Enable or disable the service | + +## Example + +```bash +export AWS_ENDPOINT_URL=http://localhost:4566 + +QUEUE_URL=$(aws sqs create-queue --queue-name large-orders --query QueueUrl --output text) +QUEUE_ARN=$(aws sqs get-queue-attributes --queue-url "$QUEUE_URL" \ + --attribute-names QueueArn --query Attributes.QueueArn --output text) +BUS_ARN=$(aws eventsv2 create-event-bus --name orders --query EventBusArn --output text) + +aws eventsv2 create-subscriber \ + --name large-orders \ + --event-bus-arn "$BUS_ARN" \ + --invoke-configuration "{\"TargetArn\":\"$QUEUE_ARN\",\"RoleArn\":\"arn:aws:iam::000000000000:role/EventBusDelivery\"}" \ + --filter-configuration '{"Filters":[{"Scope":"DATA","Pattern":"{\"detail\":{\"total\":[{\"numeric\":[\">\",500]}]}}"}]}' + +aws eventsv2 put-events --event-bus-arn "$BUS_ARN" \ + --entries '[{"Source":"com.shop","DetailType":"Order Placed","Detail":"{\"total\":750}"}]' + +aws sqs receive-message --queue-url "$QUEUE_URL" +``` diff --git a/docs/services/index.md b/docs/services/index.md index 81bd38cc89..908ebeef60 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -40,6 +40,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudFormation](cloudformation.md) | `POST /` with `Action=` param | Query | 36 | | [Cloud Control API](cloudcontrol.md) | `POST /` + `X-Amz-Target: CloudApiService.*` | JSON 1.1 | 5 | | [EventBridge](eventbridge.md) | `POST /` + `X-Amz-Target: AmazonEventBridge.*` | JSON 1.1 | 40 | +| [EventBridge V2](eventbridgev2.md) | `POST /service/AWSEventsV2/operation/*` | Smithy RPC v2 CBOR | 10 | | [EventBridge Scheduler](scheduler.md) | `/schedules/*`, `/schedule-groups/*`, `/tags/*` | REST JSON | 12 | | [EventBridge Pipes](pipes.md) | `/v1/pipes/*` | REST JSON | 7 | | [CloudWatch OAM](oam.md) | REST paths such as `POST /CreateSink` and `POST /CreateLink` | REST JSON | 15 | diff --git a/docs/services/lambda.md b/docs/services/lambda.md index b19bd23f50..1572c2254a 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -1316,17 +1316,20 @@ of `{}` or with an empty `Filters` array clears any existing filters. !!! note "Supported operators" Filtering reuses Floci's shared EventBridge matcher (the same one EventBridge - Pipes uses). It supports exact match on a string, number or `null`, plus - `prefix`, `suffix`, `equals-ignore-case`, `exists`, `anything-but` (a string, - a non-empty array of strings and numbers, or a nested `prefix`), and `numeric` - comparison/value pairs using `=`, `>`, `>=`, `<`, `<=`. Patterns using only - these behave as on AWS. + Pipes and EventBridge V2 use). It supports exact match on a string, number, + boolean or `null`, plus `prefix`, `suffix`, `equals-ignore-case`, `exists`, + `anything-but` (a string, a non-empty array of strings and numbers, or a nested + `prefix`), `numeric` comparison/value pairs using `=`, `>`, `>=`, `<`, `<=`, + and `$or`. Patterns using only these behave as on AWS. As on AWS, `[null]` + matches a field whose value is `null`, not a missing one (use + `[{"exists": false}]` for that), `anything-but` does not match a missing + field, and a record field that is an array matches when any element does. A pattern is validated at `CreateEventSourceMapping` and `UpdateEventSourceMapping` and rejected with `InvalidParameterValueException` when the matcher could not satisfy it: an unknown operator, an operator AWS documents that Floci does not implement (`cidr`, `wildcard`), more than one - operator in a single match element, a boolean literal, a wrong operand type, + operator in a single match element, a wrong operand type, or a malformed `numeric` sequence such as an odd-length array or a non-numeric value. This is stricter than AWS, which accepts several of these. The trade is deliberate: the pollers checkpoint past (Kinesis, DynamoDB) or @@ -1334,11 +1337,6 @@ of `{}` or with an empty `Filters` array clears any existing filters. match destroys records rather than being inert, and create time is the last point at which the caller can still act on it. - One matcher deviation remains and is not a validation error, because it - depends on the record rather than the pattern: event-value array intersection, - where AWS matches when the record's own field is itself an array and any - element satisfies the pattern, and Floci does not. - !!! warning "SAM event sources" CloudFormation `AWS::Lambda::EventSourceMapping` resources forward `FilterCriteria`, `MaximumBatchingWindowInSeconds`, `ScalingConfig` and diff --git a/mkdocs.yml b/mkdocs.yml index 872dfd948c..4088f65317 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -157,6 +157,7 @@ nav: - Redshift Serverless: services/redshift-serverless.md - Data Firehose: services/firehose.md - EventBridge: services/eventbridge.md + - EventBridge V2: services/eventbridgev2.md - EventBridge Pipes: services/pipes.md - EventBridge Scheduler: services/scheduler.md - CloudWatch: services/cloudwatch.md diff --git a/pom.xml b/pom.xml index ab3c1f12a1..cbaab3c903 100644 --- a/pom.xml +++ b/pom.xml @@ -372,6 +372,12 @@ ${aws.sdk.version} test + + software.amazon.awssdk + eventbridgev2 + ${aws.sdk.version} + test + software.amazon.awssdk iotdataplane diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java index ac99fa2376..150f887c22 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -763,6 +763,7 @@ public interface EmulatorConfig { RedshiftDataServiceConfig redshiftData(); RedshiftServerlessServiceConfig redshiftServerless(); EventBridgeServiceConfig eventbridge(); + EventBridgeV2ServiceConfig eventbridgev2(); CloudMapServiceConfig cloudmap(); EmrServiceConfig emr(); WafV2ServiceConfig wafv2(); @@ -1989,6 +1990,11 @@ public interface EmulatorConfig { boolean enabled(); } + interface EventBridgeV2ServiceConfig { + @WithDefault("true") + boolean enabled(); + } + interface CloudMapServiceConfig { @WithDefault("true") boolean enabled(); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java index fd382dc77e..c19f8af0df 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsJsonCborController.java @@ -12,6 +12,7 @@ import com.google.gson.JsonParseException; import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsJsonHandler; import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler; import io.github.hectorvent.floci.services.dynamodb.DynamoDbStreamsJsonHandler; +import io.github.hectorvent.floci.services.eventbridgev2.EventBridgeV2Handler; import io.github.hectorvent.floci.services.kinesis.KinesisJsonHandler; import io.github.hectorvent.floci.services.marketplace.MarketplaceEntitlementController; import io.github.hectorvent.floci.services.sns.SnsJsonHandler; @@ -34,6 +35,7 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.zip.GZIPInputStream; /** @@ -41,7 +43,7 @@ import java.util.zip.GZIPInputStream; * via either smithy-rpc-v2-cbor path routing or the legacy X-Amz-Target header. *

* Currently supported services: DynamoDB (incl. Streams), SQS, SNS, Kinesis, - * Step Functions, and CloudWatch Metrics. + * Step Functions, CloudWatch Metrics, and EventBridge V2. *

* Requests run on virtual threads, as in {@link AwsJsonController}, so a ReceiveMessage or * GetActivityTask long poll does not hold one of the shared request workers while it waits. @@ -69,6 +71,7 @@ public class AwsJsonCborController { private final StepFunctionsJsonHandler sfnJsonHandler; private final CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler; private final MarketplaceEntitlementController marketplaceEntitlementController; + private final EventBridgeV2Handler eventBridgeV2Handler; @Inject public AwsJsonCborController(ObjectMapper objectMapper, ResolvedServiceCatalog catalog, @@ -79,7 +82,8 @@ public class AwsJsonCborController { KinesisJsonHandler kinesisJsonHandler, StepFunctionsJsonHandler sfnJsonHandler, CloudWatchMetricsJsonHandler cloudWatchMetricsJsonHandler, - MarketplaceEntitlementController marketplaceEntitlementController) { + MarketplaceEntitlementController marketplaceEntitlementController, + EventBridgeV2Handler eventBridgeV2Handler) { this.objectMapper = objectMapper; this.catalog = catalog; this.regionResolver = regionResolver; @@ -91,6 +95,7 @@ public class AwsJsonCborController { this.sfnJsonHandler = sfnJsonHandler; this.cloudWatchMetricsJsonHandler = cloudWatchMetricsJsonHandler; this.marketplaceEntitlementController = marketplaceEntitlementController; + this.eventBridgeV2Handler = eventBridgeV2Handler; } @@ -110,7 +115,15 @@ public class AwsJsonCborController { * without booting Quarkus. */ static byte[] nodeToSmithyCbor(JsonNode node) throws Exception { - return writeCbor(node, false); + return nodeToSmithyCbor(node, Set.of()); + } + + /** + * As {@link #nodeToSmithyCbor(JsonNode)}, also tagging the members named, wherever they appear, as timestamps: + * a service whose model names its timestamps otherwise than {@link #isTimestampField} expects declares them. + */ + static byte[] nodeToSmithyCbor(JsonNode node, Set timestampMembers) throws Exception { + return writeCbor(node, false, timestampMembers); } /** @@ -121,14 +134,15 @@ public class AwsJsonCborController { * newer smithy-rpc-v2-cbor protocol, and {@link #writeCborTimestamp} for why. */ static byte[] nodeToLegacyCbor(JsonNode node) throws Exception { - return writeCbor(node, true); + return writeCbor(node, true, Set.of()); } - private static byte[] writeCbor(JsonNode node, boolean legacyDialect) throws Exception { + private static byte[] writeCbor(JsonNode node, boolean legacyDialect, Set timestampMembers) + throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); CBORFactory factory = (CBORFactory) CBOR_MAPPER.getFactory(); try (CBORGenerator gen = factory.createGenerator(out)) { - writeNodeToCbor(gen, node, false, legacyDialect); + writeNodeToCbor(gen, node, false, legacyDialect, timestampMembers); } return out.toByteArray(); } @@ -141,16 +155,18 @@ public class AwsJsonCborController { * object fields and is propagated into array elements, so both scalar timestamps and * elements of timestamp lists are tagged. {@code legacyDialect} selects which of the * two wire conventions tag(1) uses - see {@link #nodeToSmithyCbor}/{@link #nodeToLegacyCbor}. + * {@code timestampMembers} are field names tagged besides those the heuristic matches. */ private static void writeNodeToCbor(CBORGenerator gen, JsonNode node, boolean numberIsTimestamp, - boolean legacyDialect) throws Exception { + boolean legacyDialect, Set timestampMembers) throws Exception { if (node.isObject()) { gen.writeStartObject(); Iterator> fields = node.fields(); while (fields.hasNext()) { Map.Entry entry = fields.next(); gen.writeFieldName(entry.getKey()); - writeNodeToCbor(gen, entry.getValue(), isTimestampField(entry.getKey()), legacyDialect); + boolean timestamp = isTimestampField(entry.getKey()) || timestampMembers.contains(entry.getKey()); + writeNodeToCbor(gen, entry.getValue(), timestamp, legacyDialect, timestampMembers); } gen.writeEndObject(); } else if (node.isArray()) { @@ -158,7 +174,7 @@ public class AwsJsonCborController { for (JsonNode item : node) { // Propagate the timestamp context so every element of a timestamp list // (e.g. CloudWatch GetMetricData MetricDataResults[].Timestamps) is tagged. - writeNodeToCbor(gen, item, numberIsTimestamp, legacyDialect); + writeNodeToCbor(gen, item, numberIsTimestamp, legacyDialect, timestampMembers); } gen.writeEndArray(); } else if (numberIsTimestamp && node.isNumber()) { @@ -319,7 +335,7 @@ public class AwsJsonCborController { JsonNode responseNode = delegated.getEntity() instanceof JsonNode ? (JsonNode) delegated.getEntity() : objectMapper.valueToTree(delegated.getEntity()); - byte[] cborBytes = nodeToSmithyCbor(responseNode); + byte[] cborBytes = nodeToSmithyCbor(responseNode, timestampMembers(serviceId)); String responseContentType = responseContentType(httpHeaders); return Response.status(delegated.getStatus()) .header("smithy-protocol", "rpc-v2-cbor") @@ -499,10 +515,19 @@ public class AwsJsonCborController { case "states" -> sfnJsonHandler.handle(operation, request, region); case "monitoring" -> cloudWatchMetricsJsonHandler.handle(operation, request, region); case "marketplace" -> marketplaceEntitlementController.handle(operation, request, region); + case "eventsv2" -> eventBridgeV2Handler.handle(operation, request, region); default -> null; }; } + /** The timestamp members a service's responses carry under names {@link #isTimestampField} does not match. */ + private Set timestampMembers(String serviceId) { + return catalog.byCborSdkServiceId(serviceId) + .filter(descriptor -> "eventsv2".equals(descriptor.externalKey())) + .map(descriptor -> EventBridgeV2Handler.TIMESTAMP_MEMBERS) + .orElse(Set.of()); + } + private Response cborUnknownOperationError(String message, HttpHeaders httpHeaders) { return cborErrorResponse( new AwsException("UnknownOperationException", message, 404), diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index e0bb0696de..867bb0bb95 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -1350,7 +1350,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter { .filter(scope -> scope.equals(catalog.canonicalCredentialScope(scope))) .sorted() .findFirst() - .orElse(descriptor.externalKey()); + .orElse(catalog.canonicalCredentialScope(descriptor.externalKey())); } /** The same contexts with every object-tag key removed, keeping the principal and global keys. */ diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java index 8651ad79fa..2c86a521d6 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestResourceMembers.java @@ -129,16 +129,19 @@ final class RequestResourceMembers { * it connects to). A type whose ARN is all an id its service mints is named instead by the members its service * finds it by, {@code find}, each one value, in the order its service reads them, filling none of its variables * and read no other way, in the caller's account (a scalable target by its service namespace, resource id and - * scalable dimension). + * scalable dimension). A resource with an {@code endpoint} applies only to a request the service of that endpoint + * prefix serves, where two APIs share the operation's name and nothing in a request tells them apart + * (EventBridge's {@code events} and EventBridge V2's {@code eventsv2}); null for every request. */ record Resource(List types, Member arn, Map fill, Map> when, Map> unless, Map absent, Map arnOf, - Member account, String before, Map fixed, boolean made, List find) { + Member account, String before, Map fixed, boolean made, List find, + String endpoint) { Resource(List types, Member arn, Map fill, Map> when, Map> unless, Map absent, Map arnOf, - Member account, String before, Map fixed, boolean made) { - this(types, arn, fill, when, unless, absent, arnOf, account, before, fixed, made, List.of()); + Member account, String before, Map fixed, boolean made, String endpoint) { + this(types, arn, fill, when, unless, absent, arnOf, account, before, fixed, made, List.of(), endpoint); } } @@ -247,6 +250,11 @@ final class RequestResourceMembers { + resource.path("made") + ", which is not true"); } boolean made = resource.has("made"); + String endpoint = resource.has("endpoint") ? resource.path("endpoint").asText("") : null; + if (endpoint != null && endpoint.isEmpty()) { + throw new IllegalStateException(RESOURCE_NAME + " serves a resource of " + operation + + " on no endpoint prefix"); + } String before = resource.has("before") ? resource.path("before").asText("") : null; if (before != null && before.length() != 1) { throw new IllegalStateException(RESOURCE_NAME + " reads a member for " + operation @@ -263,7 +271,7 @@ final class RequestResourceMembers { + " and finds its resource by " + resource.path("find") + " too"); } return new Resource(types, arnMember(operation, resource.path("arn").asText("")), Map.of(), Map.of(), - Map.of(), Map.of(), Map.of(), null, before, Map.of(), made); + Map.of(), Map.of(), Map.of(), null, before, Map.of(), made, endpoint); } String type = resource.path("type").asText(""); ArnFormat format = formats.get(type); @@ -330,7 +338,7 @@ final class RequestResourceMembers { + " from " + account.name() + ", no member of one account or a type of none"); } return new Resource(List.of(type), null, Map.copyOf(fill), when, unless, Map.copyOf(absent), Map.copyOf(arnOf), - account, before, Map.copyOf(fixed), made, List.copyOf(find)); + account, before, Map.copyOf(fixed), made, List.copyOf(find), endpoint); } /** The values each member named in {@code when} or {@code unless} may have, an empty one for the member absent. */ diff --git a/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java b/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java index 7b13d40a06..72300aea28 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/RequestResources.java @@ -69,7 +69,8 @@ public final class RequestResources { public static List of(String operation, ContainerRequestContext ctx, String partition, String region, String accountId, StoredResourceArns stored) { RequestResourceMembers.Table table = RequestResourceMembers.table(); - List resources = operation == null ? null : table.operations().get(operation); + List resources = operation == null ? null + : served(table.operations().get(operation), ctx); if (resources == null || resources.isEmpty()) { return List.of(); } @@ -117,7 +118,7 @@ public final class RequestResources { RequestResourceMembers.Table table = RequestResourceMembers.table(); List creates = operation == null ? null : table.creates().get(operation); List made = operation == null || creates != null ? List.of() - : table.operations().getOrDefault(operation, List.of()).stream() + : served(table.operations().getOrDefault(operation, List.of()), ctx).stream() .filter(RequestResourceMembers.Resource::made).toList(); if (creates == null && made.isEmpty()) { return List.of(); @@ -149,6 +150,23 @@ public final class RequestResources { return List.copyOf(arns); } + /** + * The resources that apply to a request of the service serving it: one with an {@code endpoint} applies only to + * a request the service of that endpoint prefix serves, read from the claim of the service whose handler runs it + * and never from the request's members, which a caller could add to a request of the other API. A request no + * service is known to serve keeps them all, which can only check it on more. + */ + private static List served(List resources, + ContainerRequestContext ctx) { + String endpoint = ctx.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY) instanceof ProtocolClaim claim + && claim.service() != null ? claim.service().externalKey() : null; + if (resources == null || endpoint == null) { + return resources; + } + return resources.stream().filter(resource -> resource.endpoint() == null + || resource.endpoint().equals(endpoint)).toList(); + } + /** The value up to {@code separator}, which its handler drops the rest after; the whole value without one. */ private static String before(String value, String separator) { int at = separator == null ? -1 : value.indexOf(separator); diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java index 4c7b702067..98c88a15ef 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java @@ -125,7 +125,8 @@ public class ResolvedServiceCatalog { "s3express", "s3", "iot-jobs-data", "iot", "monitoring", "cloudwatch", - "awsssoportal", "sso"); + "awsssoportal", "sso", + "eventsv2", "events"); private final ServiceCatalog catalog; @@ -250,6 +251,12 @@ public class ResolvedServiceCatalog { "eventbridge", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), Set.of("AWSEvents."), Set.of("events"), Set.of(), Set.of()), + // Signs as events too, which stays EventBridge's scope: it is routed by its RPC v2 path alone, + // and its eventsv2 key aliases to the events IAM namespace its actions live under. + descriptor("eventsv2", "eventbridgev2", config.services().eventbridgev2().enabled(), true, + "eventbridgev2", config.storage().mode(), 5000L, null, ServiceProtocol.CBOR, + protocols(ServiceProtocol.CBOR), + Set.of(), Set.of(), Set.of("AWSEventsV2"), Set.of()), descriptor("servicediscovery", "cloudmap", config.services().cloudmap().enabled(), true, "cloudmap", config.storage().mode(), 5000L, null, ServiceProtocol.JSON, protocols(ServiceProtocol.JSON), diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Delivery.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Delivery.java new file mode 100644 index 0000000000..54594535de --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Delivery.java @@ -0,0 +1,98 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.eventbridgev2.model.SubscriberV2; +import io.github.hectorvent.floci.services.sqs.SqsService; +import io.github.hectorvent.floci.services.sqs.model.MessageAttributeValue; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; + +/** + * Delivers an event a subscriber's filters matched to its target, an Amazon SQS queue: one message per event, + * whose body {@code Transformer.Type} decides, {@code RAW} the event's data unchanged and {@code WITH_METADATA} + * its data, metadata and system metadata, with the queue parameters {@code SqsParameters} gives. + */ +@ApplicationScoped +public class EventBridgeV2Delivery { + + private static final Logger LOG = Logger.getLogger(EventBridgeV2Delivery.class); + + private final SqsService sqsService; + private final String baseUrl; + + @Inject + public EventBridgeV2Delivery(SqsService sqsService, EmulatorConfig config) { + this.sqsService = sqsService; + this.baseUrl = config.baseUrl(); + } + + /** Sends the event to the subscriber's queue; a delivery that fails is logged and the event dropped. */ + public void deliver(SubscriberV2 subscriber, PublishedEvent event) { + String queueArn = subscriber.getInvokeConfiguration().path("TargetArn").asText(); + try { + JsonNode parameters = subscriber.getInvokeConfiguration().path("SqsParameters"); + String groupId = parameter(parameters, "MessageGroupId", event); + String deduplicationId = parameter(parameters, "MessageDeduplicationId", event); + String delay = parameter(parameters, "DelaySeconds", event); + Map attributes = messageAttributes(parameters.path("MessageAttributes"), event); + String region = AwsArnUtils.parse(queueArn).region(); + sqsService.sendMessage(AwsArnUtils.arnToQueueUrl(queueArn, baseUrl), body(subscriber, event), + delay == null ? null : Integer.valueOf(delay), groupId, deduplicationId, + attributes.isEmpty() ? null : attributes, region); + LOG.debugv("EventBridge V2 subscriber {0} delivered to {1}", subscriber.getArn(), queueArn); + } catch (AwsException | IllegalArgumentException e) { + LOG.warnv("EventBridge V2 subscriber {0} failed to deliver to {1}: {2}", subscriber.getArn(), queueArn, + e.getMessage()); + } + } + + static String body(SubscriberV2 subscriber, PublishedEvent event) { + JsonNode transformer = subscriber.getTransformer(); + String type = transformer == null ? "RAW" : transformer.path("Type").asText("RAW"); + if ("WITH_METADATA".equals(type)) { + return event.withMetadata().toString(); + } + JsonNode data = event.data(); + return data.isTextual() ? data.textValue() : data.toString(); + } + + private static String parameter(JsonNode parameters, String name, PublishedEvent event) { + JsonNode value = parameters.get(name); + if (value == null || value.isNull()) { + return null; + } + return resolve(value.asText(), name, event); + } + + private static Map messageAttributes(JsonNode attributes, PublishedEvent event) { + Map resolved = new LinkedHashMap<>(); + attributes.properties().forEach(attribute -> { + JsonNode value = attribute.getValue(); + String dataType = value.path("DataType").asText("String"); + String name = resolve(attribute.getKey(), "MessageAttributes", event); + if (value.hasNonNull("BinaryValue")) { + resolved.put(name, new MessageAttributeValue(Base64.getDecoder().decode(value.get("BinaryValue").asText()), + dataType)); + } else { + resolved.put(name, new MessageAttributeValue( + resolve(value.path("StringValue").asText(""), "MessageAttributes." + name, event), dataType)); + } + }); + return resolved; + } + + private static String resolve(String value, String parameter, PublishedEvent event) { + Optional resolved = EventExpressions.resolve(value, event); + return resolved.orElseThrow(() -> new IllegalArgumentException( + "SqsParameters." + parameter + " expression " + value + " produced no value")); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Handler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Handler.java new file mode 100644 index 0000000000..775d66e321 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Handler.java @@ -0,0 +1,222 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.services.eventbridgev2.model.EventBusV2; +import io.github.hectorvent.floci.services.eventbridgev2.model.SubscriberV2; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import jakarta.ws.rs.core.Response; + +import java.math.BigDecimal; +import java.time.Instant; +import java.util.List; +import java.util.Set; + +/** + * EventBridge V2 handler, dispatched by {@code AwsJsonCborController} for Smithy RPC v2 CBOR requests to + * {@code /service/AWSEventsV2/operation/}. + */ +@ApplicationScoped +public class EventBridgeV2Handler { + + /** + * The response members the model types as timestamps, which the CBOR encoder tags as such: their names do not + * end in {@code Timestamp}, the convention it otherwise goes by. + */ + public static final Set TIMESTAMP_MEMBERS = Set.of("CreationTime", "LastModifiedTime", + "RetentionWindowStartTime", "StartingPoint", "EndPoint"); + + private final EventBridgeV2Service service; + private final ObjectMapper objectMapper; + + @Inject + public EventBridgeV2Handler(EventBridgeV2Service service, ObjectMapper objectMapper) { + this.service = service; + this.objectMapper = objectMapper; + } + + public Response handle(String operation, JsonNode request, String region) { + return switch (operation) { + case "CreateEventBus" -> handleCreateEventBus(request, region); + case "DescribeEventBus" -> handleDescribeEventBus(request, region); + case "DeleteEventBus" -> handleDeleteEventBus(request, region); + case "ListEventBuses" -> handleListEventBuses(request, region); + case "CreateSubscriber" -> handleCreateSubscriber(request, region); + case "DescribeSubscriber" -> handleDescribeSubscriber(request, region); + case "ListSubscribers" -> handleListSubscribers(request, region); + case "UpdateSubscriber" -> handleUpdateSubscriber(request, region); + case "DeleteSubscriber" -> handleDeleteSubscriber(request, region); + case "PutEvents" -> handlePutEvents(request, region); + default -> throw new AwsException("UnsupportedOperation", + "Operation " + operation + " is not supported.", 400); + }; + } + + private Response handleCreateEventBus(JsonNode request, String region) { + return Response.ok(eventBus(service.createEventBus(request, region))).build(); + } + + private Response handleDescribeEventBus(JsonNode request, String region) { + EventBusV2 bus = service.describeEventBus(request, region); + ObjectNode response = eventBus(bus); + response.put("LastModifiedTime", epochSeconds(bus.getLastModifiedTime())); + return Response.ok(response).build(); + } + + /** The members {@code CreateEventBus} and {@code DescribeEventBus} both answer with. */ + private ObjectNode eventBus(EventBusV2 bus) { + ObjectNode response = objectMapper.createObjectNode(); + response.put("EventBusArn", bus.getArn()); + response.put("Name", bus.getName()); + if (bus.getDescription() != null) { + response.put("Description", bus.getDescription()); + } + if (bus.getKmsKeyIdentifier() != null) { + response.putObject("EncryptionConfiguration").put("KmsKeyIdentifier", bus.getKmsKeyIdentifier()); + } + if (bus.getRetentionPeriodInDays() != null) { + response.putObject("StorageConfiguration").put("RetentionPeriodInDays", bus.getRetentionPeriodInDays()); + } + response.put("State", bus.getState()); + response.put("CreationTime", epochSeconds(bus.getCreationTime())); + return response; + } + + private Response handleDeleteEventBus(JsonNode request, String region) { + service.deleteEventBus(request, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handleListEventBuses(JsonNode request, String region) { + PaginatedResult page = service.listEventBuses(request, region); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode buses = response.putArray("EventBuses"); + for (EventBusV2 bus : page.items()) { + ObjectNode summary = buses.addObject(); + summary.put("Name", bus.getName()); + summary.put("EventBusArn", bus.getArn()); + if (bus.getDescription() != null) { + summary.put("Description", bus.getDescription()); + } + summary.put("CreationTime", epochSeconds(bus.getCreationTime())); + summary.put("LastModifiedTime", epochSeconds(bus.getLastModifiedTime())); + summary.put("State", bus.getState()); + summary.put("EventBusAccountId", AwsArnUtils.parse(bus.getArn()).accountId()); + } + if (page.nextToken() != null) { + response.put("NextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + private Response handleCreateSubscriber(JsonNode request, String region) { + SubscriberV2 subscriber = service.createSubscriber(request, region); + ObjectNode response = subscriberIdentity(subscriber); + response.put("CreationTime", epochSeconds(subscriber.getCreationTime())); + return Response.ok(response).build(); + } + + private Response handleUpdateSubscriber(JsonNode request, String region) { + SubscriberV2 subscriber = service.updateSubscriber(request, region); + ObjectNode response = subscriberIdentity(subscriber); + response.put("LastModifiedTime", epochSeconds(subscriber.getLastModifiedTime())); + return Response.ok(response).build(); + } + + private Response handleDescribeSubscriber(JsonNode request, String region) { + SubscriberV2 subscriber = service.describeSubscriber(request, region); + ObjectNode response = subscriberIdentity(subscriber); + response.set("InvokeConfiguration", subscriber.getInvokeConfiguration()); + if (subscriber.getDescription() != null) { + response.put("Description", subscriber.getDescription()); + } + putIfSet(response, "FilterConfiguration", subscriber.getFilterConfiguration()); + putIfSet(response, "BatchConfiguration", subscriber.getBatchConfiguration()); + putIfSet(response, "Transformer", subscriber.getTransformer()); + putIfSet(response, "RetryPolicy", subscriber.getRetryPolicy()); + putIfSet(response, "OnFailureConfiguration", subscriber.getOnFailureConfiguration()); + putIfSet(response, "LogConfiguration", subscriber.getLogConfiguration()); + response.put("Revoked", false); + response.put("CreationTime", epochSeconds(subscriber.getCreationTime())); + response.put("LastModifiedTime", epochSeconds(subscriber.getLastModifiedTime())); + return Response.ok(response).build(); + } + + private Response handleListSubscribers(JsonNode request, String region) { + PaginatedResult page = service.listSubscribers(request, region); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode subscribers = response.putArray("Subscribers"); + for (SubscriberV2 subscriber : page.items()) { + ObjectNode summary = subscribers.addObject(); + summary.put("SubscriberArn", subscriber.getArn()); + summary.put("Name", subscriber.getName()); + summary.put("EventBusArn", subscriber.getEventBusArn()); + summary.put("TargetArn", subscriber.getInvokeConfiguration().path("TargetArn").asText()); + summary.put("Type", subscriber.getType()); + summary.put("Revoked", false); + summary.put("State", subscriber.getState()); + summary.put("CreationTime", epochSeconds(subscriber.getCreationTime())); + summary.put("LastModifiedTime", epochSeconds(subscriber.getLastModifiedTime())); + summary.put("SubscriberAccountId", AwsArnUtils.parse(subscriber.getArn()).accountId()); + } + if (page.nextToken() != null) { + response.put("NextToken", page.nextToken()); + } + return Response.ok(response).build(); + } + + /** The members {@code CreateSubscriber}, {@code UpdateSubscriber} and {@code DescribeSubscriber} all answer with. */ + private ObjectNode subscriberIdentity(SubscriberV2 subscriber) { + ObjectNode response = objectMapper.createObjectNode(); + response.put("SubscriberArn", subscriber.getArn()); + response.put("Name", subscriber.getName()); + response.put("EventBusArn", subscriber.getEventBusArn()); + response.put("Type", subscriber.getType()); + response.put("StartingPosition", subscriber.getStartingPosition()); + putIfSet(response, "PointInTimeConfiguration", subscriber.getPointInTimeConfiguration()); + response.put("State", subscriber.getState()); + return response; + } + + private static void putIfSet(ObjectNode response, String field, JsonNode value) { + if (value != null && !value.isNull()) { + response.set(field, value); + } + } + + private Response handleDeleteSubscriber(JsonNode request, String region) { + service.deleteSubscriber(request, region); + return Response.ok(objectMapper.createObjectNode()).build(); + } + + private Response handlePutEvents(JsonNode request, String region) { + List results = service.putEvents(request, region); + ObjectNode response = objectMapper.createObjectNode(); + ArrayNode entries = response.putArray("Entries"); + int failed = 0; + for (EventBridgeV2Service.PutEventsResult result : results) { + ObjectNode entry = entries.addObject(); + if (result.errorCode() != null) { + failed++; + entry.put("ErrorCode", result.errorCode()); + entry.put("ErrorMessage", result.errorMessage()); + } else { + entry.put("EventId", result.eventId()); + entry.put("SequenceNumber", result.sequenceNumber()); + entry.put("SuccessCode", "PUBLISHED"); + } + } + response.put("FailedEntryCount", failed); + return Response.ok(response).build(); + } + + private static BigDecimal epochSeconds(Instant instant) { + return BigDecimal.valueOf(instant.toEpochMilli()).movePointLeft(3); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Service.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Service.java new file mode 100644 index 0000000000..7f3fc39cfc --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2Service.java @@ -0,0 +1,900 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsArnUtils; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsJsonTimestamp; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.Pagination; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.Resettable; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.eventbridgev2.model.EventBusV2; +import io.github.hectorvent.floci.services.eventbridgev2.model.SubscriberV2; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.math.BigDecimal; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Queue; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Function; +import java.util.regex.Pattern; + +/** + * EventBridge V2: the {@code AWSEventsV2} Smithy RPC v2 CBOR service, distinct from EventBridge's + * {@code event-bus} resources and sharing nothing with them but the {@code events} signing name. Its event buses + * accept events with {@code PutEvents} and deliver each to every running subscriber whose filters it matches. + */ +@ApplicationScoped +public class EventBridgeV2Service implements Resettable { + static final String ACTIVE = "ACTIVE"; + static final String RUNNING = "RUNNING"; + + private static final Logger LOG = Logger.getLogger(EventBridgeV2Service.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final ObjectMapper CANONICAL = new ObjectMapper() + .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); + private static final Pattern NAME = Pattern.compile("[A-Za-z0-9][.\\-_A-Za-z0-9]*"); + private static final Pattern DESCRIPTION = Pattern.compile("[^\\u0000-\\u001F\\u007F-\\u009F\\u2028\\u2029]*"); + private static final Pattern KMS_KEY_IDENTIFIER = Pattern.compile("[a-zA-Z0-9_\\-/:]*"); + private static final Pattern CLIENT_TOKEN = Pattern.compile("[\\u0021-\\u007E]+"); + private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}"); + private static final Pattern TAG_KEY = Pattern.compile("\\S([\\s\\S]*\\S)?"); + private static final Pattern TAG_VALUE = Pattern.compile("(\\S([\\s\\S]*\\S)?)?"); + private static final Pattern ROLE_ARN = Pattern.compile( + "arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::\\d{12}:role/[\\w+=,.@/-]+"); + private static final Set PARAMETER_BLOCKS = Set.of("LambdaParameters", "SqsParameters", "SnsParameters", + "KinesisParameters", "StepFunctionsParameters", "HttpParameters", "UniversalTargetParameters", + "EventBusV2Parameters"); + private static final String ID_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"; + private static final int ID_LENGTH = 25; + private static final int MAX_TAGS = 200; + private static final int MAX_ENTRIES = 100; + private static final int MAX_LIST_RESULTS = 100; + private static final List UPDATABLE_SETTINGS = List.of("Description", "State", "FilterConfiguration", + "BatchConfiguration", "Transformer", "RetryPolicy", "OnFailureConfiguration", "LogConfiguration"); + private static final String PUT_EVENTS_CONTENT_TYPE = "application/eventbridge+json"; + + private final AccountAwareStorageBackend buses; + private final AccountAwareStorageBackend subscribers; + private final RegionResolver regionResolver; + private final EventBridgeV2Delivery delivery; + private final Clock clock; + private final SecureRandom random = new SecureRandom(); + private final ConcurrentMap deliveriesByBus = new ConcurrentHashMap<>(); + + @Inject + public EventBridgeV2Service(StorageFactory storageFactory, RegionResolver regionResolver, + EventBridgeV2Delivery delivery) { + this(storageFactory.create("eventbridgev2", "eventbridgev2-buses.json", + new TypeReference>() {}), + storageFactory.create("eventbridgev2", "eventbridgev2-subscribers.json", + new TypeReference>() {}), + regionResolver, delivery, Clock.systemUTC()); + } + + EventBridgeV2Service(AccountAwareStorageBackend buses, + AccountAwareStorageBackend subscribers, RegionResolver regionResolver, + EventBridgeV2Delivery delivery, Clock clock) { + this.buses = buses; + this.subscribers = subscribers; + this.regionResolver = regionResolver; + this.delivery = delivery; + this.clock = clock; + } + + // ──────────────────────────── Event buses ──────────────────────────── + + /** + * Creates an event bus, {@code ACTIVE} at once. A retry with the {@code ClientToken} of an earlier create + * returns that bus when it repeats the request, and fails when it changes it. + */ + public synchronized EventBusV2 createEventBus(JsonNode request, String region) { + String name = requireName(request); + String description = optionalDescription(request); + String kmsKeyIdentifier = optionalKmsKeyIdentifier(request); + Integer retentionPeriodInDays = optionalRetentionPeriodInDays(request); + Map tags = readTags(request.get("Tags")); + String clientToken = optionalClientToken(request); + String createRequest = withoutClientToken(request); + + if (clientToken != null) { + Optional retried = buses.scan(key -> key.startsWith(region + "::")).stream() + .filter(bus -> clientToken.equals(bus.getClientToken())) + .findFirst(); + if (retried.isPresent()) { + if (!createRequest.equals(retried.get().getCreateRequest())) { + throw idempotentMismatch(clientToken); + } + return retried.get(); + } + } + String key = storageKey(region, name); + if (buses.get(key).isPresent()) { + throw new AwsException("ResourceAlreadyExistsException", "Event bus " + name + " already exists.", 409); + } + + Instant now = clock.instant(); + EventBusV2 bus = new EventBusV2(); + bus.setName(name); + bus.setArn(regionResolver.buildArn("events", region, "event-busv2/" + name + "/" + newId())); + bus.setDescription(description); + bus.setKmsKeyIdentifier(kmsKeyIdentifier); + bus.setRetentionPeriodInDays(retentionPeriodInDays); + bus.setState(ACTIVE); + bus.setCreationTime(now); + bus.setLastModifiedTime(now); + bus.setTags(tags); + bus.setClientToken(clientToken); + bus.setCreateRequest(createRequest); + buses.put(key, bus); + return bus; + } + + /** + * Sets a bus's description, KMS key, retention and tags to what the request gives, clearing those it leaves + * out, as a CloudFormation update of the bus's template does. The name is the bus's identity and is not read. + */ + public synchronized EventBusV2 replaceEventBusSettings(String eventBusArn, JsonNode request, String region) { + EventBusV2 bus = requireEventBus(eventBusArn, region); + String description = optionalDescription(request); + String kmsKeyIdentifier = optionalKmsKeyIdentifier(request); + Integer retentionPeriodInDays = optionalRetentionPeriodInDays(request); + Map tags = readTags(request.get("Tags")); + bus.setDescription(description); + bus.setKmsKeyIdentifier(kmsKeyIdentifier); + bus.setRetentionPeriodInDays(retentionPeriodInDays); + bus.setTags(tags); + bus.setLastModifiedTime(clock.instant()); + buses.put(storageKey(region, bus.getName()), bus); + return bus; + } + + /** The bus {@code EventBusArn} names. */ + public EventBusV2 describeEventBus(JsonNode request, String region) { + return requireEventBus(requireText(request, "EventBusArn"), region); + } + + /** Deletes the bus {@code EventBusArn} names. */ + public void deleteEventBus(JsonNode request, String region) { + deleteEventBus(requireText(request, "EventBusArn"), region); + } + + /** Deletes a bus, which must have no subscribers left. */ + public synchronized void deleteEventBus(String eventBusArn, String region) { + EventBusV2 bus = requireEventBus(eventBusArn, region); + if (!subscribersOf(bus, region).isEmpty()) { + throw new AwsException("ResourceInUseException", + "Event bus " + bus.getName() + " still has subscribers; delete them first.", 409); + } + buses.delete(storageKey(region, bus.getName())); + deliveriesByBus.remove(bus.getArn()); + } + + /** + * One page of the Region's buses in name order, those whose name starts with {@code NamePrefix}. Every bus is + * the caller's own, so an {@code EventBusAccountId} naming another account lists none. + */ + public PaginatedResult listEventBuses(JsonNode request, String region) { + String namePrefix = optionalNamePrefix(request); + String accountId = text(request, "EventBusAccountId"); + if (accountId != null && !ACCOUNT_ID.matcher(accountId).matches()) { + throw invalidInput("EventBusAccountId must be 12 digits."); + } + List listed = accountId != null && !accountId.equals(regionResolver.getAccountId()) + ? List.of() + : buses.scan(key -> key.startsWith(region + "::")).stream() + .filter(bus -> namePrefix == null || bus.getName().startsWith(namePrefix)) + .toList(); + return page(listed, EventBusV2::getName, request, "event-busv2"); + } + + // ──────────────────────────── Subscribers ──────────────────────────── + + /** + * Creates a subscriber on a bus of the caller's, delivering each event it accepts that matches every filter + * to its target, an Amazon SQS queue of the caller's. A retry with the {@code ClientToken} of an earlier create + * returns that subscriber when it repeats the request, and fails when it changes it. + */ + public synchronized SubscriberV2 createSubscriber(JsonNode request, String region) { + String name = requireName(request); + String eventBusArn = requireText(request, "EventBusArn"); + JsonNode filterConfiguration = optionalStructure(request, "FilterConfiguration"); + if (filterConfiguration != null) { + SubscriberFilters.validate(filterConfiguration); + } + String clientToken = optionalClientToken(request); + String createRequest = withoutClientToken(request); + if (clientToken != null) { + Optional retried = subscribers.scan(key -> key.startsWith(region + "::")).stream() + .filter(subscriber -> clientToken.equals(subscriber.getClientToken())) + .findFirst(); + if (retried.isPresent()) { + if (!createRequest.equals(retried.get().getCreateRequest())) { + throw idempotentMismatch(clientToken); + } + return retried.get(); + } + } + EventBusV2 bus = requireEventBus(eventBusArn, region); + String key = subscriberKey(region, bus.getName(), name); + if (subscribers.get(key).isPresent()) { + throw new AwsException("ResourceAlreadyExistsException", + "Subscriber " + name + " already exists on event bus " + bus.getName() + ".", 409); + } + + Instant now = clock.instant(); + SubscriberV2 subscriber = new SubscriberV2(); + subscriber.setName(name); + subscriber.setArn(regionResolver.buildArn("events", region, "subscriber/" + name + "/" + newId())); + subscriber.setEventBusArn(bus.getArn()); + subscriber.setType(optionalEnum(request, "Type", Set.of("FIFO", "UNORDERED"), "UNORDERED")); + subscriber.setStartingPosition(optionalEnum(request, "StartingPosition", Set.of("LATEST", "POINT_IN_TIME"), + "LATEST")); + subscriber.setPointInTimeConfiguration(pointInTimeConfiguration(request, subscriber.getStartingPosition())); + applySettings(subscriber, request, filterConfiguration); + subscriber.setCreationTime(now); + subscriber.setLastModifiedTime(now); + subscriber.setClientToken(clientToken); + subscriber.setCreateRequest(createRequest); + subscribers.put(key, subscriber); + return subscriber; + } + + /** + * Sets a subscriber's description, target, filters, transformer, delivery settings, state and tags to what the + * request gives, clearing those it leaves out, as a CloudFormation update of the subscriber's template does. + * Its name, bus, type and starting position are its identity and are not read. + */ + public synchronized SubscriberV2 replaceSubscriberSettings(String subscriberArn, JsonNode request, String region) { + SubscriberV2 subscriber = requireSubscriber(subscriberArn, region); + return changeSettings(subscriber, request, region); + } + + /** + * Changes the settings an {@code UpdateSubscriber} request gives and leaves those it omits as they are. The + * target stays the subscriber's own: the request's {@code InvokeConfiguration} carries the role and target + * parameters but no {@code TargetArn}. Events are not retained, so {@code ResumePosition} is checked and has no + * effect. + */ + public synchronized SubscriberV2 updateSubscriber(JsonNode request, String region) { + SubscriberV2 subscriber = requireSubscriber(requireText(request, "SubscriberArn"), region); + optionalEnum(request, "ResumePosition", Set.of("LAST_PROCESSED", "LATEST"), null); + JsonNode invokeConfiguration = optionalStructure(request, "InvokeConfiguration"); + if (invokeConfiguration != null && invokeConfiguration.has("TargetArn")) { + throw invalidInput("InvokeConfiguration.TargetArn cannot be updated."); + } + + ObjectNode settings = currentSettings(subscriber); + for (String field : UPDATABLE_SETTINGS) { + if (request.hasNonNull(field)) { + settings.set(field, request.get(field)); + } + } + if (invokeConfiguration != null) { + ObjectNode invoke = invokeConfiguration.deepCopy(); + invoke.set("TargetArn", subscriber.getInvokeConfiguration().get("TargetArn")); + settings.set("InvokeConfiguration", invoke); + } + return changeSettings(subscriber, settings, region); + } + + /** + * Stores a new subscriber with {@code subscriber}'s identity and {@code settings}, so a refused change changes + * nothing and a reader sees the subscriber before or after the change, never part way through it. + */ + private SubscriberV2 changeSettings(SubscriberV2 subscriber, JsonNode settings, String region) { + JsonNode filterConfiguration = optionalStructure(settings, "FilterConfiguration"); + if (filterConfiguration != null) { + SubscriberFilters.validate(filterConfiguration); + } + SubscriberV2 changed = new SubscriberV2(); + applySettings(changed, settings, filterConfiguration); + changed.setName(subscriber.getName()); + changed.setArn(subscriber.getArn()); + changed.setEventBusArn(subscriber.getEventBusArn()); + changed.setType(subscriber.getType()); + changed.setStartingPosition(subscriber.getStartingPosition()); + changed.setPointInTimeConfiguration(subscriber.getPointInTimeConfiguration()); + changed.setCreationTime(subscriber.getCreationTime()); + changed.setLastModifiedTime(clock.instant()); + changed.setClientToken(subscriber.getClientToken()); + changed.setCreateRequest(subscriber.getCreateRequest()); + subscribers.put(subscriberKey(region, busName(subscriber.getEventBusArn()), subscriber.getName()), changed); + return changed; + } + + /** The subscriber {@code SubscriberArn} names. */ + public SubscriberV2 describeSubscriber(JsonNode request, String region) { + return requireSubscriber(requireText(request, "SubscriberArn"), region); + } + + /** + * One page of the Region's subscribers, or those of the bus {@code EventBusArn} names, whose name starts with + * {@code NamePrefix}, in order of bus and then subscriber name. + */ + public PaginatedResult listSubscribers(JsonNode request, String region) { + String namePrefix = optionalNamePrefix(request); + String eventBusArn = text(request, "EventBusArn"); + EventBusV2 bus = eventBusArn == null ? null : requireEventBus(eventBusArn, region); + List listed = (bus == null ? subscribers.scan(key -> key.startsWith(region + "::")) + : subscribersOf(bus, region)).stream() + .filter(subscriber -> namePrefix == null || subscriber.getName().startsWith(namePrefix)) + .toList(); + return page(listed, subscriber -> busName(subscriber.getEventBusArn()) + "::" + subscriber.getName(), + request, "subscriber"); + } + + /** Deletes the subscriber {@code SubscriberArn} names. */ + public void deleteSubscriber(JsonNode request, String region) { + deleteSubscriber(requireText(request, "SubscriberArn"), region); + } + + public synchronized void deleteSubscriber(String subscriberArn, String region) { + SubscriberV2 subscriber = requireSubscriber(subscriberArn, region); + subscribers.delete(subscriberKey(region, busName(subscriber.getEventBusArn()), subscriber.getName())); + } + + public Optional findSubscriber(String subscriberArn, String region) { + return subscribers.scan(key -> key.startsWith(region + "::")).stream() + .filter(subscriber -> subscriber.getArn().equals(subscriberArn)) + .findFirst(); + } + + public Optional findEventBus(String eventBusArn, String region) { + return Optional.ofNullable(busName(eventBusArn)) + .flatMap(name -> buses.get(storageKey(region, name))) + .filter(bus -> bus.getArn().equals(eventBusArn)); + } + + // ──────────────────────────── Events ──────────────────────────── + + /** A bus's deliveries waiting to be sent, in sequence order, and the lock held while sending them. */ + private record OrderedDeliveries(Queue> pending, ReentrantLock sending) { + } + + /** The outcome of one {@code PutEvents} entry: its id and sequence number, or why it was refused. */ + public record PutEventsResult(String eventId, String sequenceNumber, String errorCode, String errorMessage) { + } + + /** + * Accepts each entry as an event in the EventBridge envelope and delivers it to every running subscriber of the + * bus whose filters it matches. An entry whose {@code Detail} is not a JSON object is refused on its own. + */ + public List putEvents(JsonNode request, String region) { + String eventBusArn = requireText(request, "EventBusArn"); + JsonNode entries = request.get("Entries"); + if (entries == null || !entries.isArray() || entries.isEmpty() || entries.size() > MAX_ENTRIES) { + throw invalidInput("Entries must hold 1 to " + MAX_ENTRIES + " entries."); + } + List times = new ArrayList<>(); + for (JsonNode entry : entries) { + requireText(entry, "Source"); + requireText(entry, "DetailType"); + times.add(AwsJsonTimestamp.epochSeconds(entry, "Time", "InvalidInputException")); + } + List results = new ArrayList<>(); + List> deliveries = new ArrayList<>(); + OrderedDeliveries ordered; + synchronized (this) { + EventBusV2 bus = requireEventBus(eventBusArn, region); + List running = subscribersOf(bus, region).stream() + .filter(subscriber -> RUNNING.equals(subscriber.getState())) + .toList(); + for (int i = 0; i < entries.size(); i++) { + JsonNode entry = entries.get(i); + JsonNode detail = detail(entry); + if (detail == null) { + results.add(new PutEventsResult(null, null, "MalformedDetail", "Detail is malformed.")); + continue; + } + bus.setSequenceNumber(bus.getSequenceNumber() + 1); + String sequenceNumber = Long.toString(bus.getSequenceNumber()); + PublishedEvent event = envelope(bus, entry, times.get(i), detail, sequenceNumber); + results.add(new PutEventsResult(event.systemMetadata().get("aws:EventId").asText(), sequenceNumber, + null, null)); + for (SubscriberV2 subscriber : running) { + if (SubscriberFilters.matches(subscriber.getFilterConfiguration(), event)) { + deliveries.add(Map.entry(subscriber, event)); + } + } + } + buses.put(storageKey(region, bus.getName()), bus); + ordered = deliveriesByBus.computeIfAbsent(bus.getArn(), + arn -> new OrderedDeliveries(new ConcurrentLinkedQueue<>(), new ReentrantLock())); + ordered.pending().addAll(deliveries); + } + send(ordered); + return results; + } + + /** + * Sends a bus's queued deliveries in the order {@code PutEvents} queued them, which is sequence order, holding the + * bus's sending lock, so a request that took later sequence numbers never sends ahead of an earlier one. Every + * caller drains after queueing its own deliveries, so none is left queued, and a caller returns only once its own + * have been sent, by itself or by the caller that held the lock before it. + */ + private void send(OrderedDeliveries ordered) { + ordered.sending().lock(); + try { + Map.Entry next; + while ((next = ordered.pending().poll()) != null) { + try { + delivery.deliver(next.getKey(), next.getValue()); + } catch (RuntimeException e) { + LOG.warnv(e, "EventBridge V2 subscriber {0} failed to deliver event {1}", next.getKey().getArn(), + next.getValue().systemMetadata().path("aws:EventId").asText()); + } + } + } finally { + ordered.sending().unlock(); + } + } + + private PublishedEvent envelope(EventBusV2 bus, JsonNode entry, Instant time, JsonNode detail, + String sequenceNumber) { + AwsArnUtils.Arn arn = AwsArnUtils.parse(bus.getArn()); + Instant ingested = clock.instant(); + String eventId = UUID.randomUUID().toString(); + + ObjectNode data = JsonNodeFactory.instance.objectNode(); + data.put("version", "0"); + data.put("id", eventId); + data.put("detail-type", entry.get("DetailType").asText()); + data.put("source", entry.get("Source").asText()); + data.put("account", arn.accountId()); + data.put("time", (time == null ? ingested : time).truncatedTo(ChronoUnit.SECONDS).toString()); + data.put("region", arn.region()); + data.set("resources", entry.has("Resources") && entry.get("Resources").isArray() + ? entry.get("Resources") : JsonNodeFactory.instance.arrayNode()); + data.set("detail", detail); + + ObjectNode system = JsonNodeFactory.instance.objectNode(); + system.put("ContentType", PUT_EVENTS_CONTENT_TYPE); + JsonNode supplied = entry.path("SystemMetadata"); + if (supplied.hasNonNull("EventGroupId")) { + system.put("EventGroupId", supplied.get("EventGroupId").asText()); + } + if (supplied.hasNonNull("DeduplicationId")) { + system.put("DeduplicationId", supplied.get("DeduplicationId").asText()); + } + system.put("aws:EventId", eventId); + system.put("aws:IngestionTime", ingested.toString()); + system.put("aws:SequenceNumber", sequenceNumber); + system.put("aws:DeliveryType", "LIVE"); + system.put("aws:Source", entry.get("Source").asText()); + system.put("aws:DetailType", entry.get("DetailType").asText()); + return new PublishedEvent(data, JsonNodeFactory.instance.objectNode(), system); + } + + /** The entry's detail as a JSON object, an empty one when it gives none; null when it is not one. */ + private static JsonNode detail(JsonNode entry) { + JsonNode detail = entry.get("Detail"); + if (detail == null || detail.isNull()) { + return JsonNodeFactory.instance.objectNode(); + } + try { + JsonNode parsed = MAPPER.readTree(detail.asText()); + return parsed != null && parsed.isObject() ? parsed : null; + } catch (Exception ignored) { + // A Detail that is not JSON is the caller's error, reported as that entry's MalformedDetail result. + return null; + } + } + + @Override + public void clear() { + buses.clear(); + subscribers.clear(); + deliveriesByBus.clear(); + } + + // ──────────────────────────── Subscriber settings ──────────────────────────── + + /** A subscriber's settings in the shape of the request that sets them, for an update to overlay. */ + private static ObjectNode currentSettings(SubscriberV2 subscriber) { + ObjectNode settings = JsonNodeFactory.instance.objectNode(); + if (subscriber.getDescription() != null) { + settings.put("Description", subscriber.getDescription()); + } + settings.set("InvokeConfiguration", subscriber.getInvokeConfiguration()); + settings.set("FilterConfiguration", subscriber.getFilterConfiguration()); + settings.set("Transformer", subscriber.getTransformer()); + settings.set("BatchConfiguration", subscriber.getBatchConfiguration()); + settings.set("RetryPolicy", subscriber.getRetryPolicy()); + settings.set("OnFailureConfiguration", subscriber.getOnFailureConfiguration()); + settings.set("LogConfiguration", subscriber.getLogConfiguration()); + settings.put("State", subscriber.getState()); + settings.set("Tags", MAPPER.valueToTree(subscriber.getTags())); + return settings; + } + + private void applySettings(SubscriberV2 subscriber, JsonNode request, JsonNode filterConfiguration) { + subscriber.setDescription(optionalDescription(request)); + subscriber.setInvokeConfiguration(invokeConfiguration(request)); + subscriber.setFilterConfiguration(filterConfiguration); + subscriber.setTransformer(transformer(request)); + subscriber.setBatchConfiguration(boundedIntegers(request, "BatchConfiguration", + Map.of("MaxBatchSize", new int[] {1, 500}, "MaxBatchWindowInSeconds", new int[] {0, 300}))); + JsonNode retryPolicy = boundedIntegers(request, "RetryPolicy", + Map.of("MaxRetryAttempts", new int[] {0, 185}, "MaxEventAgeInSeconds", new int[] {60, 86400})); + if (retryPolicy != null) { + optionalEnum(retryPolicy, "RetryStrategy", Set.of("ALL"), null); + } + subscriber.setRetryPolicy(retryPolicy); + subscriber.setOnFailureConfiguration(onFailureConfiguration(request)); + JsonNode logConfiguration = optionalStructure(request, "LogConfiguration"); + if (logConfiguration != null) { + optionalEnum(logConfiguration, "Level", Set.of("OFF", "ERROR", "INFO"), null); + optionalEnum(logConfiguration, "IncludePayload", Set.of("FULL", "ON_ERROR_ONLY"), null); + } + subscriber.setLogConfiguration(logConfiguration); + subscriber.setState(optionalEnum(request, "State", Set.of(RUNNING, "STOPPED"), RUNNING)); + subscriber.setTags(readTags(request.get("Tags"))); + } + + /** + * The target and its parameters. Floci delivers to an Amazon SQS queue of the caller's, so a target of another + * service or account, or a parameter block other than {@code SqsParameters}, is refused; a parameter is a + * literal or a path into the event. + */ + private JsonNode invokeConfiguration(JsonNode request) { + JsonNode configuration = optionalStructure(request, "InvokeConfiguration"); + if (configuration == null) { + throw invalidInput("InvokeConfiguration is required."); + } + String roleArn = requireText(configuration, "RoleArn"); + if (roleArn.length() > 1600 || !ROLE_ARN.matcher(roleArn).matches()) { + throw invalidInput("InvokeConfiguration.RoleArn must be the ARN of an IAM role."); + } + String targetArn = requireText(configuration, "TargetArn"); + AwsArnUtils.Arn target = AwsArnUtils.isArn(targetArn) ? AwsArnUtils.parse(targetArn) : null; + if (target == null) { + throw invalidInput("InvokeConfiguration.TargetArn must be an ARN."); + } + if (!"sqs".equals(target.service())) { + throw invalidInput("Floci delivers EventBridge V2 events only to Amazon SQS queues; " + + targetArn + " is not one."); + } + if (!regionResolver.getAccountId().equals(target.accountId())) { + throw invalidInput("InvokeConfiguration.TargetArn must belong to your account."); + } + for (String block : PARAMETER_BLOCKS) { + if (!"SqsParameters".equals(block) && configuration.hasNonNull(block)) { + throw invalidInput("InvokeConfiguration." + block + " does not match the target type of " + + targetArn + "."); + } + } + JsonNode parameters = optionalStructure(configuration, "SqsParameters"); + if (parameters != null) { + for (String name : List.of("MessageGroupId", "MessageDeduplicationId", "DelaySeconds")) { + requireSupportedExpression(text(parameters, name), "SqsParameters." + name); + } + JsonNode attributes = optionalStructure(parameters, "MessageAttributes"); + if (attributes != null) { + for (Map.Entry attribute : attributes.properties()) { + requireSupportedExpression(attribute.getKey(), "SqsParameters.MessageAttributes"); + JsonNode stringValue = attribute.getValue().get("StringValue"); + if (stringValue != null && stringValue.isTextual()) { + requireSupportedExpression(stringValue.textValue(), + "SqsParameters.MessageAttributes." + attribute.getKey()); + } + } + } + } + return configuration; + } + + private static void requireSupportedExpression(String value, String parameter) { + if (value != null && !EventExpressions.isSupported(value)) { + throw invalidInput(parameter + " is a JSONata expression Floci does not evaluate; it supports a literal " + + "or a path such as {% $events.SystemMetadata.EventGroupId %}."); + } + } + + private static JsonNode transformer(JsonNode request) { + JsonNode transformer = optionalStructure(request, "Transformer"); + if (transformer == null) { + return null; + } + String type = optionalEnum(transformer, "Type", Set.of("RAW", "WITH_METADATA", "JSONATA"), "RAW"); + if ("JSONATA".equals(type)) { + throw invalidInput("Floci does not evaluate a JSONATA transformer; use RAW or WITH_METADATA."); + } + return transformer; + } + + private static JsonNode onFailureConfiguration(JsonNode request) { + JsonNode configuration = optionalStructure(request, "OnFailureConfiguration"); + if (configuration != null) { + String arn = text(configuration, "Arn"); + if (arn != null && !AwsArnUtils.isArnFor(arn, "sqs")) { + throw invalidInput("OnFailureConfiguration.Arn must be the ARN of an Amazon SQS queue."); + } + } + return configuration; + } + + private static JsonNode pointInTimeConfiguration(JsonNode request, String startingPosition) { + JsonNode configuration = normalizedPointInTime(optionalStructure(request, "PointInTimeConfiguration")); + if (configuration != null) { + optionalEnum(configuration, "PointType", Set.of("HORIZON", "TIMESTAMP"), null); + } else if ("POINT_IN_TIME".equals(startingPosition)) { + throw invalidInput("StartingPosition POINT_IN_TIME requires PointInTimeConfiguration."); + } + return configuration; + } + + /** + * A copy of the point-in-time configuration with its {@code StartingPoint} and {@code EndPoint} as epoch + * seconds at millisecond precision, the form a response encodes as timestamps; null when there is none. + */ + private static JsonNode normalizedPointInTime(JsonNode configuration) { + if (configuration == null || configuration.isNull()) { + return null; + } + if (!(configuration instanceof ObjectNode structure)) { + throw invalidInput("PointInTimeConfiguration must be a structure."); + } + ObjectNode normalized = structure.deepCopy(); + for (String member : List.of("StartingPoint", "EndPoint")) { + Instant point = AwsJsonTimestamp.epochSeconds(structure, member, "InvalidInputException"); + if (point != null) { + normalized.put(member, BigDecimal.valueOf(point.toEpochMilli()).movePointLeft(3)); + } + } + return normalized; + } + + /** The structure, each named integer member of it within its bounds. */ + private static JsonNode boundedIntegers(JsonNode request, String field, Map bounds) { + JsonNode structure = optionalStructure(request, field); + if (structure == null) { + return null; + } + bounds.forEach((member, range) -> { + JsonNode value = structure.get(member); + if (value != null && !value.isNull() && (!value.isIntegralNumber() || !value.canConvertToInt() + || value.intValue() < range[0] || value.intValue() > range[1])) { + throw invalidInput(field + "." + member + " must be between " + range[0] + " and " + range[1] + "."); + } + }); + return structure; + } + + // ──────────────────────────── Lookups ──────────────────────────── + + private EventBusV2 requireEventBus(String eventBusArn, String region) { + return findEventBus(eventBusArn, region).orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Event bus " + eventBusArn + " does not exist.", 404)); + } + + private SubscriberV2 requireSubscriber(String subscriberArn, String region) { + return findSubscriber(subscriberArn, region).orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Subscriber " + subscriberArn + " does not exist.", 404)); + } + + private List subscribersOf(EventBusV2 bus, String region) { + String prefix = region + "::" + bus.getName() + "::"; + return subscribers.scan(key -> key.startsWith(prefix)).stream() + .filter(subscriber -> bus.getArn().equals(subscriber.getEventBusArn())) + .toList(); + } + + /** The bus name an {@code event-busv2//} ARN gives; null for any other value. */ + public static String busName(String eventBusArn) { + if (!AwsArnUtils.isArnFor(eventBusArn, "events")) { + return null; + } + String[] resource = AwsArnUtils.parse(eventBusArn).resource().split("/"); + return resource.length == 3 && "event-busv2".equals(resource[0]) ? resource[1] : null; + } + + private String newId() { + StringBuilder id = new StringBuilder(ID_LENGTH); + for (int i = 0; i < ID_LENGTH; i++) { + id.append(ID_ALPHABET.charAt(random.nextInt(ID_ALPHABET.length()))); + } + return id.toString(); + } + + private static String storageKey(String region, String name) { + return region + "::" + name; + } + + private static String subscriberKey(String region, String busName, String name) { + return region + "::" + busName + "::" + name; + } + + // ──────────────────────────── Validation ──────────────────────────── + + private static String requireName(JsonNode request) { + String name = text(request, "Name"); + if (name == null) { + throw invalidInput("Name is required."); + } + if (name.isEmpty() || name.length() > 256 || !NAME.matcher(name).matches()) { + throw invalidInput("Name must be 1-256 characters, start with a letter or digit, and contain only " + + "letters, digits, '.', '-' and '_'."); + } + return name; + } + + private static String optionalNamePrefix(JsonNode request) { + String namePrefix = text(request, "NamePrefix"); + if (namePrefix != null && (namePrefix.isEmpty() || namePrefix.length() > 256 + || !NAME.matcher(namePrefix).matches())) { + throw invalidInput("NamePrefix must be 1-256 characters, start with a letter or digit, and contain only " + + "letters, digits, '.', '-' and '_'."); + } + return namePrefix; + } + + /** One page of {@code items} in {@code cursorOf} order, as the request's {@code MaxResults} and {@code NextToken} ask. */ + private static PaginatedResult page(List items, Function cursorOf, JsonNode request, + String namespace) { + Integer maxResults = Pagination.parseMaxResults(request, "MaxResults", "InvalidInputException"); + if (maxResults != null && (maxResults < 1 || maxResults > MAX_LIST_RESULTS)) { + throw invalidInput("MaxResults must be between 1 and " + MAX_LIST_RESULTS + "."); + } + String nextToken = Pagination.parseNextToken(request, "NextToken", "InvalidInputException"); + if (nextToken != null && (nextToken.isEmpty() || nextToken.length() > 4096)) { + throw invalidInput("NextToken must be 1-4096 characters."); + } + return Pagination.paginate(items, cursorOf, maxResults == null ? MAX_LIST_RESULTS : maxResults, nextToken, + namespace, token -> invalidInput("NextToken is not valid.")); + } + + private static String optionalDescription(JsonNode request) { + String description = text(request, "Description"); + if (description != null && (description.length() > 512 || !DESCRIPTION.matcher(description).matches())) { + throw invalidInput("Description must be at most 512 characters with no control characters or line " + + "separators."); + } + return description; + } + + private static String optionalKmsKeyIdentifier(JsonNode request) { + JsonNode configuration = optionalStructure(request, "EncryptionConfiguration"); + String key = configuration == null ? null : text(configuration, "KmsKeyIdentifier"); + if (key != null && (key.length() > 2048 || !KMS_KEY_IDENTIFIER.matcher(key).matches())) { + throw invalidInput("EncryptionConfiguration.KmsKeyIdentifier is not a valid KMS key identifier."); + } + return key; + } + + private static Integer optionalRetentionPeriodInDays(JsonNode request) { + JsonNode configuration = optionalStructure(request, "StorageConfiguration"); + JsonNode days = configuration == null ? null : configuration.get("RetentionPeriodInDays"); + if (days == null || days.isNull()) { + return null; + } + if (!days.canConvertToInt() || !days.isIntegralNumber() || days.intValue() < 1 || days.intValue() > 365) { + throw invalidInput("StorageConfiguration.RetentionPeriodInDays must be between 1 and 365."); + } + return days.intValue(); + } + + private static String optionalClientToken(JsonNode request) { + String token = text(request, "ClientToken"); + if (token != null && (token.isEmpty() || token.length() > 64 || !CLIENT_TOKEN.matcher(token).matches())) { + throw invalidInput("ClientToken must be 1-64 printable ASCII characters."); + } + return token; + } + + private static String optionalEnum(JsonNode request, String field, Set values, String defaultValue) { + String value = text(request, field); + if (value == null) { + return defaultValue; + } + if (!values.contains(value)) { + throw invalidInput(field + " must be one of " + String.join(", ", values.stream().sorted().toList()) + "."); + } + return value; + } + + private static Map readTags(JsonNode node) { + Map tags = new LinkedHashMap<>(); + if (node == null || node.isNull()) { + return tags; + } + if (!node.isObject()) { + throw invalidInput("Tags must be a map of tag keys to values."); + } + if (node.size() > MAX_TAGS) { + throw invalidInput("Tags may hold at most " + MAX_TAGS + " tags."); + } + for (Map.Entry tag : node.properties()) { + String key = tag.getKey(); + JsonNode value = tag.getValue(); + if (key.length() > 128 || !TAG_KEY.matcher(key).matches()) { + throw invalidInput("Tag key " + key + " must be 1-128 characters and not start or end with whitespace."); + } + if (!value.isTextual() || value.textValue().length() > 256 + || !TAG_VALUE.matcher(value.textValue()).matches()) { + throw invalidInput("Tag value for " + key + " must be at most 256 characters and not start or end " + + "with whitespace."); + } + tags.put(key, value.textValue()); + } + return tags; + } + + /** + * The request without its {@code ClientToken}, every object's fields in name order, so a retry that sends the same + * values with its fields or tags in another order compares equal to the request it repeats. + */ + private static String withoutClientToken(JsonNode request) { + JsonNode copy = request.deepCopy(); + if (copy instanceof ObjectNode object) { + object.remove("ClientToken"); + } + try { + return CANONICAL.writeValueAsString(CANONICAL.convertValue(copy, Object.class)); + } catch (JsonProcessingException e) { + throw invalidInput("The request cannot be compared with the one its ClientToken was used for."); + } + } + + private static JsonNode optionalStructure(JsonNode request, String field) { + JsonNode node = request.get(field); + if (node == null || node.isNull()) { + return null; + } + if (!node.isObject()) { + throw invalidInput(field + " must be a structure."); + } + return node; + } + + private static String requireText(JsonNode request, String field) { + String value = text(request, field); + if (value == null || value.isEmpty()) { + throw invalidInput(field + " is required."); + } + return value; + } + + private static String text(JsonNode request, String field) { + JsonNode node = request.get(field); + if (node == null || node.isNull()) { + return null; + } + if (!node.isTextual()) { + throw invalidInput(field + " must be a string."); + } + return node.textValue(); + } + + private static AwsException idempotentMismatch(String clientToken) { + return new AwsException("IdempotentParameterMismatchException", + "ClientToken " + clientToken + " was used with a different request.", 409); + } + + private static AwsException invalidInput(String message) { + return new AwsException("InvalidInputException", message, 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventExpressions.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventExpressions.java new file mode 100644 index 0000000000..2851e570a2 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/EventExpressions.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * The JSONata a target parameter may hold, as far as Floci evaluates it: a literal value, or one expression in + * {@code {% %}} that is a path into the event, {@code $events.SystemMetadata.EventGroupId}, whose segments are + * names, {@code "quoted"} or {@code `backquoted`} for a name such as {@code aws:EventId} or {@code detail-type}. + */ +final class EventExpressions { + + private static final Pattern EXPRESSION = Pattern.compile("\\{%[\\s\\S]*%}"); + private static final Pattern PATH = Pattern.compile("\\{%\\s*\\$events((?:\\.(?:[A-Za-z_][A-Za-z0-9_]*" + + "|\"[^\"]+\"|`[^`]+`))+)\\s*%}"); + private static final Pattern SEGMENT = Pattern.compile("\\.([A-Za-z_][A-Za-z0-9_]*|\"([^\"]+)\"|`([^`]+)`)"); + + private EventExpressions() { + } + + static boolean isExpression(String value) { + return value != null && EXPRESSION.matcher(value.trim()).matches(); + } + + /** Whether Floci evaluates the value: a literal, or an expression that is a path into the event. */ + static boolean isSupported(String value) { + return !isExpression(value) || PATH.matcher(value.trim()).matches(); + } + + /** + * The value for one event: a literal as given, a path's value as text (a string unquoted, anything else as + * JSON), or empty when the path names nothing, which fails the delivery as AWS fails it. + */ + static Optional resolve(String value, PublishedEvent event) { + if (!isExpression(value)) { + return Optional.of(value); + } + Matcher path = PATH.matcher(value.trim()); + if (!path.matches()) { + return Optional.empty(); + } + JsonNode node = event.withMetadata(); + for (String segment : segments(path.group(1))) { + node = node == null || !node.isObject() ? null : node.get(segment); + } + if (node == null || node.isNull()) { + return Optional.empty(); + } + return Optional.of(node.isTextual() ? node.textValue() : node.toString()); + } + + private static List segments(String path) { + List segments = new ArrayList<>(); + Matcher segment = SEGMENT.matcher(path); + while (segment.find()) { + segments.add(segment.group(2) != null ? segment.group(2) + : segment.group(3) != null ? segment.group(3) : segment.group(1)); + } + return segments; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/PublishedEvent.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/PublishedEvent.java new file mode 100644 index 0000000000..ea403dff86 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/PublishedEvent.java @@ -0,0 +1,22 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** + * An event on an EventBridge V2 bus, in the three parts filters, transformers and target parameters address: + * {@code Data}, the payload (for {@code PutEvents}, the EventBridge envelope); {@code Metadata}, the producer's + * keys; and {@code SystemMetadata}, the string fields EventBridge assigns. + */ +record PublishedEvent(JsonNode data, ObjectNode metadata, ObjectNode systemMetadata) { + + /** The event as {@code $events} and a {@code WITH_METADATA} delivery hold it. */ + ObjectNode withMetadata() { + ObjectNode event = JsonNodeFactory.instance.objectNode(); + event.set("Data", data); + event.set("Metadata", metadata); + event.set("SystemMetadata", systemMetadata); + return event; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/SubscriberFilters.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/SubscriberFilters.java new file mode 100644 index 0000000000..f633dc0c8f --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/SubscriberFilters.java @@ -0,0 +1,249 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.pipes.PipesFilterMatcher; + +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * An EventBridge V2 subscriber's {@code FilterConfiguration}: at most one EventBridge pattern for each scope of the + * event, {@code DATA}, {@code METADATA} or {@code SYSTEM_METADATA}, every one of which an event must match. + */ +final class SubscriberFilters { + + static final String WILDCARD_MESSAGE = + "Filter pattern must not contain wildcard matchers (wildcard, anything-but wildcard)"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final Set SCOPES = Set.of("DATA", "METADATA", "SYSTEM_METADATA"); + private static final Set NUMERIC_OPERATORS = Set.of("=", ">", ">=", "<", "<="); + private static final int MAX_FILTERS = 50; + private static final int MAX_PATTERN_BYTES = 4096; + private static final int MAX_OR_COMBINATIONS = 1000; + + private SubscriberFilters() { + } + + /** + * Rejects a configuration AWS rejects: one with no filters or an empty pattern, two filters of one scope, a + * pattern that is not JSON, a wildcard, a {@code METADATA} pattern of anything but exact values, a pattern + * that is not an object, more than 1,000 {@code $or} combinations, or patterns over 4,096 bytes in all. + */ + static void validate(JsonNode configuration) { + if (!configuration.isObject()) { + throw invalid("FilterConfiguration must be a structure."); + } + JsonNode language = configuration.get("Language"); + if (language != null && !language.isNull() && !"EVENT_BRIDGE_PATTERN".equals(language.asText())) { + throw invalid("FilterConfiguration.Language must be EVENT_BRIDGE_PATTERN."); + } + JsonNode filters = configuration.get("Filters"); + if (filters == null || !filters.isArray() || filters.isEmpty() || filters.size() > MAX_FILTERS) { + throw invalid("FilterConfiguration.Filters must hold 1 to " + MAX_FILTERS + " filters."); + } + Set scopes = new HashSet<>(); + int bytes = 0; + for (JsonNode filter : filters) { + String scope = filter.path("Scope").asText(null); + if (scope == null || !SCOPES.contains(scope)) { + throw invalid("Filter Scope must be DATA, METADATA or SYSTEM_METADATA."); + } + if (!scopes.add(scope)) { + throw invalid("FilterConfiguration may hold at most one filter for the scope " + scope + "."); + } + JsonNode patternText = filter.get("Pattern"); + if (patternText == null || !patternText.isTextual() || patternText.textValue().isBlank()) { + throw invalid("Filter Pattern must be a non-empty event pattern."); + } + bytes += patternText.textValue().getBytes(StandardCharsets.UTF_8).length; + JsonNode pattern = parse(patternText.textValue()); + if (!pattern.isObject()) { + throw invalid("Filter pattern for the scope " + scope + " must be a JSON object."); + } + checkMatchers(pattern); + if ("METADATA".equals(scope) && !exactValuesOnly(pattern)) { + throw invalid("A METADATA filter pattern must give each key a list of exact values."); + } + if (orCombinations(pattern) > MAX_OR_COMBINATIONS) { + throw invalid("Filter pattern produces more than " + MAX_OR_COMBINATIONS + " combinations."); + } + } + if (bytes > MAX_PATTERN_BYTES) { + throw invalid("FilterConfiguration patterns may total at most " + MAX_PATTERN_BYTES + " bytes."); + } + } + + /** Whether the event matches every filter of the configuration; an absent configuration matches every event. */ + static boolean matches(JsonNode configuration, PublishedEvent event) { + if (configuration == null || configuration.isNull() || !configuration.has("Filters")) { + return true; + } + for (JsonNode filter : configuration.get("Filters")) { + JsonNode scope = switch (filter.path("Scope").asText()) { + case "DATA" -> event.data(); + case "METADATA" -> event.metadata(); + default -> event.systemMetadata(); + }; + if (!PipesFilterMatcher.matches(parse(filter.path("Pattern").asText()), scope)) { + return false; + } + } + return true; + } + + private static JsonNode parse(String pattern) { + try { + return MAPPER.readTree(pattern); + } catch (Exception e) { + throw invalid("Filter pattern is not valid JSON."); + } + } + + /** + * Refuses a wildcard, as AWS does, and a matcher {@link PipesFilterMatcher} cannot evaluate, which would + * otherwise match no event or every event without a word. A matcher is an object in a field's list of values; + * an object anywhere else is a nested pattern, so a field named after an operator is matched as a field. + */ + private static void checkMatchers(JsonNode pattern) { + for (Map.Entry field : pattern.properties()) { + JsonNode value = field.getValue(); + boolean or = "$or".equals(field.getKey()); + if (or && (!value.isArray() || value.size() < 2)) { + throw invalid("Filter pattern $or must be a list of at least two patterns."); + } + if (value.isObject()) { + checkMatchers(value); + } else if (value.isArray()) { + if (value.isEmpty()) { + throw invalid("Filter pattern field " + field.getKey() + " must contain at least one value."); + } + for (JsonNode element : value) { + if (or && element.isObject()) { + checkMatchers(element); + } else if (or) { + throw invalid("Filter pattern $or must be a list of patterns."); + } else if (element.isObject()) { + checkMatcher(element); + } else if (element.isArray()) { + throw invalid("Filter pattern field " + field.getKey() + " must list values and matchers, " + + "not lists."); + } + } + } else { + throw invalid("Filter pattern field " + field.getKey() + " must be a list of values or a nested " + + "pattern."); + } + } + } + + private static void checkMatcher(JsonNode matcher) { + JsonNode anythingBut = matcher.get("anything-but"); + if (matcher.has("wildcard") || anythingBut != null && anythingBut.has("wildcard")) { + throw invalid(WILDCARD_MESSAGE); + } + String operator = matcher.size() == 1 ? matcher.fieldNames().next() : ""; + JsonNode operand = matcher.path(operator); + boolean supported = switch (operator) { + case "exists" -> operand.isBoolean(); + case "prefix", "suffix" -> operand.isTextual() || ignoringCase(operand); + case "equals-ignore-case" -> operand.isTextual(); + case "numeric" -> numericConditions(operand); + case "anything-but" -> operand.isValueNode() + || operand.isArray() && !operand.isEmpty() && allValues(operand) + || operand.size() == 1 && (operand.path("prefix").isTextual() + || operand.path("suffix").isTextual() || operand.path("equals-ignore-case").isTextual() + || operand.path("equals-ignore-case").isArray() + && !operand.path("equals-ignore-case").isEmpty() + && allValues(operand.get("equals-ignore-case"))); + default -> false; + }; + if (!supported) { + throw invalid("Floci does not evaluate the filter matcher " + matcher + "; it supports exact values, " + + "prefix, suffix, equals-ignore-case, anything-but, numeric, exists and $or."); + } + } + + /** Whether the operand is one or more pairs of a comparison operator and a number. */ + private static boolean numericConditions(JsonNode operand) { + if (!operand.isArray() || operand.isEmpty() || operand.size() % 2 != 0) { + return false; + } + for (int i = 0; i < operand.size(); i += 2) { + JsonNode operator = operand.get(i); + if (!operator.isTextual() || !NUMERIC_OPERATORS.contains(operator.textValue()) + || !operand.get(i + 1).isNumber()) { + return false; + } + } + return true; + } + + private static boolean ignoringCase(JsonNode operand) { + return operand.isObject() && operand.size() == 1 && operand.path("equals-ignore-case").isTextual(); + } + + private static boolean allValues(JsonNode array) { + for (JsonNode element : array) { + if (!element.isValueNode()) { + return false; + } + } + return true; + } + + private static boolean exactValuesOnly(JsonNode pattern) { + Iterator> fields = pattern.fields(); + while (fields.hasNext()) { + JsonNode values = fields.next().getValue(); + if (!values.isArray() || values.isEmpty()) { + return false; + } + for (JsonNode value : values) { + if (!value.isTextual()) { + return false; + } + } + } + return true; + } + + /** + * The number of patterns the {@code $or} lists expand to. The branches of one {@code $or} are alternatives, so + * their counts add up; the fields of a pattern must all match, so theirs multiply. Counting stops once it passes + * the limit. + */ + private static long orCombinations(JsonNode node) { + if (!node.isObject()) { + return 1; + } + long combinations = 1; + for (Map.Entry field : node.properties()) { + long fieldCombinations = 0; + if ("$or".equals(field.getKey())) { + for (JsonNode branch : field.getValue()) { + fieldCombinations += orCombinations(branch); + if (fieldCombinations > MAX_OR_COMBINATIONS) { + return fieldCombinations; + } + } + } else { + fieldCombinations = orCombinations(field.getValue()); + } + combinations *= Math.max(1, fieldCombinations); + if (combinations > MAX_OR_COMBINATIONS) { + return combinations; + } + } + return combinations; + } + + private static AwsException invalid(String message) { + return new AwsException("InvalidInputException", message, 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/model/EventBusV2.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/model/EventBusV2.java new file mode 100644 index 0000000000..f7bfc6b243 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/model/EventBusV2.java @@ -0,0 +1,127 @@ +package io.github.hectorvent.floci.services.eventbridgev2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; + +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class EventBusV2 { + private String name; + private String arn; + private String description; + private String kmsKeyIdentifier; + private Integer retentionPeriodInDays; + private String state; + private Instant creationTime; + private Instant lastModifiedTime; + private Map tags = new LinkedHashMap<>(); + private String clientToken; + private String createRequest; + private long sequenceNumber; + + public EventBusV2() { + } + + /** The sequence number of the last event the bus accepted; the next is one more. */ + public long getSequenceNumber() { + return sequenceNumber; + } + + public void setSequenceNumber(long sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getArn() { + return arn; + } + + public void setArn(String arn) { + this.arn = arn; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getKmsKeyIdentifier() { + return kmsKeyIdentifier; + } + + public void setKmsKeyIdentifier(String kmsKeyIdentifier) { + this.kmsKeyIdentifier = kmsKeyIdentifier; + } + + public Integer getRetentionPeriodInDays() { + return retentionPeriodInDays; + } + + public void setRetentionPeriodInDays(Integer retentionPeriodInDays) { + this.retentionPeriodInDays = retentionPeriodInDays; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public Instant getCreationTime() { + return creationTime; + } + + public void setCreationTime(Instant creationTime) { + this.creationTime = creationTime; + } + + public Instant getLastModifiedTime() { + return lastModifiedTime; + } + + public void setLastModifiedTime(Instant lastModifiedTime) { + this.lastModifiedTime = lastModifiedTime; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags == null ? new LinkedHashMap<>() : tags; + } + + /** The {@code ClientToken} the bus was created with, which makes a retried create return it. */ + public String getClientToken() { + return clientToken; + } + + public void setClientToken(String clientToken) { + this.clientToken = clientToken; + } + + /** The create request without its client token, which a retry with the same token must repeat. */ + public String getCreateRequest() { + return createRequest; + } + + public void setCreateRequest(String createRequest) { + this.createRequest = createRequest; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/model/SubscriberV2.java b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/model/SubscriberV2.java new file mode 100644 index 0000000000..bda941521e --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridgev2/model/SubscriberV2.java @@ -0,0 +1,201 @@ +package io.github.hectorvent.floci.services.eventbridgev2.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.JsonNode; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.time.Instant; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * An EventBridge V2 subscriber. The configuration structures are kept as the request gave them, as the + * subscriber returns them. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class SubscriberV2 { + private String name; + private String arn; + private String eventBusArn; + private String description; + private String type; + private String startingPosition; + private String state; + private JsonNode pointInTimeConfiguration; + private JsonNode invokeConfiguration; + private JsonNode filterConfiguration; + private JsonNode transformer; + private JsonNode batchConfiguration; + private JsonNode retryPolicy; + private JsonNode onFailureConfiguration; + private JsonNode logConfiguration; + private Instant creationTime; + private Instant lastModifiedTime; + private Map tags = new LinkedHashMap<>(); + private String clientToken; + private String createRequest; + + public SubscriberV2() { + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getArn() { + return arn; + } + + public void setArn(String arn) { + this.arn = arn; + } + + public String getEventBusArn() { + return eventBusArn; + } + + public void setEventBusArn(String eventBusArn) { + this.eventBusArn = eventBusArn; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getStartingPosition() { + return startingPosition; + } + + public void setStartingPosition(String startingPosition) { + this.startingPosition = startingPosition; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public JsonNode getPointInTimeConfiguration() { + return pointInTimeConfiguration; + } + + public void setPointInTimeConfiguration(JsonNode pointInTimeConfiguration) { + this.pointInTimeConfiguration = pointInTimeConfiguration; + } + + public JsonNode getInvokeConfiguration() { + return invokeConfiguration; + } + + public void setInvokeConfiguration(JsonNode invokeConfiguration) { + this.invokeConfiguration = invokeConfiguration; + } + + public JsonNode getFilterConfiguration() { + return filterConfiguration; + } + + public void setFilterConfiguration(JsonNode filterConfiguration) { + this.filterConfiguration = filterConfiguration; + } + + public JsonNode getTransformer() { + return transformer; + } + + public void setTransformer(JsonNode transformer) { + this.transformer = transformer; + } + + public JsonNode getBatchConfiguration() { + return batchConfiguration; + } + + public void setBatchConfiguration(JsonNode batchConfiguration) { + this.batchConfiguration = batchConfiguration; + } + + public JsonNode getRetryPolicy() { + return retryPolicy; + } + + public void setRetryPolicy(JsonNode retryPolicy) { + this.retryPolicy = retryPolicy; + } + + public JsonNode getOnFailureConfiguration() { + return onFailureConfiguration; + } + + public void setOnFailureConfiguration(JsonNode onFailureConfiguration) { + this.onFailureConfiguration = onFailureConfiguration; + } + + public JsonNode getLogConfiguration() { + return logConfiguration; + } + + public void setLogConfiguration(JsonNode logConfiguration) { + this.logConfiguration = logConfiguration; + } + + public Instant getCreationTime() { + return creationTime; + } + + public void setCreationTime(Instant creationTime) { + this.creationTime = creationTime; + } + + public Instant getLastModifiedTime() { + return lastModifiedTime; + } + + public void setLastModifiedTime(Instant lastModifiedTime) { + this.lastModifiedTime = lastModifiedTime; + } + + public Map getTags() { + return tags; + } + + public void setTags(Map tags) { + this.tags = tags == null ? new LinkedHashMap<>() : tags; + } + + public String getClientToken() { + return clientToken; + } + + public void setClientToken(String clientToken) { + this.clientToken = clientToken; + } + + public String getCreateRequest() { + return createRequest; + } + + public void setCreateRequest(String createRequest) { + this.createRequest = createRequest; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java index 45695e3ecb..2ecd883ced 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java @@ -1875,28 +1875,39 @@ public class LambdaService implements ResourceProvider { /** Operators AWS documents that the matcher does not implement, rejected with a clearer message. */ private static final Set UNIMPLEMENTED_FILTER_OPERATORS = Set.of("cidr", "wildcard"); - /** Comparisons {@code matchesNumericFilter} understands. Anything else evaluates false for every record. */ + /** Comparisons {@code PipesFilterMatcher} understands. It treats a pattern with any other as matching nothing. */ private static final Set NUMERIC_COMPARISONS = Set.of("=", ">", ">=", "<", "<="); /** * Validates the recursive shape of an EventBridge filter pattern: every field value must be either a - * non-empty match array (a leaf) or a nested object (recursed into). A scalar or empty-array value is a + * non-empty match array (a leaf) or a nested object (recursed into), and {@code $or} a non-empty list of + * patterns, each validated the same way. A scalar or empty-array value is a * pattern the matcher can never satisfy, so, with enforcement active, it would silently drop every * record; reject it at create/update instead. * *

Match-array elements are validated against the operator set the matcher implements. This does couple * the validator to {@code PipesFilterMatcher}, which is deliberate: now that the pollers enforce filters, - * a pattern the matcher cannot satisfy is destructive rather than inert. A bad operand silently corrupts - * delivery instead of erroring, and the failure direction is not even consistent. {@code - * {"numeric":[">","abc"]}} coerces its operand to zero and matches every positive value, {@code - * {"numeric":[">"]}} matches every record because the comparison loop never runs, and an unknown operator - * matches nothing, so every record is checkpointed past or deleted. Failing at create/update is the only + * a pattern the matcher cannot evaluate is destructive rather than inert. The matcher refuses an unknown + * operator or a bad operand such as {@code {"numeric":[">","abc"]}}, and the pollers treat a refused pattern + * as matching nothing, so every record is checkpointed past or deleted. Failing at create/update is the only * point where the caller can still act on it. */ private static void validatePatternStructure(JsonNode node) { for (Map.Entry entry : node.properties()) { JsonNode value = entry.getValue(); - if (value.isArray()) { + if ("$or".equals(entry.getKey())) { + if (!value.isArray() || value.isEmpty()) { + throw new AwsException("InvalidParameterValueException", + "Filter Pattern field '$or' must be a non-empty list of patterns", 400); + } + for (JsonNode branch : value) { + if (!branch.isObject()) { + throw new AwsException("InvalidParameterValueException", + "Filter Pattern field '$or' must be a non-empty list of patterns", 400); + } + validatePatternStructure(branch); + } + } else if (value.isArray()) { if (value.isEmpty()) { throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + entry.getKey() + "' must have a non-empty match array", 400); @@ -1914,17 +1925,17 @@ public class LambdaService implements ResourceProvider { } /** - * A match-array element is either a literal the matcher compares directly (string, number, or null for - * "absent") or a single-operator object. Two operators in one object is rejected because the matcher + * A match-array element is either a literal the matcher compares directly (string, number, boolean, or + * null) or a single-operator object. Two operators in one object is rejected because the matcher * tests them in a fixed order and silently honours only the first. */ private static void validateMatchElement(String field, JsonNode element) { - if (element.isTextual() || element.isNumber() || element.isNull()) { + if (element.isTextual() || element.isNumber() || element.isBoolean() || element.isNull()) { return; } if (!element.isObject()) { throw new AwsException("InvalidParameterValueException", "Filter Pattern field '" + field - + "' has an invalid match value: expected a string, number, null, or an operator object", 400); + + "' has an invalid match value: expected a string, number, boolean, null, or an operator object", 400); } List operators = new ArrayList<>(); element.fieldNames().forEachRemaining(operators::add); diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesFilterMatcher.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesFilterMatcher.java index 35ac24992b..ef2b804c97 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesFilterMatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesFilterMatcher.java @@ -6,12 +6,22 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import org.jboss.logging.Logger; +import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; +/** + * EventBridge event pattern matching, shared by EventBridge Pipes, the Lambda event source mappings and the + * EventBridge V2 subscribers. A field's pattern is a list of alternatives, any of which matches, or a nested + * pattern for an object; {@code $or} takes a list of patterns, any of which matches. A field whose value is an + * array matches when any of its elements does. + * + *

A pattern the matcher cannot evaluate throws {@link IllegalArgumentException}: whether that is refused up + * front or treated as matching nothing is the calling service's choice. + */ @ApplicationScoped public class PipesFilterMatcher { @@ -55,149 +65,242 @@ public class PipesFilterMatcher { return false; } + /** + * Whether a source record matches the pattern. A string field the pattern nests an object under is parsed as + * JSON first, as for an SQS {@code body} or a Kinesis {@code data}. A pattern that is not valid matches nothing. + */ boolean matchesRecord(JsonNode record, String pattern) { if (pattern == null || pattern.isBlank()) { return true; } try { - JsonNode patternNode = objectMapper.readTree(pattern); - return matchesNode(record, patternNode); - } catch (Exception e) { - LOG.warnv("Failed to parse filter pattern: {0}", e.getMessage()); + return matches(objectMapper.readTree(pattern), record, objectMapper); + } catch (IllegalArgumentException | IOException e) { + LOG.warnv("Invalid filter pattern {0}: {1}", pattern, e.getMessage()); return false; } } - private boolean matchesNode(JsonNode actual, JsonNode pattern) { + /** + * Whether the document matches the pattern, as EventBridge matches it. + * + * @throws IllegalArgumentException if the pattern is not one the matcher can evaluate + */ + public static boolean matches(JsonNode pattern, JsonNode actual) { + return matches(pattern, actual, null); + } + + /** {@code decoder}, when given, parses a string field the pattern nests an object under. */ + private static boolean matches(JsonNode pattern, JsonNode actual, ObjectMapper decoder) { if (!pattern.isObject()) { - return false; + throw new IllegalArgumentException("a pattern must be a JSON object"); } Iterator> fields = pattern.fields(); while (fields.hasNext()) { Map.Entry field = fields.next(); - String key = field.getKey(); - JsonNode patternValue = field.getValue(); - JsonNode actualValue = actual.path(key); - - if (patternValue.isArray()) { - if (!matchesArrayField(patternValue, actualValue)) { + if ("$or".equals(field.getKey())) { + if (!anyMatches(field.getValue(), actual, decoder)) { return false; } - } else if (patternValue.isObject()) { - JsonNode resolvedActual = resolveActualForObject(actualValue); - if (!matchesNode(resolvedActual, patternValue)) { + continue; + } + JsonNode value = actual == null || !actual.isObject() ? null : actual.get(field.getKey()); + JsonNode expected = field.getValue(); + if (expected.isObject()) { + boolean nestedMatches = value == null + ? matches(expected, null, decoder) + : matchesNested(expected, decoded(value, decoder), decoder); + if (!nestedMatches) { + return false; + } + } else if (expected.isArray()) { + if (!matchesAlternatives(field.getKey(), expected, value)) { return false; } } else { - LOG.warnv("Invalid filter pattern: scalar value for key \"{0}\". " + - "Pattern values must be arrays or objects.", key); - return false; + throw new IllegalArgumentException("field " + field.getKey() + + " must be a list of values or a nested pattern"); } } return true; } - private JsonNode resolveActualForObject(JsonNode actualValue) { - if (actualValue.isTextual()) { - try { - JsonNode parsed = objectMapper.readTree(actualValue.asText()); - if (parsed.isObject() || parsed.isArray()) { - return parsed; - } - } catch (Exception ignored) { - } + private static boolean anyMatches(JsonNode patterns, JsonNode actual, ObjectMapper decoder) { + if (!patterns.isArray()) { + throw new IllegalArgumentException("$or must be a list of patterns"); } - return actualValue; - } - - private boolean matchesArrayField(JsonNode patternArray, JsonNode actualValue) { - for (JsonNode element : patternArray) { - if (matchesSingleElement(element, actualValue)) { + for (JsonNode pattern : patterns) { + if (matches(pattern, actual, decoder)) { return true; } } return false; } - private boolean matchesSingleElement(JsonNode element, JsonNode actualValue) { - boolean valueExists = !actualValue.isMissingNode() && !actualValue.isNull(); - String actualStr = valueExists && actualValue.isTextual() ? actualValue.asText() : null; + private static JsonNode decoded(JsonNode value, ObjectMapper decoder) { + if (decoder == null || !value.isTextual()) { + return value; + } + try { + JsonNode parsed = decoder.readTree(value.textValue()); + if (parsed != null && (parsed.isObject() || parsed.isArray())) { + return parsed; + } + } catch (IOException ignored) { + // Not JSON: matched as the string it is, which a nested pattern never matches. + } + return value; + } - if (element.isTextual()) { - return actualStr != null && actualStr.equals(element.asText()); - } - if (element.isNull()) { - return !valueExists; - } - if (element.isNumber()) { - return valueExists && actualValue.isNumber() - && actualValue.decimalValue().compareTo(element.decimalValue()) == 0; - } - if (element.isObject()) { - if (element.has("prefix")) { - return actualStr != null && actualStr.startsWith(element.get("prefix").asText()); - } - if (element.has("suffix")) { - return actualStr != null && actualStr.endsWith(element.get("suffix").asText()); - } - if (element.has("equals-ignore-case")) { - return actualStr != null && actualStr.equalsIgnoreCase(element.get("equals-ignore-case").asText()); - } - if (element.has("anything-but")) { - JsonNode anythingBut = element.get("anything-but"); - if (anythingBut.isArray()) { - if (!valueExists) { - return true; - } - for (JsonNode v : anythingBut) { - if (v.isTextual() && v.asText().equals(actualStr)) { - return false; - } - if (v.isNumber() && actualValue.isNumber() - && actualValue.decimalValue().compareTo(v.decimalValue()) == 0) { - return false; - } - } + private static boolean matchesNested(JsonNode pattern, JsonNode value, ObjectMapper decoder) { + if (value.isArray()) { + for (JsonNode element : value) { + if (matches(pattern, element, decoder)) { return true; } - if (anythingBut.isObject() && anythingBut.has("prefix")) { - return !valueExists || (actualStr != null && !actualStr.startsWith(anythingBut.get("prefix").asText())); - } - if (anythingBut.isTextual()) { - return !valueExists || (actualStr != null && !actualStr.equals(anythingBut.asText())); - } } - if (element.has("exists")) { - boolean shouldExist = element.get("exists").asBoolean(); - return shouldExist == valueExists; + return false; + } + return matches(pattern, value, decoder); + } + + /** Whether the field, absent as null, matches any of the alternatives. */ + private static boolean matchesAlternatives(String field, JsonNode alternatives, JsonNode value) { + for (JsonNode alternative : alternatives) { + if (alternative.isArray()) { + throw new IllegalArgumentException("field " + field + " must list values and matchers, not lists"); } - if (element.has("numeric")) { - return matchesNumericFilter(element.get("numeric"), actualValue); + if (alternative.isObject() && alternative.has("exists")) { + if (alternative.get("exists").asBoolean() == (value != null)) { + return true; + } + continue; + } + if (value == null) { + continue; + } + if (value.isArray()) { + for (JsonNode element : value) { + if (matchesOne(alternative, element)) { + return true; + } + } + } else if (matchesOne(alternative, value)) { + return true; } } return false; } - private boolean matchesNumericFilter(JsonNode numericArray, JsonNode actualValue) { - if (!actualValue.isNumber() || !numericArray.isArray()) { + private static boolean matchesOne(JsonNode alternative, JsonNode value) { + if (!alternative.isObject()) { + return equalsExactly(alternative, value); + } + if (alternative.has("prefix")) { + return matchesAffix(alternative.get("prefix"), value, true); + } + if (alternative.has("suffix")) { + return matchesAffix(alternative.get("suffix"), value, false); + } + if (alternative.has("equals-ignore-case")) { + return value.isTextual() && value.textValue().equalsIgnoreCase(alternative.get("equals-ignore-case").asText()); + } + if (alternative.has("numeric")) { + return matchesNumeric(alternative.get("numeric"), value); + } + if (alternative.has("anything-but")) { + return !matchesExcluded(alternative.get("anything-but"), value); + } + throw new IllegalArgumentException("unsupported matcher " + alternative); + } + + private static boolean matchesExcluded(JsonNode excluded, JsonNode value) { + if (excluded.isArray()) { + for (JsonNode each : excluded) { + if (equalsExactly(each, value)) { + return true; + } + } return false; } - BigDecimal actual = actualValue.decimalValue(); - for (int i = 0; i + 1 < numericArray.size(); i += 2) { - String op = numericArray.get(i).asText(); - BigDecimal operand = numericArray.get(i + 1).decimalValue(); - boolean result = switch (op) { - case "=" -> actual.compareTo(operand) == 0; - case ">" -> actual.compareTo(operand) > 0; - case ">=" -> actual.compareTo(operand) >= 0; - case "<" -> actual.compareTo(operand) < 0; - case "<=" -> actual.compareTo(operand) <= 0; - default -> false; + if (excluded.isObject()) { + if (excluded.has("prefix")) { + return matchesAffix(excluded.get("prefix"), value, true); + } + if (excluded.has("suffix")) { + return matchesAffix(excluded.get("suffix"), value, false); + } + if (excluded.has("equals-ignore-case")) { + JsonNode names = excluded.get("equals-ignore-case"); + for (JsonNode name : names.isArray() ? names : List.of(names)) { + if (value.isTextual() && value.textValue().equalsIgnoreCase(name.asText())) { + return true; + } + } + return false; + } + throw new IllegalArgumentException("unsupported anything-but matcher " + excluded); + } + return equalsExactly(excluded, value); + } + + /** A prefix or suffix, given as a string or as {@code {"equals-ignore-case": ...}}. */ + private static boolean matchesAffix(JsonNode affix, JsonNode value, boolean prefix) { + if (!value.isTextual()) { + return false; + } + String text = value.textValue(); + if (affix.isObject() && affix.has("equals-ignore-case")) { + String wanted = affix.get("equals-ignore-case").asText(); + return text.length() >= wanted.length() && (prefix + ? text.regionMatches(true, 0, wanted, 0, wanted.length()) + : text.regionMatches(true, text.length() - wanted.length(), wanted, 0, wanted.length())); + } + return prefix ? text.startsWith(affix.asText()) : text.endsWith(affix.asText()); + } + + private static boolean matchesNumeric(JsonNode conditions, JsonNode value) { + if (!conditions.isArray() || conditions.isEmpty() || conditions.size() % 2 != 0) { + throw new IllegalArgumentException("numeric takes pairs of a comparison and a number"); + } + if (!value.isNumber()) { + return false; + } + BigDecimal actual = value.decimalValue(); + for (int i = 0; i < conditions.size(); i += 2) { + JsonNode operand = conditions.get(i + 1); + if (!operand.isNumber()) { + throw new IllegalArgumentException("numeric operand " + operand + " is not a number"); + } + int compared = actual.compareTo(operand.decimalValue()); + boolean holds = switch (conditions.get(i).asText()) { + case "=" -> compared == 0; + case ">" -> compared > 0; + case ">=" -> compared >= 0; + case "<" -> compared < 0; + case "<=" -> compared <= 0; + default -> throw new IllegalArgumentException("unsupported numeric comparison " + conditions.get(i)); }; - if (!result) { + if (!holds) { return false; } } return true; } + + private static boolean equalsExactly(JsonNode expected, JsonNode value) { + if (expected.isNull()) { + return value.isNull(); + } + if (expected.isNumber()) { + return value.isNumber() && expected.decimalValue().compareTo(value.decimalValue()) == 0; + } + if (expected.isTextual()) { + return value.isTextual() && expected.textValue().equals(value.textValue()); + } + if (expected.isBoolean()) { + return value.isBoolean() && expected.booleanValue() == value.booleanValue(); + } + return false; + } } diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 124c720815..d1e13a7388 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -608,6 +608,8 @@ floci: default-neo4j-image: "neo4j:5-community" eventbridge: enabled: true + eventbridgev2: + enabled: true cloudmap: enabled: true emr: diff --git a/src/main/resources/aws/iam-request-resources.json b/src/main/resources/aws/iam-request-resources.json index faecc90ab7..cc3001c433 100644 --- a/src/main/resources/aws/iam-request-resources.json +++ b/src/main/resources/aws/iam-request-resources.json @@ -1,7 +1,7 @@ { "_source": {"generator": "tools/aws/regen_iam_request_resources.py", "reference": "https://servicereference.us-east-1.amazonaws.com/", "botocore": "botocore 1.43.113 (installed package)", "retrieved": "2026-11-01", "note": "make iam-request-resources-check re-derives every operation's resources from botocore; make iam-request-resources-verify checks every action, type and format against AWS."}, - "namespaces": {"acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "events": ["events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]}, - "clientsNotRead": {"eventbridgev2": "EventBridge V2, the AWSEventsV2 target over Smithy RPC v2 CBOR on the eventsv2 endpoint, which Floci does not serve; its operations share EventBridge's names and name their resources by other members", "kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members"}, + "namespaces": {"acm": ["acm"], "application-autoscaling": ["application-autoscaling"], "athena": ["athena"], "bcm-data-exports": ["bcm-data-exports"], "bcm-pricing-calculator": ["bcm-pricing-calculator"], "budgets": ["budgets"], "ce": ["ce"], "cloudtrail": ["cloudtrail"], "codebuild": ["codebuild"], "codepipeline": ["codepipeline"], "cognito-identity": ["cognito-identity"], "cognito-idp": ["cognito-idp"], "cur": ["cur"], "ecr": ["ecr"], "elasticloadbalancing": ["elb", "elbv2"], "events": ["eventbridgev2", "events"], "firehose": ["firehose"], "globalaccelerator": ["globalaccelerator"], "kinesisanalytics": ["kinesisanalyticsv2"], "servicediscovery": ["servicediscovery"], "servicequotas": ["service-quotas"], "states": ["stepfunctions"], "textract": ["textract"], "timestream-influxdb": ["timestream-influxdb"], "translate": ["translate"]}, + "clientsNotRead": {"kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and name their resources by other members"}, "handBuilt": ["apigateway", "bedrock", "dsql", "dynamodb", "eks", "iam", "kinesis", "kms", "lambda", "logs", "pipes", "resource-groups", "s3", "scheduler", "secretsmanager", "sns", "sqs", "ssm", "sts"], "notCovered": {"access-analyzer": "REST: its requests name their resources in the path, which RequestResources does not read yet", "account": "REST: its requests name their resources in the path, which RequestResources does not read yet", "airflow": "REST: its requests name their resources in the path, which RequestResources does not read yet", "app-integrations": "REST: its requests name their resources in the path, which RequestResources does not read yet", "appconfig": "REST: its requests name their resources in the path, which RequestResources does not read yet", "appsync": "REST: its requests name their resources in the path, which RequestResources does not read yet", "aps": "REST: its requests name their resources in the path, which RequestResources does not read yet", "autoscaling": "not read yet: AWS's group and launch configuration ARNs carry an id the service mints, `autoScalingGroup::autoScalingGroupName/`, while Floci mints `autoScalingGroup:`, which other services (ECS capacity providers) read back; the mint is fixed first", "aws-marketplace": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "backup": "REST: its requests name their resources in the path, which RequestResources does not read yet", "batch": "REST: its requests name their resources in the path, which RequestResources does not read yet", "bedrock-agentcore": "REST: its requests name their resources in the path, which RequestResources does not read yet", "cloudformation": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "cloudfront": "REST: its requests name their resources in the path, which RequestResources does not read yet", "cloudhsm": "not read yet: its ARN formats end in ${CloudHsmClusterInstanceName} and ${CloudHsmBackupInstanceName}, names, while its requests give ClusterId and BackupId, ids, which the rule does not fill a name from, so nearly every operation needs a correction", "cloudwatch": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "codeartifact": "REST: its requests name their resources in the path, which RequestResources does not read yet", "codedeploy": "not read yet: the Service Reference gives an on-premises instance's ARN as `instance:${InstanceName}`, while the CodeDeploy permissions reference gives arn:aws:codedeploy:region:account-id:instance/instance-ID and AWS's GetOnPremisesInstance example answers instance/_, an id the service mints after the name; reading it needs that format corrected", "codeguru-reviewer": "REST: its requests name their resources in the path, which RequestResources does not read yet", "comprehend": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "config": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "connect": "REST: its requests name their resources in the path, which RequestResources does not read yet", "controlcatalog": "REST: its requests name their resources in the path, which RequestResources does not read yet", "controltower": "REST: its requests name their resources in the path, which RequestResources does not read yet", "datasync": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "detective": "REST: its requests name their resources in the path, which RequestResources does not read yet", "dlm": "REST: its requests name their resources in the path, which RequestResources does not read yet", "dms": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ec2": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ecs": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticache": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticbeanstalk": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "elasticfilesystem": "REST: its requests name their resources in the path, which RequestResources does not read yet", "elasticmapreduce": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "emr-serverless": "REST: its requests name their resources in the path, which RequestResources does not read yet", "es": "REST: its requests name their resources in the path, which RequestResources does not read yet", "execute-api": "REST: its requests name their resources in the path, which RequestResources does not read yet", "fis": "REST: its requests name their resources in the path, which RequestResources does not read yet", "glue": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "guardduty": "REST: its requests name their resources in the path, which RequestResources does not read yet", "identitystore": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "inspector2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "iot": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "kafka": "REST: its requests name their resources in the path, which RequestResources does not read yet", "lightsail": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "macie2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "memorydb": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "mq": "REST: its requests name their resources in the path, which RequestResources does not read yet", "network-firewall": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "oam": "REST: its requests name their resources in the path, which RequestResources does not read yet", "organizations": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "ram": "REST: its requests name their resources in the path, which RequestResources does not read yet", "rds": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rds-data": "REST: its requests name their resources in the path, which RequestResources does not read yet", "redshift": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "redshift-data": "not read yet: a serverless workgroup's ARN ends in an id the service mints, `workgroup/`, while its requests name the workgroup by WorkgroupName, a name or an ARN, so its resource is the stored ARN that name finds, a FOUND_BY type its service does not look up yet", "redshift-serverless": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rekognition": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "resource-explorer-2": "REST: its requests name their resources in the path, which RequestResources does not read yet", "route53": "REST: its requests name their resources in the path, which RequestResources does not read yet", "route53resolver": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "rum": "REST: its requests name their resources in the path, which RequestResources does not read yet", "s3tables": "REST: its requests name their resources in the path, which RequestResources does not read yet", "s3vectors": "REST: its requests name their resources in the path, which RequestResources does not read yet", "sagemaker": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "securityhub": "REST: its requests name their resources in the path, which RequestResources does not read yet", "servicecatalog": "not read yet: CreatePortfolioShare, UpdatePortfolioShare and DeletePortfolioShare give in AccountId the account a portfolio is shared with, which the rule reads as the portfolio's; a portfolio or product imported from another account keeps its owner's account in its ARN while requests name it by its id alone; and AppRegistry's applications and attribute groups are named in the path", "ses": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "signin": "REST: its requests name their resources in the path, which RequestResources does not read yet", "sso": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "sso-oauth": "REST: its requests name their resources in the path, which RequestResources does not read yet", "swf": "not read yet: the Service Reference gives a domain's ARN no Region, `swf:::/domain/`, while the SWF Developer Guide gives it as arn:aws:swf:Region:AccountID:/domain/DomainName, as Floci mints it; reading it needs that format corrected", "transcribe": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "transfer": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint", "verifiedpermissions": "not read yet: a policyStoreId may name its store by an alias, `policy-store-alias/`, which AWS authorizes as the action on the store the alias points to and GetPolicyStoreAlias on the alias, and an aliasName carries the `policy-store-alias/` its format already gives; reading it needs both", "wafv2": "not read yet: a later batch, with the tests that show its ARNs are the ones its handlers mint"}, "otherNamespaces": ["a4b", "account-access", "acm-pca", "aco-automation", "agent-registry", "aidevops", "aiops", "airflow-serverless", "amplify", "amplifybackend", "amplifyuibuilder", "aoss", "appfabric", "appflow", "application-signals", "application-signals-mcp", "appmesh", "appmesh-preview", "apprunner", "appstream", "apptest", "arc-region-switch", "arc-zonal-shift", "artifact", "assurance", "auditmanager", "aws-external-anthropic", "b2bi", "backup-gateway", "backup-search", "bedrock-mantle", "bedrock-websearch", "billing", "billingconductor", "braket", "bugbust", "cases", "cassandra", "chatbot", "chime", "cleanrooms", "cleanrooms-ml", "cloud9", "clouddirectory", "cloudfront-keyvaluestore", "cloudsearch", "cloudshell", "cloudtrail-data", "codecatalyst", "codecommit", "codeconnections", "codeguru-profiler", "codeguru-security", "codestar-connections", "codestar-notifications", "codewhisperer", "cognito-sync", "connect-campaigns", "consoleapp", "continuum", "databrew", "dataexchange", "datapipeline", "datazone", "dax", "deadline", "devicefarm", "devops-guru", "directconnect", "docdb-elastic", "drs", "ds", "ds-data", "ebs", "ec2-instance-connect", "ecr-public", "eks-auth", "elastictranscoder", "elemental-appliances-software", "elemental-inference", "elemental-support-cases", "emr-containers", "end-user-messaging", "entityresolution", "evs", "finspace", "finspace-api", "fms", "forecast", "frauddetector", "freertos", "fsx", "gamelift", "gameliftstreams", "geo", "geo-maps", "geo-places", "geo-routes", "glacier", "grafana", "greengrass", "groundstation", "health", "health-agent", "healthlake", "honeycode", "identity-sync", "imagebuilder", "interconnect", "internetmonitor", "invoicing", "iotanalytics", "iotdeviceadvisor", "iotfleethub", "iotfleetwise", "iotjobsdata", "iotmanagedintegrations", "iotsitewise", "iottwinmaker", "iotwireless", "iq", "iq-permission", "ivs", "ivschat", "kafka-cluster", "kafkaconnect", "kendra", "kendra-ranking", "kinesisvideo", "launchwizard", "lex", "license-manager", "license-manager-linux-subscriptions", "license-manager-user-subscriptions", "lookoutequipment", "lookoutmetrics", "lookoutvision", "m2", "machinelearning", "managedblockchain", "mapcredits", "mediaconnect", "mediaconvert", "medialive", "mediapackage", "mediapackage-vod", "mediapackagev2", "mediastore", "mediatailor", "medical-imaging", "mgh", "mgn", "migrationhub-orchestrator", "mobiletargeting", "monitron", "mpa", "neptune-db", "neptune-graph", "network-security-manager", "networkflowmonitor", "networkmanager", "networkmonitor", "nimble", "notifications", "notifications-contacts", "nova-act", "observabilityadmin", "odb", "omics", "one", "opensearch", "opsworks", "osis", "outposts", "panorama", "partnercentral", "payment-cryptography", "payments", "pca-connector-ad", "pca-connector-scep", "pcs", "personalize", "pi", "polly", "private-networks", "profile", "proton", "purchase-orders", "q", "qapps", "qbusiness", "qdeveloper", "qldb", "quicksight", "rbin", "rds-db", "refactor-spaces", "repostspace", "resiliencehub", "robomaker", "rolesanywhere", "route53-recovery-cluster", "route53-recovery-control-config", "route53-recovery-readiness", "route53globalresolver", "route53profiles", "rtbfabric", "s3-object-lambda", "s3-outposts", "s3express", "s3files", "sagemaker-geospatial", "sagemaker-mlflow", "savingsplans", "schemas", "scn", "sdb", "security-ir", "securityagent", "securitylake", "serverlessrepo", "shield", "signer", "simspaceweaver", "sms-voice", "snow-device-management", "social-messaging", "sqlworkbench", "ssm-contacts", "ssm-incidents", "ssm-quicksetup", "ssm-sap", "storagegateway", "supportauthz", "synthetics", "thinclient", "timestream", "tnb", "transform", "transform-custom", "trustedadvisor", "ts", "vendor-insights", "voiceid", "vpc-lattice", "vpc-lattice-svcs", "vpce", "waf", "waf-regional", "wellarchitected", "wickr", "wisdom", "workdocs", "worklink", "workmail", "workmailmessageflow", "workspaces", "workspaces-instances", "workspaces-web", "xray"], @@ -714,39 +714,39 @@ "elasticloadbalancing:SetSubnets": {"action": "elasticloadbalancing:SetSubnets", "types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "resources": [{"types": ["loadbalancer/app/", "loadbalancer/gwy/", "loadbalancer/net/"], "arn": "LoadBalancerArn"}]}, "events:ActivateEventSource": {"action": "events:ActivateEventSource", "types": ["event-source"], "resources": [{"type": "event-source", "fill": {"EventSourceName": "Name"}}]}, "events:CancelReplay": {"action": "events:CancelReplay", "types": ["replay"], "resources": [{"type": "replay", "fill": {"ReplayName": "ReplayName"}}]}, - "events:CreateApiDestination": {"action": "events:CreateApiDestination", "types": ["api-destination", "connection"], "resources": [{"types": ["api-destination", "connection"], "arn": "ConnectionArn"}, {"type": "api-destination", "fill": {"ApiDestinationName": "Name"}}]}, - "events:CreateArchive": {"action": "events:CreateArchive", "types": ["alias", "archive", "event-bus", "key"], "resources": [{"types": ["alias", "archive", "event-bus", "key"], "arn": "EventSourceArn"}, {"type": "archive", "fill": {"ArchiveName": "ArchiveName"}}]}, + "events:CreateApiDestination": {"action": "events:CreateApiDestination", "types": ["api-destination", "connection"], "resources": [{"types": ["api-destination", "connection"], "arn": "ConnectionArn"}, {"type": "api-destination", "fill": {"ApiDestinationName": "Name"}, "made": true}]}, + "events:CreateArchive": {"action": "events:CreateArchive", "types": ["alias", "archive", "event-bus", "key"], "resources": [{"types": ["alias", "archive", "event-bus", "key"], "arn": "EventSourceArn"}, {"type": "archive", "fill": {"ArchiveName": "ArchiveName"}, "made": true}]}, "events:CreateConnection": {"action": "events:CreateConnection", "types": ["connection"], "resources": [{"type": "connection", "fill": {"ConnectionName": "Name"}}]}, "events:CreateEndpoint": {"action": "events:CreateEndpoint", "types": ["endpoint"], "resources": [{"types": ["endpoint"], "arn": "EventBuses[].EventBusArn"}, {"types": ["endpoint"], "arn": "RoleArn"}, {"type": "endpoint", "fill": {"EndpointName": "Name"}}]}, - "events:CreateEventBus": {"action": "events:CreateEventBus", "types": ["event-bus", "event-busv2"], "resources": [{"types": ["event-bus", "event-busv2"], "arn": "DeadLetterConfig.Arn"}, {"type": "event-bus", "fill": {"EventBusName": "Name"}}]}, - "events:CreateEventSource": {"action": "events:CreateEventSource", "types": ["event-busv2", "event-sourcev2"], "resources": []}, + "events:CreateEventBus": {"action": "events:CreateEventBus", "types": ["event-bus", "event-busv2"], "resources": [{"types": ["event-bus", "event-busv2"], "arn": "DeadLetterConfig.Arn", "endpoint": "events"}, {"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events", "made": true}, {"type": "event-busv2", "fill": {"EventBusName": "Name"}, "endpoint": "eventsv2"}]}, + "events:CreateEventSource": {"action": "events:CreateEventSource", "types": ["event-busv2", "event-sourcev2"], "resources": [{"types": ["event-busv2", "event-sourcev2"], "arn": "EventBusArn"}]}, "events:CreatePartnerEventSource": {"action": "events:CreatePartnerEventSource", "types": ["event-source"], "resources": [{"type": "event-source", "fill": {"EventSourceName": "Name"}}]}, - "events:CreateSubscriber": {"action": "events:CreateSubscriber", "types": ["event-busv2", "subscriber"], "resources": [{"type": "subscriber", "fill": {}}]}, + "events:CreateSubscriber": {"action": "events:CreateSubscriber", "types": ["event-busv2", "subscriber"], "resources": [{"types": ["event-busv2", "subscriber"], "arn": "EventBusArn"}, {"types": ["event-busv2", "subscriber"], "arn": "InvokeConfiguration.RoleArn"}, {"types": ["event-busv2", "subscriber"], "arn": "InvokeConfiguration.TargetArn"}, {"types": ["event-busv2", "subscriber"], "arn": "OnFailureConfiguration.Arn"}, {"type": "subscriber", "fill": {"SubscriberName": "Name"}, "made": true}]}, "events:DeactivateEventSource": {"action": "events:DeactivateEventSource", "types": ["event-source"], "resources": [{"type": "event-source", "fill": {"EventSourceName": "Name"}}]}, "events:DeauthorizeConnection": {"action": "events:DeauthorizeConnection", "types": ["connection"], "resources": [{"type": "connection", "fill": {"ConnectionName": "Name"}}]}, "events:DeleteApiDestination": {"action": "events:DeleteApiDestination", "types": ["api-destination"], "resources": [{"type": "api-destination", "fill": {"ApiDestinationName": "Name"}}]}, "events:DeleteArchive": {"action": "events:DeleteArchive", "types": ["archive"], "resources": [{"type": "archive", "fill": {"ArchiveName": "ArchiveName"}}]}, "events:DeleteConnection": {"action": "events:DeleteConnection", "types": ["connection"], "resources": [{"type": "connection", "fill": {"ConnectionName": "Name"}}]}, "events:DeleteEndpoint": {"action": "events:DeleteEndpoint", "types": ["endpoint"], "resources": [{"type": "endpoint", "fill": {"EndpointName": "Name"}}]}, - "events:DeleteEventBus": {"action": "events:DeleteEventBus", "types": ["event-bus", "event-busv2"], "resources": [{"type": "event-bus", "fill": {"EventBusName": "Name"}}]}, - "events:DeleteEventSource": {"action": "events:DeleteEventSource", "types": ["event-sourcev2"], "resources": []}, + "events:DeleteEventBus": {"action": "events:DeleteEventBus", "types": ["event-bus", "event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, {"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events"}]}, + "events:DeleteEventSource": {"action": "events:DeleteEventSource", "types": ["event-sourcev2"], "resources": [{"types": ["event-sourcev2"], "arn": "EventSourceArn"}]}, "events:DeletePartnerEventSource": {"action": "events:DeletePartnerEventSource", "types": ["event-source"], "resources": [{"type": "event-source", "fill": {"EventSourceName": "Name"}}]}, - "events:DeleteResourcePolicy": {"action": "events:DeleteResourcePolicy", "types": ["event-busv2"], "resources": []}, + "events:DeleteResourcePolicy": {"action": "events:DeleteResourcePolicy", "types": ["event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "ResourceArn"}]}, "events:DeleteRule": {"action": "events:DeleteRule", "types": ["rule-on-custom-event-bus", "rule-on-default-event-bus"], "resources": [{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Name"}, "when": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}, {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Name"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]}, - "events:DeleteSubscriber": {"action": "events:DeleteSubscriber", "types": ["subscriber"], "resources": []}, + "events:DeleteSubscriber": {"action": "events:DeleteSubscriber", "types": ["subscriber"], "resources": [{"types": ["subscriber"], "arn": "SubscriberArn"}]}, "events:DescribeApiDestination": {"action": "events:DescribeApiDestination", "types": ["api-destination", "connection"], "resources": [{"type": "api-destination", "fill": {"ApiDestinationName": "Name"}}]}, "events:DescribeArchive": {"action": "events:DescribeArchive", "types": ["archive"], "resources": [{"type": "archive", "fill": {"ArchiveName": "ArchiveName"}}]}, "events:DescribeConnection": {"action": "events:DescribeConnection", "types": ["connection"], "resources": [{"type": "connection", "fill": {"ConnectionName": "Name"}}]}, "events:DescribeEndpoint": {"action": "events:DescribeEndpoint", "types": ["endpoint"], "resources": [{"type": "endpoint", "fill": {"EndpointName": "Name"}}]}, - "events:DescribeEventBus": {"action": "events:DescribeEventBus", "types": ["event-bus", "event-busv2"], "resources": [{"type": "event-bus", "fill": {"EventBusName": "Name"}, "absent": {"Name": "default"}, "arnOf": {"Name": "event-bus"}}]}, - "events:DescribeEventSource": {"action": "events:DescribeEventSource", "types": ["event-source", "event-sourcev2"], "resources": [{"type": "event-source", "fill": {"EventSourceName": "Name"}}]}, + "events:DescribeEventBus": {"action": "events:DescribeEventBus", "types": ["event-bus", "event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, {"type": "event-bus", "fill": {"EventBusName": "Name"}, "absent": {"Name": "default"}, "endpoint": "events", "arnOf": {"Name": "event-bus"}}]}, + "events:DescribeEventSource": {"action": "events:DescribeEventSource", "types": ["event-source", "event-sourcev2"], "resources": [{"types": ["event-sourcev2"], "arn": "EventSourceArn", "endpoint": "eventsv2"}, {"type": "event-source", "fill": {"EventSourceName": "Name"}, "endpoint": "events"}]}, "events:DescribePartnerEventSource": {"action": "events:DescribePartnerEventSource", "types": ["event-source"], "resources": [{"type": "event-source", "fill": {"EventSourceName": "Name"}}]}, "events:DescribeReplay": {"action": "events:DescribeReplay", "types": ["replay"], "resources": [{"type": "replay", "fill": {"ReplayName": "ReplayName"}}]}, "events:DescribeRule": {"action": "events:DescribeRule", "types": ["rule-on-custom-event-bus", "rule-on-default-event-bus"], "resources": [{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Name"}, "when": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}, {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Name"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]}, - "events:DescribeSubscriber": {"action": "events:DescribeSubscriber", "types": ["subscriber"], "resources": []}, + "events:DescribeSubscriber": {"action": "events:DescribeSubscriber", "types": ["subscriber"], "resources": [{"types": ["subscriber"], "arn": "SubscriberArn"}]}, "events:DisableRule": {"action": "events:DisableRule", "types": ["rule-on-custom-event-bus", "rule-on-default-event-bus"], "resources": [{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Name"}, "when": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}, {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Name"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]}, "events:EnableRule": {"action": "events:EnableRule", "types": ["rule-on-custom-event-bus", "rule-on-default-event-bus"], "resources": [{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Name"}, "when": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}, {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Name"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]}, - "events:GetResourcePolicy": {"action": "events:GetResourcePolicy", "types": ["event-busv2"], "resources": []}, + "events:GetResourcePolicy": {"action": "events:GetResourcePolicy", "types": ["event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "ResourceArn"}]}, "events:ListApiDestinations": {"action": "events:ListApiDestinations", "types": [], "resources": []}, "events:ListArchives": {"action": "events:ListArchives", "types": [], "resources": []}, "events:ListConnections": {"action": "events:ListConnections", "types": [], "resources": []}, @@ -756,33 +756,33 @@ "events:ListPartnerEventSourceAccounts": {"action": "events:ListPartnerEventSourceAccounts", "types": ["event-source"], "resources": [{"type": "event-source", "fill": {"EventSourceName": "EventSourceName"}}]}, "events:ListPartnerEventSources": {"action": "events:ListPartnerEventSources", "types": [], "resources": []}, "events:ListReplays": {"action": "events:ListReplays", "types": [], "resources": []}, - "events:ListResourcePolicies": {"action": "events:ListResourcePolicies", "types": ["event-busv2"], "resources": []}, + "events:ListResourcePolicies": {"action": "events:ListResourcePolicies", "types": ["event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "ResourceArn"}]}, "events:ListRuleNamesByTarget": {"action": "events:ListRuleNamesByTarget", "types": [], "resources": []}, "events:ListRules": {"action": "events:ListRules", "types": [], "resources": []}, "events:ListSubscribers": {"action": "events:ListSubscribers", "types": [], "resources": []}, - "events:ListTagsForResource": {"action": "events:ListTagsForResource", "types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "resources": [{"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceARN"}]}, + "events:ListTagsForResource": {"action": "events:ListTagsForResource", "types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "resources": [{"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceARN"}, {"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceArn"}]}, "events:ListTargetsByRule": {"action": "events:ListTargetsByRule", "types": ["rule-on-custom-event-bus", "rule-on-default-event-bus"], "resources": [{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Rule"}, "when": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}, {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Rule"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]}, - "events:PutEvents": {"action": "events:PutEvents", "types": ["event-bus", "event-busv2"], "resources": [{"type": "event-bus", "fill": {"EventBusName": "Entries[].EventBusName"}, "absent": {"Entries[].EventBusName": "default"}, "arnOf": {"Entries[].EventBusName": "event-bus"}}]}, + "events:PutEvents": {"action": "events:PutEvents", "types": ["event-bus", "event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, {"type": "event-bus", "fill": {"EventBusName": "Entries[].EventBusName"}, "absent": {"Entries[].EventBusName": "default"}, "endpoint": "events", "arnOf": {"Entries[].EventBusName": "event-bus"}}]}, "events:PutPartnerEvents": {"action": "events:PutPartnerEvents", "types": [], "resources": []}, "events:PutPermission": {"action": "events:PutPermission", "types": [], "resources": []}, - "events:PutRawEvents": {"action": "events:PutRawEvents", "types": ["event-busv2"], "resources": []}, - "events:PutResourcePolicy": {"action": "events:PutResourcePolicy", "types": ["event-busv2"], "resources": []}, + "events:PutRawEvents": {"action": "events:PutRawEvents", "types": ["event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "EventBusArn"}]}, + "events:PutResourcePolicy": {"action": "events:PutResourcePolicy", "types": ["event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "ResourceArn"}]}, "events:PutRule": {"action": "events:PutRule", "types": ["rule-on-custom-event-bus", "rule-on-default-event-bus"], "resources": [{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Name"}, "when": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}, {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Name"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]}, "events:PutTargets": {"action": "events:PutTargets", "types": ["rule-on-custom-event-bus", "rule-on-default-event-bus"], "resources": [{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Rule"}, "when": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}, {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Rule"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]}, "events:RemovePermission": {"action": "events:RemovePermission", "types": [], "resources": []}, "events:RemoveTargets": {"action": "events:RemoveTargets", "types": ["rule-on-custom-event-bus", "rule-on-default-event-bus"], "resources": [{"type": "rule-on-default-event-bus", "fill": {"RuleName": "Rule"}, "when": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}, {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Rule"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}]}, - "events:RevokeResource": {"action": "events:RevokeResource", "types": ["event-busv2"], "resources": []}, - "events:StartReplay": {"action": "events:StartReplay", "types": ["archive", "event-bus", "replay"], "resources": [{"types": ["archive", "event-bus", "replay"], "arn": "Destination.Arn"}, {"types": ["archive", "event-bus", "replay"], "arn": "Destination.FilterArns[]"}, {"types": ["archive", "event-bus", "replay"], "arn": "EventSourceArn"}, {"type": "replay", "fill": {"ReplayName": "ReplayName"}}]}, - "events:TagResource": {"action": "events:TagResource", "types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "resources": [{"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceARN"}]}, + "events:RevokeResource": {"action": "events:RevokeResource", "types": ["event-busv2"], "resources": [{"types": ["event-busv2"], "arn": "Arn"}]}, + "events:StartReplay": {"action": "events:StartReplay", "types": ["archive", "event-bus", "replay"], "resources": [{"types": ["archive", "event-bus", "replay"], "arn": "Destination.Arn"}, {"types": ["archive", "event-bus", "replay"], "arn": "Destination.FilterArns[]"}, {"types": ["archive", "event-bus", "replay"], "arn": "EventSourceArn"}, {"type": "replay", "fill": {"ReplayName": "ReplayName"}, "made": true}]}, + "events:TagResource": {"action": "events:TagResource", "types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "resources": [{"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceARN"}, {"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceArn"}]}, "events:TestEventPattern": {"action": "events:TestEventPattern", "types": [], "resources": []}, - "events:UntagResource": {"action": "events:UntagResource", "types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "resources": [{"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceARN"}]}, + "events:UntagResource": {"action": "events:UntagResource", "types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "resources": [{"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceARN"}, {"types": ["event-bus", "event-busv2", "event-sourcev2", "rule-on-custom-event-bus", "rule-on-default-event-bus", "subscriber"], "arn": "ResourceArn"}]}, "events:UpdateApiDestination": {"action": "events:UpdateApiDestination", "types": ["api-destination"], "resources": [{"types": ["api-destination"], "arn": "ConnectionArn"}, {"type": "api-destination", "fill": {"ApiDestinationName": "Name"}}]}, "events:UpdateArchive": {"action": "events:UpdateArchive", "types": ["alias", "archive", "key"], "resources": [{"type": "archive", "fill": {"ArchiveName": "ArchiveName"}}]}, "events:UpdateConnection": {"action": "events:UpdateConnection", "types": ["connection"], "resources": [{"type": "connection", "fill": {"ConnectionName": "Name"}}]}, "events:UpdateEndpoint": {"action": "events:UpdateEndpoint", "types": ["endpoint"], "resources": [{"types": ["endpoint"], "arn": "EventBuses[].EventBusArn"}, {"types": ["endpoint"], "arn": "RoleArn"}, {"type": "endpoint", "fill": {"EndpointName": "Name"}}]}, - "events:UpdateEventBus": {"action": "events:UpdateEventBus", "types": ["event-bus", "event-busv2"], "resources": [{"types": ["event-bus", "event-busv2"], "arn": "DeadLetterConfig.Arn"}, {"type": "event-bus", "fill": {"EventBusName": "Name"}}]}, - "events:UpdateEventSource": {"action": "events:UpdateEventSource", "types": ["event-busv2", "event-sourcev2"], "resources": []}, - "events:UpdateSubscriber": {"action": "events:UpdateSubscriber", "types": ["event-busv2", "subscriber"], "resources": []}, + "events:UpdateEventBus": {"action": "events:UpdateEventBus", "types": ["event-bus", "event-busv2"], "resources": [{"types": ["event-bus", "event-busv2"], "arn": "DeadLetterConfig.Arn", "endpoint": "events"}, {"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, {"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events"}]}, + "events:UpdateEventSource": {"action": "events:UpdateEventSource", "types": ["event-busv2", "event-sourcev2"], "resources": [{"types": ["event-busv2", "event-sourcev2"], "arn": "EventSourceArn"}]}, + "events:UpdateSubscriber": {"action": "events:UpdateSubscriber", "types": ["event-busv2", "subscriber"], "resources": [{"types": ["event-busv2", "subscriber"], "arn": "InvokeConfiguration.RoleArn"}, {"types": ["event-busv2", "subscriber"], "arn": "OnFailureConfiguration.Arn"}, {"types": ["event-busv2", "subscriber"], "arn": "SubscriberArn"}]}, "firehose:CreateDeliveryStream": {"action": "firehose:CreateDeliveryStream", "types": ["deliverystream"], "resources": [{"types": ["deliverystream"], "arn": "AmazonOpenSearchServerlessDestinationConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "AmazonopensearchserviceDestinationConfiguration.DomainARN"}, {"types": ["deliverystream"], "arn": "AmazonopensearchserviceDestinationConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "DeliveryStreamEncryptionConfigurationInput.KeyARN"}, {"types": ["deliverystream"], "arn": "ElasticsearchDestinationConfiguration.DomainARN"}, {"types": ["deliverystream"], "arn": "ElasticsearchDestinationConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "ExtendedS3DestinationConfiguration.BucketARN"}, {"types": ["deliverystream"], "arn": "ExtendedS3DestinationConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "HttpEndpointDestinationConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "IcebergDestinationConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "KinesisStreamSourceConfiguration.KinesisStreamARN"}, {"types": ["deliverystream"], "arn": "KinesisStreamSourceConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "MSKSourceConfiguration.MSKClusterARN"}, {"types": ["deliverystream"], "arn": "RedshiftDestinationConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "S3DestinationConfiguration.BucketARN"}, {"types": ["deliverystream"], "arn": "S3DestinationConfiguration.RoleARN"}, {"types": ["deliverystream"], "arn": "SnowflakeDestinationConfiguration.RoleARN"}, {"type": "deliverystream", "fill": {"DeliveryStreamName": "DeliveryStreamName"}}]}, "firehose:DeleteDeliveryStream": {"action": "firehose:DeleteDeliveryStream", "types": ["deliverystream"], "resources": [{"type": "deliverystream", "fill": {"DeliveryStreamName": "DeliveryStreamName"}}]}, "firehose:DescribeDeliveryStream": {"action": "firehose:DescribeDeliveryStream", "types": ["deliverystream"], "resources": [{"type": "deliverystream", "fill": {"DeliveryStreamName": "DeliveryStreamName"}}]}, diff --git a/src/test/java/io/github/hectorvent/floci/core/common/AwsJsonCborSerializerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/AwsJsonCborSerializerTest.java index 0927e7e69f..8c63ca3a88 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/AwsJsonCborSerializerTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/AwsJsonCborSerializerTest.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.cbor.CBORFactory; import org.junit.jupiter.api.Test; +import java.util.Set; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -101,6 +103,22 @@ class AwsJsonCborSerializerTest { assertEquals(1700000000.5, cborMapper.readTree(cbor).path("Timestamp").asDouble()); } + @Test + void smithyRpcV2DeclaredTimestampMembersAreTaggedWhereverTheyAppear() throws Exception { + // EventBridge V2 names its timestamps CreationTime and LastModifiedTime, which the suffix heuristic misses. + JsonNode node = jsonMapper.readTree("{\"CreationTime\": 1700000000, \"Period\": 60," + + " \"EventBuses\": [{\"LastModifiedTime\": 1700000001.5}]}"); + + assertEquals(0, countTag1(AwsJsonCborController.nodeToSmithyCbor(node))); + byte[] cbor = AwsJsonCborController.nodeToSmithyCbor(node, Set.of("CreationTime", "LastModifiedTime")); + + assertEquals(2, countTag1(cbor), "each declared timestamp member must be tagged, and nothing else"); + JsonNode decoded = cborMapper.readTree(cbor); + assertEquals(1700000000L, decoded.path("CreationTime").asLong()); + assertEquals(1700000001.5, decoded.path("EventBuses").path(0).path("LastModifiedTime").asDouble()); + assertEquals(60L, decoded.path("Period").asLong()); + } + @Test void smithyRpcV2NonTimestampNumberIsNotTagged() throws Exception { // A plain numeric field (e.g. CloudWatch Period) must remain an untagged integer. diff --git a/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeAliasTest.java b/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeAliasTest.java index e19a143457..8c1dc9b6cd 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeAliasTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/CredentialScopeAliasTest.java @@ -45,6 +45,13 @@ class CredentialScopeAliasTest { } + @Test + void eventBridgeV2NormalisesToEvents() { + // EventBridge V2 signs as events and its actions are events:CreateSubscriber and peers, but it + // cannot claim the events scope, which routes to EventBridge, so its catalog key is aliased. + assertEquals("events", catalog.canonicalCredentialScope("eventsv2")); + } + @Test void ssoPortalAliasNormalisesToSso() { assertEquals("sso", catalog.canonicalCredentialScope("awsssoportal")); diff --git a/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java index 6695b100ec..ac644dc3a5 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/PartitionCrossServiceSmokeIntegrationTest.java @@ -1,5 +1,7 @@ package io.github.hectorvent.floci.core.common; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; import io.github.hectorvent.floci.testing.PartitionCleanup; import io.github.hectorvent.floci.testing.PartitionMatrix; import io.github.hectorvent.floci.testing.PartitionMatrix.PartitionCase; @@ -16,6 +18,7 @@ import org.junit.jupiter.params.provider.MethodSource; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Base64; +import java.util.Map; import java.util.Set; import static io.restassured.RestAssured.given; @@ -43,7 +46,7 @@ class PartitionCrossServiceSmokeIntegrationTest { "cloudfront", "cloudmap", "cloudwatch", "codebuild", "codedeploy", "codepipeline", "cognito", "configservice", "connect", "controlcatalog", "controltower", "datasync", "dlm", "dms", "dsql", "dynamodb", "ec2", "ecr", "ecs", "efs", "eks", "elasticache", "elasticbeanstalk", "elb", "elbv2", "emr", "emrserverless", - "eventbridge", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda", + "eventbridge", "eventbridgev2", "firehose", "fis", "glue", "guardduty", "iot", "kinesis", "kinesisanalytics", "lambda", "lambdamicrovms", "lambdaweb", "memorydb", "msk", "mwaa", "networkfirewall", "oam", "opensearch", "organizations", "pipes", "ram", "rds", "redshift", "redshiftserverless", "resourceexplorer2", "resourcegroups", "route53resolver", "s3tables", "s3vectors", "sagemaker", "scheduler", "secretsmanager", "servicequotas", "ses", "sns", "sqs", @@ -1027,6 +1030,21 @@ class PartitionCrossServiceSmokeIntegrationTest { PartitionMatrix.assertArnIn(partitionCase, arn); } + @ParameterizedTest + @MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES) + void eventBridgeV2EventBusArn(PartitionCase partitionCase) throws Exception { + String region = offered(partitionCase, "events"); + ObjectMapper cbor = new ObjectMapper(new CBORFactory()); + byte[] body = signed(region, "events") + .header("smithy-protocol", "rpc-v2-cbor") + .contentType("application/cbor") + .accept("application/cbor") + .body(cbor.writeValueAsBytes(Map.of("Name", unique("smoke-busv2", partitionCase)))) + .when().post("/service/AWSEventsV2/operation/CreateEventBus").then().statusCode(200) + .extract().asByteArray(); + PartitionMatrix.assertArnIn(partitionCase, cbor.readTree(body).path("EventBusArn").asText()); + } + @ParameterizedTest @MethodSource(PartitionMatrix.NON_COMMERCIAL_CASES) void accessAnalyzerArn(PartitionCase partitionCase) { diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java index c9a39cea8f..0ad83c11fc 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourceMembersTest.java @@ -17,6 +17,7 @@ import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -139,7 +140,7 @@ class RequestResourceMembersTest { // only a member filling a variable is. Member each = new Member("A", true, new Member("Name", false)); assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", each), Map.of(), Map.of(), - Map.of("A[].Name", "default"), Map.of("A[].Name", "thing"), null, null, Map.of(), false)), + Map.of("A[].Name", "default"), Map.of("A[].Name", "thing"), null, null, Map.of(), false, null)), parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A[].Name\"}," + "\"absent\":{\"A[].Name\":\"default\"},\"arnOf\":{\"A[].Name\":\"thing\"}}")) .operations().get("a:Op")); @@ -151,7 +152,7 @@ class RequestResourceMembersTest { // A field of a structure fills a variable, as one value. Member field = new Member("A", false, new Member("Name", false)); assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", field), Map.of(), Map.of(), - Map.of("A.Name", "default"), Map.of(), null, null, Map.of(), false)), + Map.of("A.Name", "default"), Map.of(), null, null, Map.of(), false, null)), parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"A.Name\"}," + "\"absent\":{\"A.Name\":\"default\"}}")).operations().get("a:Op")); assertEquals("A.Name", field.path()); @@ -159,7 +160,7 @@ class RequestResourceMembersTest { // or to no value. String owned = "\"arnFormats\":{\"a\":{\"thing\":\"arn:${Partition}:a:${Region}:${Account}:thing/${Owner}/${ThingName}\"}}"; assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Name", false)), Map.of(), - Map.of(), Map.of(), Map.of(), null, null, Map.of("Owner", "Custom"), false)), + Map.of(), Map.of(), Map.of(), null, null, Map.of("Owner", "Custom"), false, null)), parseUnchecked(document(owned, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"}," + "\"fixed\":{\"Owner\":\"Custom\"}}")).operations().get("a:Op")); for (String bad : List.of("{\"Other\":\"Custom\"}", "{\"ThingName\":\"Custom\"}", "{\"Owner\":\"\"}", @@ -177,7 +178,7 @@ class RequestResourceMembersTest { "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"},\"made\":" + bad + "}")), bad); } assertEquals(List.of(new Resource(List.of("thing"), new Member("A", true, new Member("ThingArns", true)), Map.of(), - Map.of(), Map.of(), Map.of(), Map.of(), null, null, Map.of(), false)), parseUnchecked(document(formats, "{\"types\":[\"thing\"],\"arn\":\"A[].ThingArns[]\"}")) + Map.of(), Map.of(), Map.of(), Map.of(), null, null, Map.of(), false, null)), parseUnchecked(document(formats, "{\"types\":[\"thing\"],\"arn\":\"A[].ThingArns[]\"}")) .operations().get("a:Op")); // A member read before more than one character, holding an ARN or filling a variable. assertThrows(IllegalStateException.class, () -> parse(document(formats, @@ -217,12 +218,12 @@ class RequestResourceMembersTest { } assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Name", false)), Map.of(), Map.of("Bus", List.of("default")), Map.of("Bus", "default"), Map.of("Bus", "thing"), null, null, - Map.of(), false)), + Map.of(), false, null)), parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Name\"}," + "\"unless\":{\"Bus\":[\"default\"]},\"absent\":{\"Bus\":\"default\"}," + "\"arnOf\":{\"Bus\":\"thing\"}}")).operations().get("a:Op")); assertEquals(List.of(new Resource(List.of("thing"), null, Map.of("ThingName", new Member("Names", true)), Map.of(), - Map.of(), Map.of(), Map.of(), new Member("registryId", false), null, Map.of(), false)), + Map.of(), Map.of(), Map.of(), new Member("registryId", false), null, Map.of(), false, null)), parseUnchecked(document(formats, "{\"type\":\"thing\",\"fill\":{\"ThingName\":\"Names[]\"}," + "\"account\":\"registryId\"}")).operations().get("a:Op")); } @@ -263,15 +264,18 @@ class RequestResourceMembersTest { form.append('&').append(parameter(member)).append('=').append(encoded(value)); }); List named = operation.getValue().stream() - .filter(other -> other == resource || named(other)) + .filter(other -> other == resource || named(other) && (other.endpoint() == null + || resource.endpoint() == null || other.endpoint().equals(resource.endpoint()))) .map(other -> other == resource ? expected : expected( table.formats().get(namespace).get(other.types().getFirst()).format(), other, "000000000000")) .distinct().toList(); - assertEquals(named, RequestResources.of(operation.getKey(), json(body.toString()), - "aws", "us-east-1", "000000000000"), body.toString()); - assertEquals(named, RequestResources.of(operation.getKey(), form(form.toString()), - "aws", "us-east-1", "000000000000"), form.toString()); + assertEquals(named, RequestResources.of(operation.getKey(), + servedBy(json(body.toString()), resource.endpoint()), "aws", "us-east-1", "000000000000"), + body.toString()); + assertEquals(named, RequestResources.of(operation.getKey(), + servedBy(form(form.toString()), resource.endpoint()), "aws", "us-east-1", "000000000000"), + form.toString()); }))); } @@ -369,6 +373,18 @@ class RequestResourceMembersTest { return URLEncoder.encode(value, StandardCharsets.UTF_8); } + /** The request as the service of the endpoint prefix serves it; as no known service when there is none. */ + static ContainerRequestContext servedBy(ContainerRequestContext request, String endpoint) { + if (endpoint != null) { + ServiceDescriptor service = new ServiceDescriptor(endpoint, endpoint, true, true, null, null, 0L, null, + ServiceProtocol.JSON, Set.of(ServiceProtocol.JSON), Set.of(), Set.of(), Set.of(), Set.of(), + Set.of()); + when(request.getProperty(AwsProtocolClaimFilter.CLAIM_PROPERTY)) + .thenReturn(new ProtocolClaim(WireProtocol.AWS_JSON_1_1, service, null, null)); + } + return request; + } + private static ContainerRequestContext json(String body) { return request("application/x-amz-json-1.1", body); } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourcesTest.java b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourcesTest.java index 5d3650e682..b9f9016e1b 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/RequestResourcesTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/RequestResourcesTest.java @@ -1,10 +1,14 @@ package io.github.hectorvent.floci.core.common; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.core.MediaType; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; @@ -16,6 +20,7 @@ import static org.mockito.Mockito.when; /** How {@link RequestResources} builds the ARNs of the resources a request names. */ class RequestResourcesTest { + private static final ObjectMapper CBOR = new ObjectMapper(new CBORFactory()); private static final String MACHINE = "arn:aws:states:us-east-1:000000000000:stateMachine:orders"; @Test @@ -324,6 +329,68 @@ class RequestResourcesTest { + "&Entries.member.4.EventBusName=late"))); } + /** + * An EventBridge V2 request, checked as the same {@code events} actions, names its bus or subscriber by ARN and + * never the default bus, and a create makes an {@code event-busv2}, whose id V2 mints. EventBridge's own requests + * still name their bus by Name. + */ + @Test + void anEventBridgeV2RequestIsOnTheBusOrSubscriberItsArnNames() { + String events = "arn:aws:events:us-east-1:000000000000:"; + String bus = events + "event-busv2/orders/a1b2c3d4"; + String subscriber = events + "subscriber/audit/e5f6g7h8"; + assertEquals(List.of(bus), of("events:PutEvents", + v2("{\"EventBusArn\":\"" + bus + "\",\"Entries\":[{\"Source\":\"s\",\"DetailType\":\"d\"}]}"))); + assertEquals(List.of(bus), of("events:DescribeEventBus", v2("{\"EventBusArn\":\"" + bus + "\"}"))); + assertEquals(List.of(bus), of("events:DeleteEventBus", v2("{\"EventBusArn\":\"" + bus + "\"}"))); + assertEquals(List.of(subscriber), of("events:DescribeSubscriber", + v2("{\"SubscriberArn\":\"" + subscriber + "\"}"))); + assertEquals(List.of(subscriber), of("events:UpdateSubscriber", + v2("{\"SubscriberArn\":\"" + subscriber + "\",\"State\":\"STOPPED\"}"))); + assertEquals(List.of(subscriber), of("events:DeleteSubscriber", + v2("{\"SubscriberArn\":\"" + subscriber + "\"}"))); + // A subscriber is made on the bus it names, its target and role naming neither. + assertEquals(List.of(bus, events + "subscriber/audit/*"), of("events:CreateSubscriber", + v2("{\"Name\":\"audit\",\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":{" + + "\"TargetArn\":\"arn:aws:sqs:us-east-1:000000000000:q\"," + + "\"RoleArn\":\"arn:aws:iam::000000000000:role/r\"}}"))); + assertEquals(List.of(events + "subscriber/audit/*"), created("events:CreateSubscriber", + v2("{\"Name\":\"audit\",\"EventBusArn\":\"" + bus + "\"}"))); + assertEquals(List.of(events + "event-busv2/orders/*"), of("events:CreateEventBus", + v2("{\"Name\":\"orders\"}"))); + assertEquals(List.of(), created("events:CreateEventBus", v2("{\"Name\":\"orders\"}"))); + + assertEquals(List.of(events + "event-bus/orders"), of("events:CreateEventBus", v1("{\"Name\":\"orders\"}"))); + assertEquals(List.of(events + "event-bus/orders"), created("events:CreateEventBus", + v1("{\"Name\":\"orders\",\"DeadLetterConfig\":{\"Arn\":\"" + events + "event-bus/other\"}}"))); + assertEquals(List.of(events + "event-bus/orders"), of("events:DeleteEventBus", v1("{\"Name\":\"orders\"}"))); + assertEquals(List.of(events + "event-bus/orders"), of("events:UpdateEventBus", + v1("{\"Name\":\"orders\",\"Description\":\"d\"}"))); + assertEquals(List.of("arn:aws:events:us-east-1::event-source/aws.partner/acme/orders"), + of("events:DescribeEventSource", v1("{\"Name\":\"aws.partner/acme/orders\"}"))); + } + + /** + * Which API's resources a request is checked on is the API serving it, never a member it gives: an EventBridge + * request naming a V2 bus's ARN beside its own bus, or giving V2's ClientToken, is checked on the bus its handler + * acts on, and a request no service is known to serve is checked on both. + */ + @Test + void aMemberOfTheOtherApiDoesNotChooseTheResourceChecked() { + String events = "arn:aws:events:us-east-1:000000000000:"; + String v2Bus = events + "event-busv2/open/a1b2c3d4"; + String withV2Arn = "{\"Name\":\"locked\",\"EventBusArn\":\"" + v2Bus + "\"}"; + for (String operation : List.of("events:DeleteEventBus", "events:DescribeEventBus", "events:UpdateEventBus")) { + assertEquals(List.of(events + "event-bus/locked"), of(operation, v1(withV2Arn)), operation); + assertEquals(List.of(v2Bus, events + "event-bus/locked"), of(operation, json(withV2Arn)), operation); + } + assertEquals(List.of(events + "event-bus/locked"), of("events:PutEvents", v1("{\"EventBusArn\":\"" + v2Bus + + "\",\"Entries\":[{\"EventBusName\":\"locked\",\"Source\":\"s\"}]}"))); + assertEquals(List.of(events + "event-bus/locked"), of("events:CreateEventBus", + v1("{\"Name\":\"locked\",\"ClientToken\":\"t\"}"))); + assertEquals(List.of(v2Bus), of("events:DeleteEventBus", v2(withV2Arn))); + } + /** * A connection or an API destination, whose ARN EventBridge follows with an id it mints after the name, is the * one stored under the name the request gives, and has that id open when none is or nothing looks it up. @@ -501,8 +568,26 @@ class RequestResourcesTest { return request("application/x-www-form-urlencoded", body); } + /** The JSON body as EventBridge's JSON 1.1 handler serves it. */ + private static ContainerRequestContext v1(String body) { + return RequestResourceMembersTest.servedBy(json(body), "events"); + } + + /** The JSON body as EventBridge V2's SDKs send it, in CBOR to the RPC v2 handler that serves it. */ + private static ContainerRequestContext v2(String body) { + try { + return RequestResourceMembersTest.servedBy(request("application/cbor", + CBOR.writeValueAsBytes(new ObjectMapper().readTree(body))), "eventsv2"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + private static ContainerRequestContext request(String mediaType, String body) { - byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + return request(mediaType, body.getBytes(StandardCharsets.UTF_8)); + } + + private static ContainerRequestContext request(String mediaType, byte[] bytes) { ContainerRequestContext request = mock(ContainerRequestContext.class); when(request.getMethod()).thenReturn("POST"); when(request.getMediaType()).thenReturn(MediaType.valueOf(mediaType)); diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2IntegrationTest.java new file mode 100644 index 0000000000..6507462f5a --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2IntegrationTest.java @@ -0,0 +1,214 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; +import com.fasterxml.jackson.dataformat.cbor.CBORParser; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; +import software.amazon.awssdk.services.eventbridgev2.model.BusState; +import software.amazon.awssdk.services.eventbridgev2.model.CreateEventBusResponse; +import software.amazon.awssdk.services.eventbridgev2.model.DescribeEventBusResponse; +import software.amazon.awssdk.services.eventbridgev2.model.EventBridgeV2Exception; +import software.amazon.awssdk.services.eventbridgev2.model.EventBusSummary; +import software.amazon.awssdk.services.eventbridgev2.model.IdempotentParameterMismatchException; +import software.amazon.awssdk.services.eventbridgev2.model.InvalidInputException; +import software.amazon.awssdk.services.eventbridgev2.model.ListEventBusesResponse; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceAlreadyExistsException; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceNotFoundException; + +import java.net.URI; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class EventBridgeV2IntegrationTest { + + private static final ObjectMapper CBOR_MAPPER = new ObjectMapper(new CBORFactory()); + + @Test + void sdkCreatesAnEventBusAndReadsItsResponse() { + String name = "orders-" + suffix(); + Instant before = Instant.now().minusSeconds(1); + try (EventBridgeV2Client client = client()) { + CreateEventBusResponse response = client.createEventBus(request -> request.name(name) + .description("Order events") + .storageConfiguration(storage -> storage.retentionPeriodInDays(30)) + .encryptionConfiguration(encryption -> encryption.kmsKeyIdentifier("alias/orders")) + .tags(Map.of("team", "orders"))); + + assertTrue(response.eventBusArn().matches( + "arn:aws:events:us-east-1:000000000000:event-busv2/" + name + "/[a-z0-9]{25}"), response.eventBusArn()); + assertEquals(name, response.name()); + assertEquals("Order events", response.description()); + assertEquals(30, response.storageConfiguration().retentionPeriodInDays()); + assertEquals("alias/orders", response.encryptionConfiguration().kmsKeyIdentifier()); + assertEquals(BusState.ACTIVE, response.state()); + // The SDK decodes CreationTime only from a CBOR timestamp. + assertTrue(!response.creationTime().isBefore(before) + && response.creationTime().isBefore(Instant.now().plus(Duration.ofSeconds(1))), + response.creationTime().toString()); + } + } + + @Test + void sdkRetryWithTheSameClientTokenReturnsTheSameBus() { + String name = "retry-" + suffix(); + try (EventBridgeV2Client client = client()) { + String arn = client.createEventBus(request -> request.name(name).clientToken("token-" + name)).eventBusArn(); + assertEquals(arn, client.createEventBus(request -> request.name(name).clientToken("token-" + name)) + .eventBusArn()); + IdempotentParameterMismatchException mismatch = assertThrows(IdempotentParameterMismatchException.class, + () -> client.createEventBus(request -> request.name(name).clientToken("token-" + name) + .description("changed"))); + assertEquals(409, mismatch.statusCode()); + } + } + + @Test + void sdkCreatingAnExistingBusFailsWithResourceAlreadyExists() { + String name = "dup-" + suffix(); + try (EventBridgeV2Client client = client()) { + client.createEventBus(request -> request.name(name)); + ResourceAlreadyExistsException e = assertThrows(ResourceAlreadyExistsException.class, + () -> client.createEventBus(request -> request.name(name))); + assertEquals(409, e.statusCode()); + } + } + + @Test + void sdkInvalidNameFailsWithInvalidInput() { + try (EventBridgeV2Client client = client()) { + InvalidInputException e = assertThrows(InvalidInputException.class, + () -> client.createEventBus(request -> request.name("not valid"))); + assertEquals(400, e.statusCode()); + } + } + + @Test + void sdkDescribesTheBusItCreated() { + String name = "describe-" + suffix(); + try (EventBridgeV2Client client = client()) { + CreateEventBusResponse created = client.createEventBus(request -> request.name(name) + .description("Order events") + .storageConfiguration(storage -> storage.retentionPeriodInDays(30)) + .encryptionConfiguration(encryption -> encryption.kmsKeyIdentifier("alias/orders"))); + + DescribeEventBusResponse described = client.describeEventBus(request -> request + .eventBusArn(created.eventBusArn())); + assertEquals(created.eventBusArn(), described.eventBusArn()); + assertEquals(name, described.name()); + assertEquals("Order events", described.description()); + assertEquals(30, described.storageConfiguration().retentionPeriodInDays()); + assertEquals("alias/orders", described.encryptionConfiguration().kmsKeyIdentifier()); + assertEquals(BusState.ACTIVE, described.state()); + // The SDK decodes these only from CBOR timestamps. + assertEquals(created.creationTime(), described.creationTime()); + assertNotNull(described.lastModifiedTime()); + + String unknown = created.eventBusArn().substring(0, created.eventBusArn().lastIndexOf('/') + 1) + + "zzzzzzzzzzzzzzzzzzzzzzzzz"; + ResourceNotFoundException missing = assertThrows(ResourceNotFoundException.class, + () -> client.describeEventBus(request -> request.eventBusArn(unknown))); + assertEquals(404, missing.statusCode()); + } + } + + @Test + void sdkListsTheBusesItCreatedPageByPage() { + String prefix = "list-" + suffix() + "-"; + try (EventBridgeV2Client client = client()) { + for (String name : List.of("c", "a", "b")) { + client.createEventBus(request -> request.name(prefix + name).description("bus " + name)); + } + + ListEventBusesResponse first = client.listEventBuses(request -> request.namePrefix(prefix).maxResults(2)); + assertEquals(List.of(prefix + "a", prefix + "b"), + first.eventBuses().stream().map(EventBusSummary::name).toList()); + EventBusSummary a = first.eventBuses().getFirst(); + assertTrue(a.eventBusArn().startsWith("arn:aws:events:us-east-1:000000000000:event-busv2/" + prefix + "a/"), + a.eventBusArn()); + assertEquals("bus a", a.description()); + assertEquals(BusState.ACTIVE, a.state()); + assertEquals("000000000000", a.eventBusAccountId()); + // The SDK decodes these only from CBOR timestamps. + assertNotNull(a.creationTime()); + assertEquals(a.creationTime(), a.lastModifiedTime()); + + List all = client.listEventBusesPaginator(request -> request.namePrefix(prefix).maxResults(1)) + .eventBuses().stream().map(EventBusSummary::name).toList(); + assertEquals(List.of(prefix + "a", prefix + "b", prefix + "c"), all); + } + } + + @Test + void sdkUnsupportedOperationFailsAsSuch() { + try (EventBridgeV2Client client = client()) { + EventBridgeV2Exception e = assertThrows(EventBridgeV2Exception.class, () -> client.listTagsForResource( + request -> request.resourceArn("arn:aws:events:us-east-1:000000000000:subscriber/x/" + + "abcdefghijklmnopqrstuvwxy"))); + assertEquals("UnsupportedOperation", e.awsErrorDetails().errorCode()); + } + } + + /** A bus with no optional configuration answers without those members, and with its time as a CBOR tag 1. */ + @Test + void createEventBusAnswersInSmithyRpcV2Cbor() throws Exception { + String name = "wire-" + suffix(); + byte[] body = given().header("smithy-protocol", "rpc-v2-cbor").contentType("application/cbor") + .accept("application/cbor").body(CBOR_MAPPER.writeValueAsBytes(Map.of("Name", name))) + .post("/service/AWSEventsV2/operation/CreateEventBus") + .then().statusCode(200).header("smithy-protocol", "rpc-v2-cbor").extract().asByteArray(); + JsonNode response = CBOR_MAPPER.readTree(body); + assertEquals(name, response.path("Name").asText()); + assertEquals("ACTIVE", response.path("State").asText()); + assertNull(response.get("Description")); + assertNull(response.get("StorageConfiguration")); + assertEquals(1, tagOf(body, "CreationTime"), "CreationTime is not a CBOR timestamp (tag 1)"); + } + + /** The CBOR tag of a top-level member's value; -1 for none. */ + private static int tagOf(byte[] body, String member) throws Exception { + try (CBORParser parser = (CBORParser) CBOR_MAPPER.getFactory().createParser(body)) { + parser.nextToken(); + while (parser.nextToken() == JsonToken.FIELD_NAME) { + String field = parser.currentName(); + parser.nextToken(); + if (member.equals(field)) { + return parser.getCurrentTag(); + } + parser.skipChildren(); + } + } + return -1; + } + + private static EventBridgeV2Client client() { + return EventBridgeV2Client.builder() + .endpointOverride(URI.create("http://localhost:" + RestAssured.port)) + .httpClientBuilder(UrlConnectionHttpClient.builder()) + .region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) + .build(); + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2ServiceTest.java new file mode 100644 index 0000000000..09cfa31131 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2ServiceTest.java @@ -0,0 +1,650 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.PaginatedResult; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.services.eventbridgev2.model.EventBusV2; +import io.github.hectorvent.floci.services.eventbridgev2.model.SubscriberV2; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.ArgumentCaptor; + +import java.math.BigDecimal; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.stream.LongStream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +class EventBridgeV2ServiceTest { + private static final String REGION = "us-east-1"; + private static final String ACCOUNT = "000000000000"; + private static final Instant NOW = Instant.parse("2026-10-28T12:00:00.123Z"); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String QUEUE = "arn:aws:sqs:us-east-1:000000000000:orders"; + private static final String ROLE = "arn:aws:iam::000000000000:role/EventBusDelivery"; + + private EventBridgeV2Service service; + private EventBridgeV2Delivery delivery; + + @BeforeEach + void setUp() { + delivery = mock(EventBridgeV2Delivery.class); + service = new EventBridgeV2Service(AccountAwareStorageBackend.inMemory(ACCOUNT), + AccountAwareStorageBackend.inMemory(ACCOUNT), new RegionResolver(REGION, ACCOUNT), delivery, + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + @Test + void createEventBusMintsAnActiveBusUnderAnEventBusV2Arn() { + EventBusV2 bus = service.createEventBus(json("{\"Name\":\"orders\",\"Description\":\"Order events\"," + + "\"EncryptionConfiguration\":{\"KmsKeyIdentifier\":\"alias/orders\"}," + + "\"StorageConfiguration\":{\"RetentionPeriodInDays\":90},\"Tags\":{\"team\":\"orders\"}}"), REGION); + + assertTrue(bus.getArn().matches("arn:aws:events:us-east-1:000000000000:event-busv2/orders/[a-z0-9]{25}"), + bus.getArn()); + assertEquals("orders", bus.getName()); + assertEquals("Order events", bus.getDescription()); + assertEquals("alias/orders", bus.getKmsKeyIdentifier()); + assertEquals(90, bus.getRetentionPeriodInDays()); + assertEquals(EventBridgeV2Service.ACTIVE, bus.getState()); + assertEquals(NOW, bus.getCreationTime()); + assertEquals(NOW, bus.getLastModifiedTime()); + assertEquals(Map.of("team", "orders"), bus.getTags()); + } + + @Test + void createEventBusLeavesOptionalConfigurationUnset() { + EventBusV2 bus = service.createEventBus(json("{\"Name\":\"minimal\"}"), REGION); + assertNull(bus.getDescription()); + assertNull(bus.getKmsKeyIdentifier()); + assertNull(bus.getRetentionPeriodInDays()); + assertEquals(Map.of(), bus.getTags()); + } + + @Test + void createEventBus_existingName_resourceAlreadyExists() { + service.createEventBus(json("{\"Name\":\"orders\"}"), REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createEventBus(json("{\"Name\":\"orders\"}"), REGION)); + assertEquals("ResourceAlreadyExistsException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + // A bus name is unique per Region. + service.createEventBus(json("{\"Name\":\"orders\"}"), "eu-west-1"); + } + + @Test + void createEventBus_retryWithItsClientToken_returnsTheSameBus() { + String request = "{\"Name\":\"orders\",\"ClientToken\":\"token-1\",\"Description\":\"d\"}"; + EventBusV2 created = service.createEventBus(json(request), REGION); + EventBusV2 retried = service.createEventBus(json(request), REGION); + assertEquals(created.getArn(), retried.getArn()); + } + + @Test + void createEventBus_clientTokenWithAnotherRequest_idempotentParameterMismatch() { + service.createEventBus(json("{\"Name\":\"orders\",\"ClientToken\":\"token-1\"}"), REGION); + AwsException e = assertThrows(AwsException.class, () -> service.createEventBus( + json("{\"Name\":\"orders\",\"ClientToken\":\"token-1\",\"Description\":\"changed\"}"), REGION)); + assertEquals("IdempotentParameterMismatchException", e.getErrorCode()); + assertEquals(409, e.getHttpStatus()); + } + + @Test + void createEventBus_retryWithItsFieldsAndTagsReordered_returnsTheSameBus() { + EventBusV2 created = service.createEventBus(json("{\"Name\":\"orders\",\"ClientToken\":\"token-1\"," + + "\"Description\":\"d\",\"Tags\":{\"team\":\"orders\",\"env\":\"dev\"}," + + "\"StorageConfiguration\":{\"RetentionPeriodInDays\":7}}"), REGION); + EventBusV2 retried = service.createEventBus(json("{\"StorageConfiguration\":{\"RetentionPeriodInDays\":7}," + + "\"Tags\":{\"env\":\"dev\",\"team\":\"orders\"},\"Description\":\"d\",\"ClientToken\":\"token-1\"," + + "\"Name\":\"orders\"}"), REGION); + assertEquals(created.getArn(), retried.getArn()); + } + + @Test + void createSubscriber_retryWithItsFieldsReordered_returnsTheSameSubscriber() { + String bus = bus("orders"); + SubscriberV2 created = service.createSubscriber(json("{\"Name\":\"s\",\"ClientToken\":\"token-1\"," + + "\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":{\"TargetArn\":\"" + QUEUE + "\"," + + "\"RoleArn\":\"" + ROLE + "\"},\"Tags\":{\"a\":\"1\",\"b\":\"2\"}}"), REGION); + SubscriberV2 retried = service.createSubscriber(json("{\"Tags\":{\"b\":\"2\",\"a\":\"1\"}," + + "\"InvokeConfiguration\":{\"RoleArn\":\"" + ROLE + "\",\"TargetArn\":\"" + QUEUE + "\"}," + + "\"EventBusArn\":\"" + bus + "\",\"ClientToken\":\"token-1\",\"Name\":\"s\"}"), REGION); + assertEquals(created.getArn(), retried.getArn()); + } + + @Test + void createEventBus_anotherClientToken_resourceAlreadyExists() { + service.createEventBus(json("{\"Name\":\"orders\",\"ClientToken\":\"token-1\"}"), REGION); + AwsException e = assertThrows(AwsException.class, () -> service.createEventBus( + json("{\"Name\":\"orders\",\"ClientToken\":\"token-2\"}"), REGION)); + assertEquals("ResourceAlreadyExistsException", e.getErrorCode()); + } + + @Test + void eachBusGetsItsOwnId() { + String first = service.createEventBus(json("{\"Name\":\"a\"}"), REGION).getArn(); + String second = service.createEventBus(json("{\"Name\":\"b\"}"), REGION).getArn(); + assertNotEquals(first.substring(first.lastIndexOf('/')), second.substring(second.lastIndexOf('/'))); + } + + @ParameterizedTest + @ValueSource(strings = { + "{}", + "{\"Name\":\"\"}", + "{\"Name\":\"-starts-with-dash\"}", + "{\"Name\":\"has space\"}", + "{\"Name\":7}", + "{\"Name\":\"ok\",\"Description\":\"line\\nbreak\"}", + "{\"Name\":\"ok\",\"StorageConfiguration\":{\"RetentionPeriodInDays\":0}}", + "{\"Name\":\"ok\",\"StorageConfiguration\":{\"RetentionPeriodInDays\":366}}", + "{\"Name\":\"ok\",\"StorageConfiguration\":[]}", + "{\"Name\":\"ok\",\"EncryptionConfiguration\":{\"KmsKeyIdentifier\":\"not a key\"}}", + "{\"Name\":\"ok\",\"ClientToken\":\"\"}", + "{\"Name\":\"ok\",\"Tags\":{\" padded\":\"v\"}}", + "{\"Name\":\"ok\",\"Tags\":{\"k\":7}}", + "{\"Name\":\"ok\",\"Tags\":[]}" + }) + void createEventBus_invalidRequest_invalidInput(String request) { + AwsException e = assertThrows(AwsException.class, () -> service.createEventBus(json(request), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + } + + @Test + void createEventBusAcceptsTheLongestNameAndDescription() { + String name = "n" + "a".repeat(255); + EventBusV2 bus = service.createEventBus(json("{\"Name\":\"" + name + "\",\"Description\":\"" + + "d".repeat(512) + "\"}"), REGION); + assertEquals(name, bus.getName()); + assertThrows(AwsException.class, () -> service.createEventBus(json("{\"Name\":\"" + name + "b\"}"), REGION)); + } + + @Test + void clearRemovesEveryBus() { + service.createEventBus(json("{\"Name\":\"orders\"}"), REGION); + service.clear(); + service.createEventBus(json("{\"Name\":\"orders\"}"), REGION); + } + + @Test + void describeEventBusFindsABusByItsArnAlone() { + String arn = bus("orders"); + assertEquals("orders", service.describeEventBus(json("{\"EventBusArn\":\"" + arn + "\"}"), REGION).getName()); + + String sameNameOtherId = arn.substring(0, arn.lastIndexOf('/') + 1) + "zzzzzzzzzzzzzzzzzzzzzzzzz"; + AwsException missing = assertThrows(AwsException.class, + () -> service.describeEventBus(json("{\"EventBusArn\":\"" + sameNameOtherId + "\"}"), REGION)); + assertEquals("ResourceNotFoundException", missing.getErrorCode()); + AwsException otherRegion = assertThrows(AwsException.class, + () -> service.describeEventBus(json("{\"EventBusArn\":\"" + arn + "\"}"), "eu-west-1")); + assertEquals("ResourceNotFoundException", otherRegion.getErrorCode()); + AwsException absent = assertThrows(AwsException.class, () -> service.describeEventBus(json("{}"), REGION)); + assertEquals("InvalidInputException", absent.getErrorCode()); + } + + @Test + void listEventBusesPagesTheRegionsBusesInNameOrder() { + for (String name : List.of("orders-b", "billing", "orders-a", "orders-c")) { + bus(name); + } + service.createEventBus(json("{\"Name\":\"orders-elsewhere\"}"), "eu-west-1"); + + PaginatedResult first = service.listEventBuses(json("{\"NamePrefix\":\"orders\",\"MaxResults\":2}"), + REGION); + assertEquals(List.of("orders-a", "orders-b"), first.items().stream().map(EventBusV2::getName).toList()); + assertNotNull(first.nextToken()); + + PaginatedResult second = service.listEventBuses(json("{\"NamePrefix\":\"orders\",\"MaxResults\":2," + + "\"NextToken\":\"" + first.nextToken() + "\"}"), REGION); + assertEquals(List.of("orders-c"), second.items().stream().map(EventBusV2::getName).toList()); + assertNull(second.nextToken()); + + assertEquals(4, service.listEventBuses(json("{}"), REGION).items().size()); + } + + @Test + void listEventBusesForAnotherAccountListsNone() { + bus("orders"); + assertEquals(1, service.listEventBuses(json("{\"EventBusAccountId\":\"" + ACCOUNT + "\"}"), REGION) + .items().size()); + assertEquals(List.of(), service.listEventBuses(json("{\"EventBusAccountId\":\"111122223333\"}"), REGION) + .items()); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"MaxResults\":0}", "{\"MaxResults\":101}", "{\"NamePrefix\":\"-orders\"}", + "{\"EventBusAccountId\":\"123\"}", "{\"NextToken\":\"not-a-token\"}"}) + void listEventBuses_invalidRequest_invalidInput(String request) { + AwsException e = assertThrows(AwsException.class, () -> service.listEventBuses(json(request), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals(400, e.getHttpStatus()); + } + + // ──────────────────────────── Subscribers ──────────────────────────── + + @Test + void createSubscriberOnABusStoresItsConfigurationWithDefaults() { + String bus = bus("orders"); + SubscriberV2 subscriber = service.createSubscriber(json(subscriberRequest("large-orders", bus, + ",\"FilterConfiguration\":{\"Filters\":[{\"Scope\":\"DATA\",\"Pattern\":" + + "\"{\\\"source\\\":[\\\"shop\\\"]}\"}]}")), REGION); + + assertTrue(subscriber.getArn().matches( + "arn:aws:events:us-east-1:000000000000:subscriber/large-orders/[a-z0-9]{25}"), subscriber.getArn()); + assertEquals(bus, subscriber.getEventBusArn()); + assertEquals("RUNNING", subscriber.getState()); + assertEquals("UNORDERED", subscriber.getType()); + assertEquals("LATEST", subscriber.getStartingPosition()); + assertEquals(QUEUE, subscriber.getInvokeConfiguration().path("TargetArn").asText()); + assertEquals(NOW, subscriber.getCreationTime()); + } + + @Test + void createSubscriber_unknownBus_resourceNotFound() { + AwsException e = assertThrows(AwsException.class, () -> service.createSubscriber(json(subscriberRequest("s", + "arn:aws:events:us-east-1:000000000000:event-busv2/none/abcdefghijklmnopqrstuvwxy", "")), REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + assertEquals(404, e.getHttpStatus()); + } + + @Test + void createSubscriber_existingNameOnTheBus_resourceAlreadyExists() { + String bus = bus("orders"); + service.createSubscriber(json(subscriberRequest("s", bus, "")), REGION); + AwsException e = assertThrows(AwsException.class, + () -> service.createSubscriber(json(subscriberRequest("s", bus, "")), REGION)); + assertEquals("ResourceAlreadyExistsException", e.getErrorCode()); + } + + @ParameterizedTest + @ValueSource(strings = { + "{\"TargetArn\":\"arn:aws:lambda:us-east-1:000000000000:function:f\",\"RoleArn\":\"ROLE\"}", + "{\"TargetArn\":\"arn:aws:sqs:us-east-1:111111111111:other\",\"RoleArn\":\"ROLE\"}", + "{\"TargetArn\":\"QUEUE\",\"RoleArn\":\"ROLE\",\"LambdaParameters\":{}}", + "{\"TargetArn\":\"QUEUE\",\"RoleArn\":\"not-a-role\"}", + "{\"TargetArn\":\"QUEUE\"}", + "{\"TargetArn\":\"QUEUE\",\"RoleArn\":\"ROLE\",\"SqsParameters\":{\"MessageGroupId\":\"{% $uuid() %}\"}}" + }) + void createSubscriber_unsupportedInvokeConfiguration_invalidInput(String invoke) { + String bus = bus("orders"); + String request = "{\"Name\":\"s\",\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":" + + invoke.replace("QUEUE", QUEUE).replace("ROLE", ROLE) + "}"; + AwsException e = assertThrows(AwsException.class, () -> service.createSubscriber(json(request), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + } + + @ParameterizedTest + @ValueSource(strings = {"{\"{% $uppercase($events.Data.source) %}\":{\"DataType\":\"String\",\"StringValue\":\"x\"}}", + "{\"origin\":{\"DataType\":\"String\",\"StringValue\":\"{% $uppercase($events.Data.source) %}\"}}"}) + void createSubscriber_messageAttributeJsonata_invalidInput(String attributes) { + String bus = bus("orders"); + String request = "{\"Name\":\"s\",\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":{\"TargetArn\":\"" + + QUEUE + "\",\"RoleArn\":\"" + ROLE + "\",\"SqsParameters\":{\"MessageAttributes\":" + attributes + "}}}"; + AwsException e = assertThrows(AwsException.class, () -> service.createSubscriber(json(request), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + assertTrue(e.getMessage().startsWith("SqsParameters.MessageAttributes"), e.getMessage()); + } + + @Test + void createSubscriber_jsonataTransformer_invalidInput() { + String bus = bus("orders"); + AwsException e = assertThrows(AwsException.class, () -> service.createSubscriber(json(subscriberRequest("s", + bus, ",\"Transformer\":{\"Type\":\"JSONATA\",\"JsonataConfiguration\":{\"Expression\":\"{% 1 %}\"}}")), + REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + } + + @Test + void deleteEventBus_withASubscriber_resourceInUse() { + String bus = bus("orders"); + SubscriberV2 subscriber = service.createSubscriber(json(subscriberRequest("s", bus, "")), REGION); + AwsException e = assertThrows(AwsException.class, () -> service.deleteEventBus(bus, REGION)); + assertEquals("ResourceInUseException", e.getErrorCode()); + service.deleteSubscriber(subscriber.getArn(), REGION); + service.deleteEventBus(bus, REGION); + assertTrue(service.findEventBus(bus, REGION).isEmpty()); + } + + @Test + void deleteSubscriber_unknown_resourceNotFound() { + AwsException e = assertThrows(AwsException.class, () -> service.deleteSubscriber( + "arn:aws:events:us-east-1:000000000000:subscriber/s/abcdefghijklmnopqrstuvwxy", REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void deleteWithoutAnArn_invalidInput() { + AwsException bus = assertThrows(AwsException.class, () -> service.deleteEventBus(json("{}"), REGION)); + assertEquals("InvalidInputException", bus.getErrorCode()); + AwsException subscriber = assertThrows(AwsException.class, () -> service.deleteSubscriber(json("{}"), REGION)); + assertEquals("InvalidInputException", subscriber.getErrorCode()); + } + + @Test + void createSubscriberStoresAPointInTimeAsEpochSeconds() { + SubscriberV2 subscriber = service.createSubscriber(json(subscriberRequest("s", bus("orders"), + ",\"StartingPosition\":\"POINT_IN_TIME\",\"PointInTimeConfiguration\":{\"PointType\":\"TIMESTAMP\"," + + "\"StartingPoint\":1767225600.25,\"EndPoint\":1767312000}")), REGION); + + JsonNode pointInTime = subscriber.getPointInTimeConfiguration(); + assertTrue(pointInTime.path("StartingPoint").isNumber()); + assertEquals(0, new BigDecimal("1767225600.25").compareTo(pointInTime.path("StartingPoint").decimalValue())); + assertEquals(0, new BigDecimal("1767312000").compareTo(pointInTime.path("EndPoint").decimalValue())); + assertEquals("TIMESTAMP", pointInTime.path("PointType").asText()); + } + + @Test + void createSubscriber_pointInTimeThatIsNotATimestamp_invalidInput() { + String bus = bus("orders"); + AwsException e = assertThrows(AwsException.class, () -> service.createSubscriber(json(subscriberRequest("s", + bus, ",\"StartingPosition\":\"POINT_IN_TIME\",\"PointInTimeConfiguration\":{\"PointType\":" + + "\"TIMESTAMP\",\"StartingPoint\":\"2026-01-01T00:00:00Z\"}")), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + } + + @Test + void updateSubscriberStoresANewSubscriberAndLeavesTheOneAReaderHeldUnchanged() { + SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus("orders"), + ",\"Description\":\"d\"")), REGION); + SubscriberV2 held = service.findSubscriber(created.getArn(), REGION).orElseThrow(); + + service.updateSubscriber(json("{\"SubscriberArn\":\"" + created.getArn() + "\",\"State\":\"STOPPED\"," + + "\"Description\":\"changed\"}"), REGION); + + assertEquals("d", held.getDescription()); + assertEquals(EventBridgeV2Service.RUNNING, held.getState()); + SubscriberV2 stored = service.findSubscriber(created.getArn(), REGION).orElseThrow(); + assertEquals("changed", stored.getDescription()); + assertEquals("STOPPED", stored.getState()); + assertEquals(created.getCreationTime(), stored.getCreationTime()); + } + + @Test + void replaceSubscriberSettingsClearsWhatTheRequestLeavesOut() { + String bus = bus("orders"); + SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus, + ",\"Description\":\"d\",\"FilterConfiguration\":{\"Filters\":[{\"Scope\":\"DATA\"," + + "\"Pattern\":\"{\\\"source\\\":[\\\"a\\\"]}\"}]}")), REGION); + SubscriberV2 updated = service.replaceSubscriberSettings(created.getArn(), + json(subscriberRequest("s", bus, ",\"State\":\"STOPPED\"")), REGION); + assertNull(updated.getDescription()); + assertNull(updated.getFilterConfiguration()); + assertEquals("STOPPED", updated.getState()); + assertEquals(created.getArn(), updated.getArn()); + } + + @Test + void replaceSubscriberSettings_invalidSetting_leavesTheSubscriberAsItWas() { + String bus = bus("orders"); + SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus, ",\"Description\":\"d\"")), + REGION); + + AwsException e = assertThrows(AwsException.class, () -> service.replaceSubscriberSettings(created.getArn(), + json(subscriberRequest("s", bus, ",\"Description\":\"changed\",\"State\":\"STOPPED\"," + + "\"RetryPolicy\":{\"MaxRetryAttempts\":999}")), REGION)); + + assertEquals("InvalidInputException", e.getErrorCode()); + SubscriberV2 unchanged = service.findSubscriber(created.getArn(), REGION).orElseThrow(); + assertEquals("d", unchanged.getDescription()); + assertEquals(EventBridgeV2Service.RUNNING, unchanged.getState()); + assertNull(unchanged.getRetryPolicy()); + } + + @Test + void replaceEventBusSettings_invalidSetting_leavesTheBusAsItWas() { + String arn = service.createEventBus(json("{\"Name\":\"orders\",\"Description\":\"d\"}"), REGION).getArn(); + + AwsException e = assertThrows(AwsException.class, () -> service.replaceEventBusSettings(arn, + json("{\"Name\":\"orders\",\"Description\":\"changed\",\"StorageConfiguration\":" + + "{\"RetentionPeriodInDays\":999}}"), REGION)); + + assertEquals("InvalidInputException", e.getErrorCode()); + assertEquals("d", service.findEventBus(arn, REGION).orElseThrow().getDescription()); + } + + @Test + void updateSubscriberChangesWhatTheRequestGivesAndKeepsTheRest() { + String bus = bus("orders"); + SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus, + ",\"Description\":\"d\",\"Tags\":{\"team\":\"orders\"},\"FilterConfiguration\":{\"Filters\":[{" + + "\"Scope\":\"DATA\",\"Pattern\":\"{\\\"source\\\":[\\\"a\\\"]}\"}]}")), REGION); + Instant createdAt = created.getCreationTime(); + + SubscriberV2 updated = service.updateSubscriber(json("{\"SubscriberArn\":\"" + created.getArn() + + "\",\"State\":\"STOPPED\",\"ResumePosition\":\"LATEST\",\"InvokeConfiguration\":{\"RoleArn\":" + + "\"arn:aws:iam::000000000000:role/Other\",\"SqsParameters\":{\"MessageGroupId\":\"g\"}}}"), REGION); + + assertEquals("STOPPED", updated.getState()); + assertEquals("d", updated.getDescription()); + assertEquals("{\"source\":[\"a\"]}", updated.getFilterConfiguration().path("Filters").path(0).path("Pattern") + .asText()); + assertEquals(Map.of("team", "orders"), updated.getTags()); + assertEquals(QUEUE, updated.getInvokeConfiguration().path("TargetArn").asText(), "the target is kept"); + assertEquals("arn:aws:iam::000000000000:role/Other", updated.getInvokeConfiguration().path("RoleArn").asText()); + assertEquals("g", updated.getInvokeConfiguration().path("SqsParameters").path("MessageGroupId").asText()); + assertEquals(createdAt, updated.getCreationTime()); + } + + @Test + void updateSubscriber_invalidSetting_leavesTheSubscriberAsItWas() { + String bus = bus("orders"); + SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus, ",\"Description\":\"d\"")), + REGION); + + AwsException e = assertThrows(AwsException.class, () -> service.updateSubscriber(json("{\"SubscriberArn\":\"" + + created.getArn() + "\",\"Description\":\"changed\",\"RetryPolicy\":{\"MaxRetryAttempts\":999}}"), + REGION)); + + assertEquals("InvalidInputException", e.getErrorCode()); + SubscriberV2 unchanged = service.findSubscriber(created.getArn(), REGION).orElseThrow(); + assertEquals("d", unchanged.getDescription()); + assertNull(unchanged.getRetryPolicy()); + } + + @ParameterizedTest + @ValueSource(strings = {"\"ResumePosition\":\"FIRST\"", "\"State\":\"PAUSED\"", + "\"InvokeConfiguration\":{\"RoleArn\":\"arn:aws:iam::000000000000:role/r\",\"TargetArn\":\"" + QUEUE + "\"}", + "\"FilterConfiguration\":{\"Filters\":[{\"Scope\":\"DATA\",\"Pattern\":\"{\\\"a\\\":[{\\\"wildcard\\\":\\\"*\\\"}]}\"}]}"}) + void updateSubscriber_invalidRequest_invalidInput(String member) { + SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus("orders"), "")), REGION); + AwsException e = assertThrows(AwsException.class, () -> service.updateSubscriber(json("{\"SubscriberArn\":\"" + + created.getArn() + "\"," + member + "}"), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + } + + @Test + void updateSubscriber_unknown_resourceNotFound() { + AwsException e = assertThrows(AwsException.class, () -> service.updateSubscriber(json("{\"SubscriberArn\":" + + "\"arn:aws:events:us-east-1:000000000000:subscriber/s/abcdefghijklmnopqrstuvwxy\"}"), REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + @Test + void describeSubscriberFindsASubscriberByItsArn() { + SubscriberV2 created = service.createSubscriber(json(subscriberRequest("s", bus("orders"), "")), REGION); + assertEquals("s", service.describeSubscriber(json("{\"SubscriberArn\":\"" + created.getArn() + "\"}"), REGION) + .getName()); + AwsException absent = assertThrows(AwsException.class, () -> service.describeSubscriber(json("{}"), REGION)); + assertEquals("InvalidInputException", absent.getErrorCode()); + } + + @Test + void listSubscribersPagesTheRegionsOrOneBussSubscribers() { + String orders = bus("orders"); + String billing = bus("billing"); + for (String name : List.of("orders-b", "orders-a", "audit")) { + service.createSubscriber(json(subscriberRequest(name, orders, "")), REGION); + } + service.createSubscriber(json(subscriberRequest("orders-c", billing, "")), REGION); + + PaginatedResult first = service.listSubscribers(json("{\"EventBusArn\":\"" + orders + + "\",\"NamePrefix\":\"orders\",\"MaxResults\":1}"), REGION); + assertEquals(List.of("orders-a"), first.items().stream().map(SubscriberV2::getName).toList()); + PaginatedResult second = service.listSubscribers(json("{\"EventBusArn\":\"" + orders + + "\",\"NamePrefix\":\"orders\",\"MaxResults\":1,\"NextToken\":\"" + first.nextToken() + "\"}"), REGION); + assertEquals(List.of("orders-b"), second.items().stream().map(SubscriberV2::getName).toList()); + assertNull(second.nextToken()); + + assertEquals(List.of("orders-c", "audit", "orders-a", "orders-b"), service.listSubscribers(json("{}"), REGION) + .items().stream().map(SubscriberV2::getName).toList(), "every bus's, by bus then name"); + + AwsException e = assertThrows(AwsException.class, () -> service.listSubscribers(json("{\"EventBusArn\":" + + "\"arn:aws:events:us-east-1:000000000000:event-busv2/none/abcdefghijklmnopqrstuvwxy\"}"), REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + // ──────────────────────────── PutEvents ──────────────────────────── + + @Test + void putEventsDeliversAMatchingEventInTheEventBridgeEnvelope() { + String bus = bus("orders"); + SubscriberV2 large = service.createSubscriber(json(subscriberRequest("large", bus, + ",\"FilterConfiguration\":{\"Filters\":[{\"Scope\":\"DATA\",\"Pattern\":" + + "\"{\\\"detail\\\":{\\\"total\\\":[{\\\"numeric\\\":[\\\">\\\",500]}]}}\"}," + + "{\"Scope\":\"SYSTEM_METADATA\",\"Pattern\":\"{\\\"aws:Source\\\":[\\\"shop\\\"]}\"}]}")), + REGION); + + List results = service.putEvents(json("{\"EventBusArn\":\"" + bus + + "\",\"Entries\":[{\"Source\":\"shop\",\"DetailType\":\"Order Placed\",\"Detail\":\"{\\\"total\\\":750}\"}," + + "{\"Source\":\"shop\",\"DetailType\":\"Order Placed\",\"Detail\":\"{\\\"total\\\":10}\"}," + + "{\"Source\":\"other\",\"DetailType\":\"Order Placed\",\"Detail\":\"{\\\"total\\\":900}\"}]}"), REGION); + + assertEquals(3, results.size()); + assertEquals(List.of("1", "2", "3"), results.stream().map(EventBridgeV2Service.PutEventsResult::sequenceNumber) + .toList()); + ArgumentCaptor delivered = ArgumentCaptor.forClass(SubscriberV2.class); + ArgumentCaptor event = ArgumentCaptor.forClass(PublishedEvent.class); + verify(delivery, times(1)).deliver(delivered.capture(), event.capture()); + assertEquals(large.getArn(), delivered.getValue().getArn()); + JsonNode data = event.getValue().data(); + assertEquals("0", data.path("version").asText()); + assertEquals(results.getFirst().eventId(), data.path("id").asText()); + assertEquals("Order Placed", data.path("detail-type").asText()); + assertEquals("shop", data.path("source").asText()); + assertEquals(ACCOUNT, data.path("account").asText()); + assertEquals(REGION, data.path("region").asText()); + assertEquals("2026-10-28T12:00:00Z", data.path("time").asText()); + assertEquals(750, data.path("detail").path("total").asInt()); + assertEquals("application/eventbridge+json", event.getValue().systemMetadata().path("ContentType").asText()); + assertEquals("1", event.getValue().systemMetadata().path("aws:SequenceNumber").asText()); + } + + @Test + void putEventsSkipsAStoppedSubscriberAndRefusesAMalformedDetailAlone() { + String bus = bus("orders"); + service.createSubscriber(json(subscriberRequest("s", bus, ",\"State\":\"STOPPED\"")), REGION); + + List results = service.putEvents(json("{\"EventBusArn\":\"" + bus + + "\",\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\",\"Detail\":\"not json\"}," + + "{\"Source\":\"a\",\"DetailType\":\"t\"}]}"), REGION); + + assertEquals("MalformedDetail", results.getFirst().errorCode()); + assertNull(results.get(1).errorCode()); + verify(delivery, never()).deliver(any(), any()); + } + + @Test + void putEvents_malformedTime_failsTheRequestWithoutUsingASequenceNumber() { + String bus = bus("orders"); + service.createSubscriber(json(subscriberRequest("s", bus, "")), REGION); + + AwsException e = assertThrows(AwsException.class, () -> service.putEvents(json("{\"EventBusArn\":\"" + bus + + "\",\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\"}," + + "{\"Source\":\"a\",\"DetailType\":\"t\",\"Time\":\"yesterday\"}]}"), REGION)); + assertEquals("InvalidInputException", e.getErrorCode()); + verify(delivery, never()).deliver(any(), any()); + + List results = service.putEvents(json("{\"EventBusArn\":\"" + bus + + "\",\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\"}]}"), REGION); + assertEquals("1", results.getFirst().sequenceNumber()); + } + + @Test + void concurrentPutEventsDeliverInSequenceOrder() throws Exception { + String bus = bus("orders"); + service.createSubscriber(json(subscriberRequest("fifo", bus, ",\"Type\":\"FIFO\"")), REGION); + List delivered = Collections.synchronizedList(new ArrayList<>()); + doAnswer(invocation -> { + PublishedEvent event = invocation.getArgument(1); + delivered.add(Long.parseLong(event.systemMetadata().path("aws:SequenceNumber").asText())); + Thread.yield(); + return null; + }).when(delivery).deliver(any(), any()); + + int threads = 8; + int requestsPerThread = 50; + ExecutorService executor = Executors.newFixedThreadPool(threads); + CountDownLatch start = new CountDownLatch(1); + List> requests = new ArrayList<>(); + for (int t = 0; t < threads; t++) { + requests.add(executor.submit(() -> { + start.await(); + for (int i = 0; i < requestsPerThread; i++) { + service.putEvents(json("{\"EventBusArn\":\"" + bus + "\",\"Entries\":[" + + "{\"Source\":\"a\",\"DetailType\":\"t\"},{\"Source\":\"a\",\"DetailType\":\"t\"}]}"), REGION); + } + return null; + })); + } + start.countDown(); + for (Future request : requests) { + request.get(30, TimeUnit.SECONDS); + } + executor.shutdown(); + + List expected = LongStream.rangeClosed(1, threads * requestsPerThread * 2L).boxed().toList(); + assertEquals(expected, delivered); + } + + @Test + void putEvents_unknownBus_resourceNotFound() { + AwsException e = assertThrows(AwsException.class, () -> service.putEvents(json("{\"EventBusArn\":" + + "\"arn:aws:events:us-east-1:000000000000:event-busv2/none/abcdefghijklmnopqrstuvwxy\"," + + "\"Entries\":[{\"Source\":\"a\",\"DetailType\":\"t\"}]}"), REGION)); + assertEquals("ResourceNotFoundException", e.getErrorCode()); + } + + private String bus(String name) { + return service.createEventBus(json("{\"Name\":\"" + name + "\"}"), REGION).getArn(); + } + + private static String subscriberRequest(String name, String bus, String extra) { + return "{\"Name\":\"" + name + "\",\"EventBusArn\":\"" + bus + "\",\"InvokeConfiguration\":{\"TargetArn\":\"" + + QUEUE + "\",\"RoleArn\":\"" + ROLE + "\"}" + extra + "}"; + } + + private static JsonNode json(String value) { + try { + return MAPPER.readTree(value); + } catch (Exception e) { + throw new AssertionError(e); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2SubscriberIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2SubscriberIntegrationTest.java new file mode 100644 index 0000000000..634019adf6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventBridgeV2SubscriberIntegrationTest.java @@ -0,0 +1,245 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.eventbridgev2.EventBridgeV2Client; +import software.amazon.awssdk.services.eventbridgev2.model.DescribeSubscriberResponse; +import software.amazon.awssdk.services.eventbridgev2.model.FilterScope; +import software.amazon.awssdk.services.eventbridgev2.model.InvalidInputException; +import software.amazon.awssdk.services.eventbridgev2.model.PutEventsResponse; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceInUseException; +import software.amazon.awssdk.services.eventbridgev2.model.ResourceNotFoundException; +import software.amazon.awssdk.services.eventbridgev2.model.SubscriberState; +import software.amazon.awssdk.services.eventbridgev2.model.SubscriberSummary; +import software.amazon.awssdk.services.eventbridgev2.model.TransformerType; +import software.amazon.awssdk.services.eventbridgev2.model.UpdateSubscriberResponse; +import software.amazon.awssdk.services.sqs.SqsClient; +import software.amazon.awssdk.services.sqs.model.Message; +import software.amazon.awssdk.services.sqs.model.QueueAttributeName; + +import java.net.URI; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** An EventBridge V2 subscriber delivers the events its filters match to an Amazon SQS queue, through the SDKs. */ +@QuarkusTest +class EventBridgeV2SubscriberIntegrationTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String ROLE = "arn:aws:iam::000000000000:role/EventBusDelivery"; + + @Test + void aSubscriberDeliversTheEventsItsFiltersMatchToItsQueue() throws Exception { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) { + String queueUrl = sqs.createQueue(request -> request.queueName("v2-large-" + suffix)).queueUrl(); + String queueArn = queueArn(sqs, queueUrl); + String bus = events.createEventBus(request -> request.name("v2-orders-" + suffix)).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("large-orders").eventBusArn(bus) + .invokeConfiguration(invoke -> invoke.targetArn(queueArn).roleArn(ROLE)) + .filterConfiguration(filters -> filters.filters( + filter -> filter.scope(FilterScope.DATA) + .pattern("{\"detail\":{\"total\":[{\"numeric\":[\">\",500]}]}}"), + filter -> filter.scope(FilterScope.SYSTEM_METADATA) + .pattern("{\"aws:Source\":[\"com.shop\"]}")))).subscriberArn(); + assertTrue(subscriber.contains(":subscriber/large-orders/"), subscriber); + + PutEventsResponse published = events.putEvents(request -> request.eventBusArn(bus).entries( + entry -> entry.source("com.shop").detailType("Order Placed").detail("{\"total\":750,\"id\":\"o-1\"}"), + entry -> entry.source("com.shop").detailType("Order Placed").detail("{\"total\":20,\"id\":\"o-2\"}"), + entry -> entry.source("com.other").detailType("Order Placed").detail("{\"total\":900,\"id\":\"o-3\"}"))); + assertEquals(0, published.failedEntryCount()); + assertEquals(3, published.entries().size()); + + List messages = receive(sqs, queueUrl); + assertEquals(1, messages.size(), messages.toString()); + JsonNode body = MAPPER.readTree(messages.getFirst().body()); + assertEquals("o-1", body.path("detail").path("id").asText()); + assertEquals("com.shop", body.path("source").asText()); + assertEquals("Order Placed", body.path("detail-type").asText()); + assertEquals(published.entries().getFirst().eventId(), body.path("id").asText()); + + ResourceInUseException inUse = assertThrows(ResourceInUseException.class, + () -> events.deleteEventBus(request -> request.eventBusArn(bus))); + assertEquals(409, inUse.statusCode()); + events.deleteSubscriber(request -> request.subscriberArn(subscriber)); + events.deleteEventBus(request -> request.eventBusArn(bus)); + assertThrows(ResourceNotFoundException.class, () -> events.putEvents(request -> request.eventBusArn(bus) + .entries(entry -> entry.source("com.shop").detailType("Order Placed")))); + sqs.deleteQueue(request -> request.queueUrl(queueUrl)); + } + } + + @Test + void aWithMetadataSubscriberReceivesTheDataAndItsMetadata() throws Exception { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) { + String queueUrl = sqs.createQueue(request -> request.queueName("v2-meta-" + suffix)).queueUrl(); + String queueArn = queueArn(sqs, queueUrl); + String bus = events.createEventBus(request -> request.name("v2-meta-" + suffix)).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("all").eventBusArn(bus) + .invokeConfiguration(invoke -> invoke.targetArn(queueArn).roleArn(ROLE)) + .transformer(transformer -> transformer.type(TransformerType.WITH_METADATA))).subscriberArn(); + + events.putEvents(request -> request.eventBusArn(bus).entries(entry -> entry.source("com.shop") + .detailType("Order Placed").detail("{\"id\":\"o-9\"}") + .systemMetadata(system -> system.eventGroupId("customer-1")))); + + List messages = receive(sqs, queueUrl); + assertEquals(1, messages.size()); + JsonNode body = MAPPER.readTree(messages.getFirst().body()); + assertEquals("o-9", body.path("Data").path("detail").path("id").asText()); + assertTrue(body.path("Metadata").isObject() && body.path("Metadata").isEmpty(), body.toString()); + assertEquals("application/eventbridge+json", body.path("SystemMetadata").path("ContentType").asText()); + assertEquals("customer-1", body.path("SystemMetadata").path("EventGroupId").asText()); + assertEquals("LIVE", body.path("SystemMetadata").path("aws:DeliveryType").asText()); + + events.deleteSubscriber(request -> request.subscriberArn(subscriber)); + events.deleteEventBus(request -> request.eventBusArn(bus)); + sqs.deleteQueue(request -> request.queueUrl(queueUrl)); + } + } + + @Test + void aStoppedSubscriberDeliversNothing() { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) { + String queueUrl = sqs.createQueue(request -> request.queueName("v2-stopped-" + suffix)).queueUrl(); + String queueArn = queueArn(sqs, queueUrl); + String bus = events.createEventBus(request -> request.name("v2-stopped-" + suffix)).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("paused").eventBusArn(bus) + .state(SubscriberState.STOPPED) + .invokeConfiguration(invoke -> invoke.targetArn(queueArn).roleArn(ROLE))).subscriberArn(); + + events.putEvents(request -> request.eventBusArn(bus).entries(entry -> entry.source("a").detailType("t"))); + assertEquals(List.of(), receive(sqs, queueUrl)); + + events.deleteSubscriber(request -> request.subscriberArn(subscriber)); + events.deleteEventBus(request -> request.eventBusArn(bus)); + sqs.deleteQueue(request -> request.queueUrl(queueUrl)); + } + } + + @Test + void aSubscriberIsDescribedListedAndUpdatedInPlace() throws Exception { + String suffix = suffix(); + try (EventBridgeV2Client events = events(); SqsClient sqs = sqs()) { + String queueUrl = sqs.createQueue(request -> request.queueName("v2-update-" + suffix)).queueUrl(); + String queueArn = queueArn(sqs, queueUrl); + String bus = events.createEventBus(request -> request.name("v2-update-" + suffix)).eventBusArn(); + String subscriber = events.createSubscriber(request -> request.name("orders").eventBusArn(bus) + .description("all orders") + .invokeConfiguration(invoke -> invoke.targetArn(queueArn).roleArn(ROLE)) + .filterConfiguration(filters -> filters.filters(filter -> filter.scope(FilterScope.DATA) + .pattern("{\"source\":[\"com.shop\"]}")))).subscriberArn(); + + DescribeSubscriberResponse described = events.describeSubscriber(request -> request + .subscriberArn(subscriber)); + assertEquals("orders", described.name()); + assertEquals(bus, described.eventBusArn()); + assertEquals(queueArn, described.invokeConfiguration().targetArn()); + assertEquals("all orders", described.description()); + assertEquals("{\"source\":[\"com.shop\"]}", described.filterConfiguration().filters().getFirst().pattern()); + assertEquals(SubscriberState.RUNNING, described.state()); + assertEquals(Boolean.FALSE, described.revoked()); + // The SDK decodes these only from CBOR timestamps. + assertNotNull(described.creationTime()); + assertNotNull(described.lastModifiedTime()); + + SubscriberSummary listed = events.listSubscribers(request -> request.eventBusArn(bus)).subscribers() + .getFirst(); + assertEquals(subscriber, listed.subscriberArn()); + assertEquals(queueArn, listed.targetArn()); + assertEquals("000000000000", listed.subscriberAccountId()); + assertNotNull(listed.creationTime()); + + UpdateSubscriberResponse updated = events.updateSubscriber(request -> request.subscriberArn(subscriber) + .filterConfiguration(filters -> filters.filters(filter -> filter.scope(FilterScope.DATA) + .pattern("{\"source\":[\"com.other\"]}")))); + assertEquals(subscriber, updated.subscriberArn()); + assertNotNull(updated.lastModifiedTime()); + assertEquals("all orders", events.describeSubscriber(request -> request.subscriberArn(subscriber)) + .description(), "what the update leaves out is kept"); + + events.putEvents(request -> request.eventBusArn(bus).entries( + entry -> entry.source("com.shop").detailType("t").detail("{\"id\":\"old\"}"), + entry -> entry.source("com.other").detailType("t").detail("{\"id\":\"new\"}"))); + List messages = receive(sqs, queueUrl); + assertEquals(1, messages.size(), messages.toString()); + assertEquals("new", MAPPER.readTree(messages.getFirst().body()).path("detail").path("id").asText()); + + events.updateSubscriber(request -> request.subscriberArn(subscriber).state(SubscriberState.STOPPED)); + sqs.deleteMessage(request -> request.queueUrl(queueUrl).receiptHandle(messages.getFirst().receiptHandle())); + events.putEvents(request -> request.eventBusArn(bus).entries( + entry -> entry.source("com.other").detailType("t"))); + assertEquals(List.of(), receive(sqs, queueUrl)); + + events.deleteSubscriber(request -> request.subscriberArn(subscriber)); + events.deleteEventBus(request -> request.eventBusArn(bus)); + sqs.deleteQueue(request -> request.queueUrl(queueUrl)); + } + } + + @Test + void aFilterWithAWildcardIsRejected() { + String suffix = suffix(); + try (EventBridgeV2Client events = events()) { + String bus = events.createEventBus(request -> request.name("v2-wild-" + suffix)).eventBusArn(); + InvalidInputException e = assertThrows(InvalidInputException.class, () -> events.createSubscriber( + request -> request.name("wild").eventBusArn(bus) + .invokeConfiguration(invoke -> invoke.roleArn(ROLE) + .targetArn("arn:aws:sqs:us-east-1:000000000000:any")) + .filterConfiguration(filters -> filters.filters(filter -> filter.scope(FilterScope.DATA) + .pattern("{\"source\":[{\"wildcard\":\"com.*\"}]}"))))); + assertEquals(SubscriberFilters.WILDCARD_MESSAGE, e.awsErrorDetails().errorMessage()); + events.deleteEventBus(request -> request.eventBusArn(bus)); + } + } + + private static List receive(SqsClient sqs, String queueUrl) { + return sqs.receiveMessage(request -> request.queueUrl(queueUrl).maxNumberOfMessages(10).waitTimeSeconds(1)) + .messages(); + } + + private static String queueArn(SqsClient sqs, String queueUrl) { + return sqs.getQueueAttributes(request -> request.queueUrl(queueUrl) + .attributeNames(QueueAttributeName.QUEUE_ARN)).attributes().get(QueueAttributeName.QUEUE_ARN); + } + + private static EventBridgeV2Client events() { + return EventBridgeV2Client.builder() + .endpointOverride(endpoint()) + .httpClientBuilder(UrlConnectionHttpClient.builder()) + .region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) + .build(); + } + + private static SqsClient sqs() { + return SqsClient.builder() + .endpointOverride(endpoint()) + .httpClientBuilder(UrlConnectionHttpClient.builder()) + .region(Region.US_EAST_1) + .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"))) + .build(); + } + + private static URI endpoint() { + return URI.create("http://localhost:" + RestAssured.port); + } + + private static String suffix() { + return Long.toString(System.nanoTime(), 36); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventExpressionsTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventExpressionsTest.java new file mode 100644 index 0000000000..f8ef9bd4f2 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/EventExpressionsTest.java @@ -0,0 +1,39 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class EventExpressionsTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void aPathIntoTheEventResolvesToItsValue() throws Exception { + PublishedEvent event = new PublishedEvent( + MAPPER.readTree("{\"detail-type\":\"Order Placed\",\"detail\":{\"customerId\":\"c-1\",\"total\":7}}"), + MAPPER.createObjectNode(), + (ObjectNode) MAPPER.readTree("{\"EventGroupId\":\"g1\",\"aws:EventId\":\"e-1\"}")); + + assertEquals(Optional.of("literal"), EventExpressions.resolve("literal", event)); + assertEquals(Optional.of("g1"), EventExpressions.resolve("{% $events.SystemMetadata.EventGroupId %}", event)); + assertEquals(Optional.of("e-1"), EventExpressions.resolve("{% $events.SystemMetadata.\"aws:EventId\" %}", event)); + assertEquals(Optional.of("Order Placed"), EventExpressions.resolve("{% $events.Data.`detail-type` %}", event)); + assertEquals(Optional.of("7"), EventExpressions.resolve("{%$events.Data.detail.total%}", event)); + assertEquals(Optional.empty(), EventExpressions.resolve("{% $events.Data.detail.missing %}", event)); + } + + @Test + void onlyALiteralOrAPathIsSupported() { + assertTrue(EventExpressions.isSupported("group-1")); + assertTrue(EventExpressions.isSupported("{% $events.Data.id %}")); + assertFalse(EventExpressions.isSupported("{% $uuid() %}")); + assertFalse(EventExpressions.isSupported("{% $events.Data.a & $events.Data.b %}")); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/SubscriberFiltersTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/SubscriberFiltersTest.java new file mode 100644 index 0000000000..320b489338 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridgev2/SubscriberFiltersTest.java @@ -0,0 +1,156 @@ +package io.github.hectorvent.floci.services.eventbridgev2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.AwsException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.util.Collections; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class SubscriberFiltersTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void aFilterPerScopeValidates() { + assertDoesNotThrow(() -> SubscriberFilters.validate(json("{\"Language\":\"EVENT_BRIDGE_PATTERN\",\"Filters\":[" + + filter("DATA", "{\"detail\":{\"total\":[{\"numeric\":[\">\",500]}]}}") + "," + + filter("METADATA", "{\"region\":[\"EU\"]}") + "," + + filter("SYSTEM_METADATA", "{\"aws:Source\":[{\"prefix\":\"com.\"}]}") + "]}"))); + } + + @ParameterizedTest + @ValueSource(strings = { + "{}", + "{\"Filters\":[]}", + "{\"Language\":\"JSONATA\",\"Filters\":[F_DATA]}", + "{\"Filters\":[{\"Scope\":\"DATA\",\"Pattern\":\"\"}]}", + "{\"Filters\":[{\"Scope\":\"PAYLOAD\",\"Pattern\":\"{}\"}]}", + "{\"Filters\":[F_DATA,F_DATA]}", + "{\"Filters\":[{\"Scope\":\"DATA\",\"Pattern\":\"not json\"}]}", + "{\"Filters\":[{\"Scope\":\"METADATA\",\"Pattern\":\"[]\"}]}", + "{\"Filters\":[{\"Scope\":\"METADATA\",\"Pattern\":\"{\\\"region\\\":[{\\\"prefix\\\":\\\"E\\\"}]}\"}]}", + "{\"Filters\":[{\"Scope\":\"DATA\",\"Pattern\":\"{\\\"a\\\":[{\\\"wildcard\\\":\\\"*x\\\"}]}\"}]}", + "{\"Filters\":[{\"Scope\":\"DATA\",\"Pattern\":\"{\\\"a\\\":[{\\\"anything-but\\\":{\\\"wildcard\\\":\\\"*\\\"}}]}\"}]}" + }) + void aConfigurationAwsRejectsIsInvalidInput(String configuration) { + AwsException e = assertThrows(AwsException.class, () -> SubscriberFilters.validate( + json(configuration.replace("F_DATA", filter("DATA", "{\"source\":[\"a\"]}"))))); + assertEquals("InvalidInputException", e.getErrorCode()); + } + + @Test + void aWildcardIsRejectedWithAwsMessage() { + AwsException e = assertThrows(AwsException.class, () -> SubscriberFilters.validate(json( + "{\"Filters\":[" + filter("DATA", "{\"a\":[{\"wildcard\":\"x*\"}]}") + "]}"))); + assertEquals(SubscriberFilters.WILDCARD_MESSAGE, e.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = { + "{\"detail\":{\"wildcard\":[\"on\"],\"prefix\":{\"numeric\":[1]}}}", + "{\"$or\":[{\"source\":[{\"prefix\":\"com.\"}]},{\"detail\":{\"total\":[{\"numeric\":[\">\",1,\"<\",9]}]}}]}", + "{\"a\":[{\"exists\":false},{\"suffix\":{\"equals-ignore-case\":\".PNG\"}},{\"equals-ignore-case\":\"x\"}]}", + "{\"a\":[{\"anything-but\":[\"x\",1]},{\"anything-but\":{\"prefix\":\"y\"}}," + + "{\"anything-but\":{\"equals-ignore-case\":[\"a\",\"b\"]}},{\"anything-but\":\"z\"}]}" + }) + void aPatternWithOnlyMatchersFlociEvaluatesValidates(String pattern) { + assertDoesNotThrow(() -> SubscriberFilters.validate(json("{\"Filters\":[" + filter("DATA", pattern) + "]}"))); + } + + @ParameterizedTest + @ValueSource(strings = { + "{\"ip\":[{\"cidr\":\"10.0.0.0/24\"}]}", + "{\"a\":[{\"anything-but\":{\"numeric\":[\">\",1]}}]}", + "{\"a\":[{\"prefix\":\"x\",\"suffix\":\"y\"}]}", + "{\"$or\":[{\"a\":[{\"cidr\":\"10.0.0.0/8\"}]},{\"b\":[\"x\"]}]}", + "{\"a\":[{\"anything-but\":[]}]}", + "{\"a\":[{\"anything-but\":{\"equals-ignore-case\":[]}}]}" + }) + void aMatcherFlociCannotEvaluateIsRejectedRatherThanNeverMatching(String pattern) { + AwsException e = assertThrows(AwsException.class, () -> SubscriberFilters.validate( + json("{\"Filters\":[" + filter("DATA", pattern) + "]}"))); + assertEquals("InvalidInputException", e.getErrorCode()); + assertTrue(e.getMessage().startsWith("Floci does not evaluate the filter matcher"), e.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = { + "{\"source\":\"my.app\"}", + "{\"detail\":{\"total\":500}}", + "{\"a\":[[\"x\"]]}", + "{\"$or\":{\"a\":[\"x\"]}}", + "{\"$or\":[\"x\"]}", + "{\"$or\":[{\"a\":[\"x\"]}]}", + "{\"a\":[{\"numeric\":[\">\",\"abc\"]}]}", + "{\"a\":[{\"numeric\":[\"!=\",1]}]}", + "{\"a\":[{\"numeric\":[]}]}" + }) + void aPatternThatWouldSilentlyMatchNothingIsInvalidInput(String pattern) { + AwsException e = assertThrows(AwsException.class, () -> SubscriberFilters.validate( + json("{\"Filters\":[" + filter("DATA", pattern) + "]}"))); + assertEquals("InvalidInputException", e.getErrorCode()); + } + + @Test + void nestedOrBranchesAreCountedAsAlternatives() { + String inner = "{\"$or\":[{\"x\":[\"1\"]},{\"y\":[\"2\"]}]}"; + String outer = "{\"$or\":[" + String.join(",", Collections.nCopies(10, inner)) + "]}"; + assertDoesNotThrow(() -> SubscriberFilters.validate(json("{\"Filters\":[" + filter("DATA", outer) + "]}")), + "10 branches of 2 alternatives each are 20 combinations, not 10 x 2^10"); + } + + @Test + void orListsThatMustMatchTogetherMultiplyPastTheLimit() { + String branches = IntStream.range(0, 32).mapToObj(i -> "{\"v\":[\"" + i + "\"]}") + .collect(Collectors.joining(",")); + String pattern = "{\"a\":{\"$or\":[" + branches + "]},\"b\":{\"$or\":[" + branches + "]}}"; + AwsException e = assertThrows(AwsException.class, () -> SubscriberFilters.validate( + json("{\"Filters\":[" + filter("DATA", pattern) + "]}"))); + assertTrue(e.getMessage().contains("1000 combinations"), e.getMessage()); + } + + @Test + void patternsOverFourKilobytesInAllAreRejected() { + String big = "{\"a\":[\"" + "x".repeat(2100) + "\"]}"; + assertThrows(AwsException.class, () -> SubscriberFilters.validate(json("{\"Filters\":[" + + filter("DATA", big) + "," + filter("SYSTEM_METADATA", big) + "]}"))); + } + + @Test + void anEventMustMatchEveryFilterAndNoConfigurationMatchesAll() { + ObjectNode metadata = (ObjectNode) json("{\"region\":\"EU\"}"); + ObjectNode system = (ObjectNode) json("{\"ContentType\":\"application/json\"}"); + PublishedEvent event = new PublishedEvent(json("{\"amount\":600}"), metadata, system); + JsonNode both = json("{\"Filters\":[" + filter("DATA", "{\"amount\":[{\"numeric\":[\">\",500]}]}") + "," + + filter("METADATA", "{\"region\":[\"EU\"]}") + "]}"); + assertTrue(SubscriberFilters.matches(both, event)); + assertFalse(SubscriberFilters.matches(both, new PublishedEvent(json("{\"amount\":600}"), + (ObjectNode) json("{\"region\":\"US\"}"), system))); + assertTrue(SubscriberFilters.matches(null, event)); + assertTrue(SubscriberFilters.matches(json("{}"), event)); + } + + private static String filter(String scope, String pattern) { + return "{\"Scope\":\"" + scope + "\",\"Pattern\":" + MAPPER.valueToTree(pattern).toString() + "}"; + } + + private static JsonNode json(String value) { + try { + return MAPPER.readTree(value); + } catch (Exception e) { + throw new AssertionError(e); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestResourceEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestResourceEnforcementIntegrationTest.java index e55eab2281..04293d91fb 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestResourceEnforcementIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamRequestResourceEnforcementIntegrationTest.java @@ -18,6 +18,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import java.io.IOException; +import java.io.UncheckedIOException; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Base64; @@ -411,6 +412,80 @@ class IamRequestResourceEnforcementIntegrationTest { putEvents(user, "", ",\"EventBusName\":null").statusCode(200).body("FailedEntryCount", equalTo(0)); } + /** + * EventBridge V2 is authorized as the same {@code events} actions, on the bus or subscriber its request's ARN + * names: a grant on one V2 bus publishes to it and to no other, the default bus never standing in for it, a deny + * on it holds, a subscriber is checked on its own ARN rather than {@code *}, and a new bus on its name. + */ + @Test + void anEventBridgeV2RequestIsCheckedOnTheBusOrSubscriberItsArnNames() throws IOException { + String bus = createEventBusV2("res-v2-" + suffix()); + String other = createEventBusV2("res-v2-other-" + suffix()); + User user = user("res-v2"); + + user.policy(allowOn("events:PutEvents", bus)); + eventsV2(user, "PutEvents", putEventsV2(bus)).statusCode(200).body(not(containsString("ErrorCode"))); + refusedCbor(eventsV2(user, "PutEvents", putEventsV2(other)), "events:PutEvents"); + user.policy(allowOn("events:PutEvents", EVENTS + "event-bus/default")); + refusedCbor(eventsV2(user, "PutEvents", putEventsV2(bus)), "events:PutEvents"); + user.policy(allowOn("events:PutEvents", "*") + ",{\"Effect\":\"Deny\",\"Action\":\"events:PutEvents\"," + + "\"Resource\":\"" + bus + "\"}"); + refusedCbor(eventsV2(user, "PutEvents", putEventsV2(bus)), "events:PutEvents"); + eventsV2(user, "PutEvents", putEventsV2(other)).statusCode(200); + + String subscriber = EVENTS + "subscriber/res-v2-sub/" + suffix(); + user.policy(allowOn("events:DescribeSubscriber", subscriber)); + eventsV2(user, "DescribeSubscriber", Map.of("SubscriberArn", subscriber)).statusCode(404) + .body(containsString("ResourceNotFoundException")); + refusedCbor(eventsV2(user, "DescribeSubscriber", Map.of("SubscriberArn", subscriber + "0")), + "events:DescribeSubscriber"); + + String created = "res-v2-new-" + suffix(); + user.policy(allowOn("events:CreateEventBus", EVENTS + "event-busv2/" + created + "/*")); + refusedCbor(eventsV2(user, "CreateEventBus", Map.of("Name", created + "-other", "ClientToken", suffix())), + "events:CreateEventBus"); + String createdArn = CBOR_MAPPER.readTree(eventsV2(user, "CreateEventBus", + Map.of("Name", created, "ClientToken", suffix())).statusCode(200).extract().asByteArray()) + .path("EventBusArn").asText(); + cleanup.register(() -> deleteEventBusV2(createdArn)); + assertTrue(createdArn.startsWith(EVENTS + "event-busv2/" + created + "/"), createdArn); + + // A subscriber's tags are checked on the subscriber it makes, not on the bus it names. + String tagged = "res-v2-tagged-" + suffix(); + String role = "arn:aws:iam::" + ACCOUNT + ":role/res-v2-delivery"; + user.policy(allowOn("iam:PassRole", role) + "," + allowOn("events:CreateSubscriber", bus) + "," + + allowOn("events:CreateSubscriber", EVENTS + "subscriber/" + tagged + "/*") + "," + + allowOn("events:TagResource", EVENTS + "subscriber/*")); + Map subscriberRequest = Map.of("Name", tagged, "EventBusArn", bus, + "InvokeConfiguration", Map.of("TargetArn", "arn:aws:sqs:" + REGION + ":" + ACCOUNT + ":res-v2-queue", + "RoleArn", role), + "Tags", Map.of("team", "orders")); + String subscriberArn = CBOR_MAPPER.readTree(eventsV2(user, "CreateSubscriber", subscriberRequest) + .statusCode(200).extract().asByteArray()).path("SubscriberArn").asText(); + cleanup.register(() -> deleteSubscriberV2(subscriberArn)); + user.policy(allowOn("iam:PassRole", role) + "," + allowOn("events:CreateSubscriber", bus) + "," + + allowOn("events:CreateSubscriber", EVENTS + "subscriber/*") + "," + + allowOn("events:TagResource", bus)); + refusedCbor(eventsV2(user, "CreateSubscriber", Map.of("Name", tagged + "-other", "EventBusArn", bus, + "InvokeConfiguration", subscriberRequest.get("InvokeConfiguration"), "Tags", Map.of("team", "orders"))), + "events:TagResource"); + + // An EventBridge request adding the ARN of a V2 bus the caller may delete is still checked on its own bus. + String locked = "res-v1-locked-" + suffix(); + admin("events").header("X-Amz-Target", "AWSEvents.CreateEventBus").contentType("application/x-amz-json-1.1") + .body("{\"Name\":\"" + locked + "\"}").post("/").then().statusCode(200); + cleanup.register(() -> admin("events").header("X-Amz-Target", "AWSEvents.DeleteEventBus") + .contentType("application/x-amz-json-1.1").body("{\"Name\":\"" + locked + "\"}").post("/")); + user.policy(allowOn("events:DeleteEventBus", bus) + "," + allowOn("events:DescribeEventBus", bus)); + for (String operation : List.of("DeleteEventBus", "DescribeEventBus")) { + refusedJson(user.json("events", "AWSEvents." + operation, "1.1") + .body("{\"Name\":\"" + locked + "\",\"EventBusArn\":\"" + bus + "\"}").post("/").then(), + "events:" + operation); + } + admin("events").header("X-Amz-Target", "AWSEvents.DescribeEventBus").contentType("application/x-amz-json-1.1") + .body("{\"Name\":\"" + locked + "\"}").post("/").then().statusCode(200); + } + @Test void aUserPoolIsCheckedOnTheArnItsIdNames() { String id = admin("cognito-idp").header("X-Amz-Target", "AWSCognitoIdentityProviderService.CreateUserPool") @@ -1369,6 +1444,54 @@ class IamRequestResourceEnforcementIntegrationTest { .post("/").then(); } + private String createEventBusV2(String name) throws IOException { + String arn = CBOR_MAPPER.readTree(admin("events").header("smithy-protocol", "rpc-v2-cbor") + .contentType("application/cbor").accept("application/cbor") + .body(CBOR_MAPPER.writeValueAsBytes(Map.of("Name", name))) + .post("/service/AWSEventsV2/operation/CreateEventBus").then().statusCode(200).extract().asByteArray()) + .path("EventBusArn").asText(); + cleanup.register(() -> deleteEventBusV2(arn)); + return arn; + } + + private static void deleteEventBusV2(String arn) { + try { + admin("events").header("smithy-protocol", "rpc-v2-cbor").contentType("application/cbor") + .accept("application/cbor").body(CBOR_MAPPER.writeValueAsBytes(Map.of("EventBusArn", arn))) + .post("/service/AWSEventsV2/operation/DeleteEventBus"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static void deleteSubscriberV2(String arn) { + try { + admin("events").header("smithy-protocol", "rpc-v2-cbor").contentType("application/cbor") + .accept("application/cbor").body(CBOR_MAPPER.writeValueAsBytes(Map.of("SubscriberArn", arn))) + .post("/service/AWSEventsV2/operation/DeleteSubscriber"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + /** One event published to the EventBridge V2 bus. */ + private static Map putEventsV2(String bus) { + return Map.of("EventBusArn", bus, "Entries", List.of(Map.of("Source", "res.test", "DetailType", "t", + "Detail", "{}"))); + } + + private static ValidatableResponse eventsV2(User user, String operation, Map body) throws IOException { + return user.cbor("events").body(CBOR_MAPPER.writeValueAsBytes(body)) + .post("/service/AWSEventsV2/operation/" + operation).then(); + } + + /** An RPC v2 CBOR service refuses with {@code AccessDeniedException}, a 403, naming the missing permission. */ + private static void refusedCbor(ValidatableResponse response, String action) throws IOException { + JsonNode error = CBOR_MAPPER.readTree(response.statusCode(403).extract().asByteArray()); + assertEquals("AccessDeniedException", error.path("__type").asText()); + assertTrue(error.path("message").asText().contains(action), error.toString()); + } + private static String publishVersion(String arn) { return admin("states").header("X-Amz-Target", "AWSStepFunctions.PublishStateMachineVersion") .contentType("application/x-amz-json-1.0").body("{\"stateMachineArn\":\"" + arn + "\"}") diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaMatcherIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaMatcherIntegrationTest.java index 00eae0cd89..a30ac31bbf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaMatcherIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/EsmFilterCriteriaMatcherIntegrationTest.java @@ -18,9 +18,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; * {@link EsmFilterCriteriaUtils#matcherSourceParameters}, actually drives the REAL * {@link PipesFilterMatcher}, not just that the wrapper has the right field names. Without this, the * wrapper could be shaped wrong (silently disabling filtering) and unit tests inspecting only its fields - * would stay green. Uses supported EventBridge operators the matcher implements; known matcher deviations - * (boolean literals, event-array intersection, numeric anything-but) are documented, not covered here, per - * the reuse-the-matcher scope decision. + * would stay green. Uses supported EventBridge operators the matcher implements; the operators themselves + * are covered by {@code PipesFilterMatcherTest}. */ class EsmFilterCriteriaMatcherIntegrationTest { diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEsmFilterCriteriaValidationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEsmFilterCriteriaValidationTest.java index cbf5ec375b..2b88028678 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEsmFilterCriteriaValidationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaEsmFilterCriteriaValidationTest.java @@ -124,10 +124,19 @@ class LambdaEsmFilterCriteriaValidationTest { assertRejected(filtersReq("{\"body\":{\"inner\":[{\"numeric\":[\">\",\"abc\"]}]}}")); } - /** A boolean literal is not a match value the matcher compares, so it can never match. */ @Test - void booleanLiteralMatchValueIsRejected() { - assertRejected(filtersReq("{\"value\":[true]}")); + void booleanLiteralAndOrAreAccepted() { + assertNotNull(LambdaService.parseFilterCriteria(filtersReq( + "{\"value\":[true],\"$or\":[{\"a\":[\"x\"]},{\"body\":{\"b\":[{\"prefix\":\"y\"}]}}]}"), MAPPER)); + } + + /** Each {@code $or} branch is a pattern, validated like the top level. */ + @Test + void malformedOrIsRejected() { + assertRejected(filtersReq("{\"$or\":[]}")); + assertRejected(filtersReq("{\"$or\":{\"a\":[\"x\"]}}")); + assertRejected(filtersReq("{\"$or\":[\"x\"]}")); + assertRejected(filtersReq("{\"$or\":[{\"a\":[{\"numeric\":[\">\"]}]}]}")); } // ──────────── accepted ──────────── diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesFilterMatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesFilterMatcherTest.java index 9fff5ee76b..d44c79f898 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesFilterMatcherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesFilterMatcherTest.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import java.util.List; @@ -13,6 +15,10 @@ import static org.junit.jupiter.api.Assertions.*; class PipesFilterMatcherTest { private static final ObjectMapper MAPPER = new ObjectMapper(); + private static final String EVENT = "{\"source\":\"com.shop\",\"detail-type\":\"Order Placed\"," + + "\"resources\":[\"arn:aws:sqs:us-east-1:000000000000:a\",\"r2\"]," + + "\"detail\":{\"total\":750,\"status\":\"NEW\",\"customer\":{\"tier\":\"gold\"},\"note\":null," + + "\"items\":[{\"sku\":\"A1\"},{\"sku\":\"B2\"}]}}"; private PipesFilterMatcher matcher; @BeforeEach @@ -199,6 +205,28 @@ class PipesFilterMatcherTest { assertFalse(matcher.matchesRecord(nonNull, "{\"body\": [null]}")); } + @Test + void nullMatch_doesNotMatchMissingField() throws Exception { + JsonNode record = MAPPER.readTree("{\"other\": \"value\"}"); + assertFalse(matcher.matchesRecord(record, "{\"body\": [null]}")); + } + + @Test + void booleanMatch() throws Exception { + JsonNode record = MAPPER.readTree("{\"flagged\": true}"); + assertTrue(matcher.matchesRecord(record, "{\"flagged\": [true]}")); + assertFalse(matcher.matchesRecord(record, "{\"flagged\": [false]}")); + } + + @Test + void orAcrossFields() throws Exception { + JsonNode record = MAPPER.readTree("{\"body\": \"{\\\"day\\\": \\\"Monday\\\"}\"}"); + assertTrue(matcher.matchesRecord(record, + "{\"$or\": [{\"body\": {\"location\": [\"New York\"]}}, {\"body\": {\"day\": [\"Monday\"]}}]}")); + assertFalse(matcher.matchesRecord(record, + "{\"$or\": [{\"body\": {\"location\": [\"New York\"]}}, {\"body\": {\"day\": [\"Friday\"]}}]}")); + } + @Test void numericExactMatch() throws Exception { JsonNode record = MAPPER.readTree("{\"count\": 42}"); @@ -229,30 +257,30 @@ class PipesFilterMatcherTest { } @Test - void anythingBut_array_matchesMissingField() throws Exception { + void anythingBut_array_doesNotMatchMissingField() throws Exception { JsonNode record = MAPPER.readTree("{\"other\": \"value\"}"); - assertTrue(matcher.matchesRecord(record, + assertFalse(matcher.matchesRecord(record, "{\"eventSource\": [{\"anything-but\": [\"aws:sqs\"]}]}")); } @Test - void anythingBut_string_matchesMissingField() throws Exception { + void anythingBut_string_doesNotMatchMissingField() throws Exception { JsonNode record = MAPPER.readTree("{\"other\": \"value\"}"); - assertTrue(matcher.matchesRecord(record, + assertFalse(matcher.matchesRecord(record, "{\"eventSource\": [{\"anything-but\": \"aws:sqs\"}]}")); } @Test - void anythingButPrefix_matchesMissingField() throws Exception { + void anythingButPrefix_doesNotMatchMissingField() throws Exception { JsonNode record = MAPPER.readTree("{\"other\": \"value\"}"); - assertTrue(matcher.matchesRecord(record, + assertFalse(matcher.matchesRecord(record, "{\"eventSource\": [{\"anything-but\": {\"prefix\": \"aws:\"}}]}")); } @Test - void existsTrue_doesNotMatchNullValue() throws Exception { + void existsTrue_matchesNullValue() throws Exception { JsonNode record = MAPPER.readTree("{\"body\": null}"); - assertFalse(matcher.matchesRecord(record, "{\"body\": [{\"exists\": true}]}")); + assertTrue(matcher.matchesRecord(record, "{\"body\": [{\"exists\": true}]}")); } @Test @@ -261,9 +289,73 @@ class PipesFilterMatcherTest { assertFalse(matcher.matchesRecord(record, "{\"count\": [{\"prefix\": \"4\"}]}")); } + @Test + void invalidPattern_matchesNothing() throws Exception { + JsonNode record = MAPPER.readTree("{\"count\": 42}"); + assertFalse(matcher.matchesRecord(record, "{\"count\": [{\"cidr\": \"10.0.0.0/24\"}]}")); + assertFalse(matcher.matchesRecord(record, "{\"count\": [{\"numeric\": [\">\"]}]}")); + assertFalse(matcher.matchesRecord(record, "not json")); + } + + @Test + void invalidPattern_isLeftToTheCaller() throws Exception { + JsonNode record = MAPPER.readTree("{\"count\": 42}"); + assertThrows(IllegalArgumentException.class, + () -> PipesFilterMatcher.matches(json("{\"count\": [{\"cidr\": \"10.0.0.0/24\"}]}"), record)); + assertThrows(IllegalArgumentException.class, + () -> PipesFilterMatcher.matches(json("{\"count\": [{\"numeric\": [\">\", \"abc\"]}]}"), record)); + assertThrows(IllegalArgumentException.class, + () -> PipesFilterMatcher.matches(json("{\"count\": 42}"), record)); + } + + @Test + void eventPattern_doesNotParseStringFields() throws Exception { + JsonNode record = MAPPER.readTree("{\"body\": \"{\\\"status\\\": \\\"active\\\"}\"}"); + assertFalse(PipesFilterMatcher.matches(json("{\"body\": {\"status\": [\"active\"]}}"), record)); + } + + // ──────────────────────────── EventBridge event patterns ──────────────────────────── + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "{\"source\":[\"com.shop\"]}|true", + "{\"source\":[\"com.other\",\"com.shop\"]}|true", + "{\"source\":[\"com.other\"]}|false", + "{\"detail\":{\"total\":[{\"numeric\":[\">\",500]}]}}|true", + "{\"detail\":{\"total\":[{\"numeric\":[\">\",500,\"<=\",750]}]}}|true", + "{\"detail\":{\"total\":[{\"numeric\":[\">\",750]}]}}|false", + "{\"detail\":{\"total\":[750.0]}}|true", + "{\"detail\":{\"status\":[{\"prefix\":\"NE\"}]}}|true", + "{\"detail\":{\"status\":[{\"suffix\":\"EW\"}]}}|true", + "{\"detail\":{\"status\":[{\"prefix\":{\"equals-ignore-case\":\"ne\"}}]}}|true", + "{\"detail\":{\"status\":[{\"equals-ignore-case\":\"new\"}]}}|true", + "{\"detail\":{\"status\":[{\"anything-but\":[\"OLD\",\"VOID\"]}]}}|true", + "{\"detail\":{\"status\":[{\"anything-but\":\"NEW\"}]}}|false", + "{\"detail\":{\"status\":[{\"anything-but\":{\"prefix\":\"N\"}}]}}|false", + "{\"detail\":{\"status\":[{\"anything-but\":{\"suffix\":\"EW\"}}]}}|false", + "{\"detail\":{\"status\":[{\"anything-but\":{\"equals-ignore-case\":[\"new\"]}}]}}|false", + "{\"detail\":{\"missing\":[{\"anything-but\":\"x\"}]}}|false", + "{\"detail\":{\"missing\":[{\"exists\":false}]}}|true", + "{\"detail\":{\"status\":[{\"exists\":false}]}}|false", + "{\"detail\":{\"note\":[null]}}|true", + "{\"detail\":{\"customer\":{\"tier\":[\"gold\"]}}}|true", + "{\"detail\":{\"customer\":{\"tier\":[\"silver\"]}}}|false", + "{\"detail\":{\"items\":{\"sku\":[\"B2\"]}}}|true", + "{\"resources\":[\"r2\"]}|true", + "{\"$or\":[{\"source\":[\"x\"]},{\"detail\":{\"status\":[\"NEW\"]}}]}|true", + "{\"$or\":[{\"source\":[\"x\"]},{\"detail\":{\"status\":[\"OLD\"]}}]}|false" + }) + void eventPattern_matchesAsEventBridgeDefinesIt(String pattern, boolean matches) throws Exception { + assertEquals(matches, PipesFilterMatcher.matches(json(pattern), json(EVENT)), pattern); + } + @Test void numericFilter_withNonNumber_doesNotMatch() throws Exception { JsonNode record = MAPPER.readTree("{\"count\": \"not-a-number\"}"); assertFalse(matcher.matchesRecord(record, "{\"count\": [{\"numeric\": [\"=\", 42]}]}")); } + + private static JsonNode json(String value) throws Exception { + return MAPPER.readTree(value); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java index 3623428d89..6709808775 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java @@ -741,7 +741,7 @@ class PipesPollerTest { }, "FilterCriteria": { "Filters": [ - {"Pattern": "{\\\"key\\\": [{\\\"exists\\\": false}]}"} + {"Pattern": "{\\\"key\\\": [null]}"} ] } } diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index 79fd9ba177..59dbe89f16 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -266,6 +266,8 @@ floci: default-image: "tinkerpop/gremlin-server:3.7.3" eventbridge: enabled: true + eventbridgev2: + enabled: true cloudmap: enabled: true emr: diff --git a/tools/aws/regen_iam_request_resources.py b/tools/aws/regen_iam_request_resources.py index 1788fc5260..9d55cf440f 100644 --- a/tools/aws/regen_iam_request_resources.py +++ b/tools/aws/regen_iam_request_resources.py @@ -75,7 +75,10 @@ element lacking it (`PutEvents` publishes each entry to its bus), or from a stru a variable no member gives may be `fixed` to the one value its handler uses (a CodePipeline custom action type's owner, `Custom`), and an ARN member's value may be read only up to a character `before` which its handler drops the rest (`StartExecution`'s -`#`). `CLIENTS_NOT_READ` are SDK clients the reference lists for a +`#`). A resource there may also apply only to the requests of the client whose +`endpoint` prefix it names, where two clients give an operation of one name and nothing in a request tells them +apart (EventBridge's `CreateEventBus` and EventBridge V2's); Floci reads that from the service serving the +request, never from a member a caller could add. `CLIENTS_NOT_READ` are SDK clients the reference lists for a namespace's operations whose requests Floci does not serve, each with its reason. `UNQUALIFIED` are the resource types whose ARN a request may give with a qualifier, one more `:` past its format, and whose service checks it without one: Step Functions checks a version or an alias @@ -132,9 +135,6 @@ NAMESPACES = ("acm", "application-autoscaling", "athena", "bcm-data-exports", "b # SDK clients the reference lists for a namespace's operations whose requests Floci does not serve, and why: their # members are not read. CLIENTS_NOT_READ: dict[str, str] = { - "eventbridgev2": "EventBridge V2, the AWSEventsV2 target over Smithy RPC v2 CBOR on the eventsv2 endpoint, which " - "Floci does not serve; its operations share EventBridge's names and name their resources by " - "other members", "kinesisanalytics": "Kinesis Data Analytics v1, SQL applications on the KinesisAnalytics_20150814 target, which " "Floci does not serve (it serves v2, kinesisanalyticsv2); its operations share v2's names and " "name their resources by other members", @@ -247,7 +247,10 @@ NOT_COVERED: dict[str, str] = { } # An operation's resources where the rule gets them wrong: the resources, and why. A resource's `when` names the -# values of a member it applies for, null for the member absent. +# values of a member it applies for, null for the member absent. Its `endpoint` names the endpoint prefix of the one +# client whose requests it applies to, where two clients share the operation's name and nothing a request gives tells +# them apart (EventBridge's `events` and EventBridge V2's `eventsv2`): Floci applies it only to a request the service +# of that endpoint serves, never by a member a caller could add to a request of the other. CORRECTIONS: dict[str, tuple[list[dict], str]] = { "elasticloadbalancing:CreateLoadBalancer": ([ {"type": "loadbalancer", "fill": {"LoadBalancerName": "LoadBalancerName"}}, @@ -316,15 +319,36 @@ CORRECTIONS: dict[str, tuple[list[dict], str]] = { for operation, rule in (("DeleteRule", "Name"), ("DescribeRule", "Name"), ("DisableRule", "Name"), ("EnableRule", "Name"), ("ListTargetsByRule", "Rule"), ("PutRule", "Name"), ("PutTargets", "Rule"), ("RemoveTargets", "Rule"))}, - "events:DescribeEventBus": ([{"type": "event-bus", "fill": {"EventBusName": "Name"}, "absent": {"Name": "default"}}], + "events:DescribeEventBus": ([{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, + {"type": "event-bus", "fill": {"EventBusName": "Name"}, "absent": {"Name": "default"}, + "endpoint": "events"}], "a request naming no event bus describes the default one ('If you omit this, the " - "default event bus is displayed')"), - "events:PutEvents": ([{"type": "event-bus", "fill": {"EventBusName": "Entries[].EventBusName"}, - "absent": {"Entries[].EventBusName": "default"}}], + "default event bus is displayed'); EventBridge V2's request names its bus by " + "EventBusArn alone"), + "events:PutEvents": ([{"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, + {"type": "event-bus", "fill": {"EventBusName": "Entries[].EventBusName"}, + "absent": {"Entries[].EventBusName": "default"}, "endpoint": "events"}], "each entry goes to the event bus its EventBusName names, the default one when it names " "none ('If you omit this, the default event bus is used'), and publishing is authorized " "against the bus for every entry in the request; the rule reads no member of a list's " - "structures"), + "structures. EventBridge V2's request names by EventBusArn the one bus every entry goes to"), + "events:CreateEventBus": ([{"types": ["event-bus", "event-busv2"], "arn": "DeadLetterConfig.Arn", + "endpoint": "events"}, + {"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events"}, + {"type": "event-busv2", "fill": {"EventBusName": "Name"}, "endpoint": "eventsv2"}], + "EventBridge's request and EventBridge V2's both name the bus they create by Name, and " + "nothing a request gives tells them apart; the API serving it does, an event-bus " + "for EventBridge and an event-busv2, whose id V2 mints, for V2"), + **{f"events:{operation}": ([*extra, {"types": [v2], "arn": arn, "endpoint": "eventsv2"}, + {"type": v1, "fill": {variable: "Name"}, "endpoint": "events"}], + f"EventBridge's request names the {v1} by Name, EventBridge V2's by {arn}; the rule " + "fills a type's variables only when no member holds its ARN, so with both clients " + "read it drops EventBridge's Name") + for operation, v1, v2, variable, arn, extra in ( + ("DeleteEventBus", "event-bus", "event-busv2", "EventBusName", "EventBusArn", []), + ("UpdateEventBus", "event-bus", "event-busv2", "EventBusName", "EventBusArn", + [{"types": ["event-bus", "event-busv2"], "arn": "DeadLetterConfig.Arn", "endpoint": "events"}]), + ("DescribeEventSource", "event-source", "event-sourcev2", "EventSourceName", "EventSourceArn", []))}, **{f"states:{operation}": ([{"types": ["statemachine"], "arn": "stateMachineArn", "before": "#"}], "Floci takes Step Functions Local's # and runs the machine " "the part before the # names, so that part is the one checked") @@ -691,18 +715,20 @@ RESOURCE_PART_RE = re.compile(r"^arn:\$\{Partition}:[^:]*:[^:]*:[^:]*:([A-Za-z][ def with_made(resources: list[dict], operation: str, formats: dict[str, str]) -> list[dict]: """The resources, those a create makes marked `made` when it names others too (the pipeline a webhook connects to, the namespace a service is created in), so that its tags are checked on what it makes alone: of a type, or - with an ARN format's leading resource word, related to the operation's name past its verb.""" + with an ARN format's leading resource word, related to the operation's name past its verb. A member that may hold + an ARN of several types is made only when every one of them is: one that may name the parent too (a subscriber's + `EventBusArn`) names a resource the create does not make.""" name = operation.split(":", 1)[1] if not CREATING_RE.match(name): return resources created = stem(CREATING_RE.sub("", name)) + def is_created(kind: str) -> bool: + word = RESOURCE_PART_RE.match(formats.get(kind, "")) + return related(created, stem(kind)) or (word is not None and related(created, stem(word.group(1)))) + def makes(resource: dict) -> bool: - for kind in resource.get("types") or [resource.get("type")]: - word = RESOURCE_PART_RE.match(formats.get(kind, "")) - if related(created, stem(kind)) or (word is not None and related(created, stem(word.group(1)))): - return True - return False + return all(is_created(kind) for kind in resource.get("types") or [resource.get("type")]) made = [makes(resource) for resource in resources] if all(made) or not any(made): @@ -773,6 +799,11 @@ def entry_for(operation: str, upstream: dict, formats: dict[str, str], models: d members = request_members(models, operation.split(":", 1)[1]) if operation in CORRECTIONS: resources = CORRECTIONS[operation][0] + endpoints = {model["metadata"]["endpointPrefix"] for model in models.values()} + unknown = {resource["endpoint"] for resource in resources if "endpoint" in resource} - endpoints + if unknown: + raise ValueError(f"CORRECTIONS serves {operation} on {sorted(unknown)}, no endpoint prefix of the clients " + f"it reads ({sorted(endpoints)})") else: resources = with_found(resources_for(operation, types, formats, members), namespace_of(operation), members) resources = with_account(resources, formats, account_members(models, operation.split(":", 1)[1])) @@ -976,10 +1007,13 @@ def validate(document: dict) -> list[str]: def _resource_problems(operation: str, resource: object, types: set[str], formats: dict[str, str]) -> list[str]: - if not isinstance(resource, dict) or not ({"types", "arn"} <= set(resource) <= {"types", "arn", "before", "made"} + if not isinstance(resource, dict) or not ({"types", "arn"} <= set(resource) <= {"types", "arn", "before", "made", + "endpoint"} or {"type", "fill"} <= set(resource) <= {"type", "fill", "when", "unless", "absent", "arnOf", "account", - "fixed", "made", "before", "find"}): + "fixed", "made", "before", "find", "endpoint"}): return [f"{operation} names {resource!r}, which is neither an ARN member nor a type's variables"] + if "endpoint" in resource and not (isinstance(resource["endpoint"], str) and resource["endpoint"]): + return [f"{operation} serves {resource!r} on {resource['endpoint']!r}, which is no endpoint prefix"] if resource.get("made", True) is not True: return [f"{operation} marks {resource!r} made by {resource['made']!r}, which is not true"] before = resource.get("before", "#") diff --git a/tools/aws/test_regen_iam_request_resources.py b/tools/aws/test_regen_iam_request_resources.py index 722806039f..267825dda1 100644 --- a/tools/aws/test_regen_iam_request_resources.py +++ b/tools/aws/test_regen_iam_request_resources.py @@ -141,6 +141,9 @@ def test_a_create_naming_others_marks_what_it_makes(): assert r.with_made([classic, app], "svc:CreateLoadBalancer", formats) == [classic, app] assert r.with_made([pipeline], "svc:PutWebhook", formats) == [pipeline] assert r.with_made([webhook, pipeline], "svc:DescribeWebhook", formats) == [webhook, pipeline] + # A member that may hold the ARN of the parent too names no resource the create makes. + parent = {"types": ["pipeline", "webhook"], "arn": "PipelineArn"} + assert r.with_made([parent, webhook], "svc:PutWebhook", formats) == [parent, dict(webhook, made=True)] def test_stems_drop_the_suffixes_names_carry(): @@ -527,12 +530,34 @@ def test_the_vendored_file_is_well_formed(): {"type": "rule-on-custom-event-bus", "fill": {"EventBusName": "EventBusName", "RuleName": "Name"}, "unless": {"EventBusName": ["default"]}, "absent": {"EventBusName": "default"}, "arnOf": {"EventBusName": "event-bus"}}] assert operations["events:DescribeEventBus"]["resources"] == [ - {"type": "event-bus", "fill": {"EventBusName": "Name"}, "absent": {"Name": "default"}, "arnOf": {"Name": "event-bus"}}] - # Each PutEvents entry is on the bus it names, by name or ARN, or the default one when it names none. + {"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, + {"type": "event-bus", "fill": {"EventBusName": "Name"}, "absent": {"Name": "default"}, "endpoint": "events", + "arnOf": {"Name": "event-bus"}}] + # Each PutEvents entry is on the bus it names, by name or ARN, or the default one when it names none; an + # EventBridge V2 request is on the one bus its EventBusArn names. assert operations["events:PutEvents"]["resources"] == [ + {"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, {"type": "event-bus", "fill": {"EventBusName": "Entries[].EventBusName"}, - "absent": {"Entries[].EventBusName": "default"}, "arnOf": {"Entries[].EventBusName": "event-bus"}}] - assert document["namespaces"]["events"] == ["events"] and "eventbridgev2" in document["clientsNotRead"] + "absent": {"Entries[].EventBusName": "default"}, "endpoint": "events", + "arnOf": {"Entries[].EventBusName": "event-bus"}}] + # EventBridge V2 is read beside EventBridge, and where both name an operation's resources, which one applies is + # the endpoint serving the request, never a member a caller could add. + assert document["namespaces"]["events"] == ["eventbridgev2", "events"] + assert "eventbridgev2" not in document["clientsNotRead"] + assert operations["events:DeleteSubscriber"]["resources"] == [{"types": ["subscriber"], "arn": "SubscriberArn"}] + assert operations["events:DeleteEventBus"]["resources"] == [ + {"types": ["event-busv2"], "arn": "EventBusArn", "endpoint": "eventsv2"}, + {"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events"}] + assert operations["events:CreateEventBus"]["resources"][1:] == [ + {"type": "event-bus", "fill": {"EventBusName": "Name"}, "endpoint": "events", "made": True}, + {"type": "event-busv2", "fill": {"EventBusName": "Name"}, "endpoint": "eventsv2"}] + # A create's tags are checked on what it makes: not a dead-letter target or the bus a subscriber is made on. + assert "made" not in operations["events:CreateEventBus"]["resources"][0] + assert [resource for resource in operations["events:CreateSubscriber"]["resources"] if resource.get("made")] == [ + {"type": "subscriber", "fill": {"SubscriberName": "Name"}, "made": True}] + assert not any("when" in resource or "unless" in resource + for operation, entry in operations.items() if operation.startswith("events:") + and "endpoint" in json.dumps(entry) for resource in entry["resources"]) # A state machine's version or alias is checked on the state machine. assert document["unqualified"] == {"states": ["statemachine"]} # A listener is made under a load balancer, and a rule under a listener. diff --git a/tools/docs/service_matrix.yaml b/tools/docs/service_matrix.yaml index 93dfba544e..d50ab1a3a9 100644 --- a/tools/docs/service_matrix.yaml +++ b/tools/docs/service_matrix.yaml @@ -28,6 +28,7 @@ aliases: sso: ssoadmin # descriptor("sso") is the Identity Center admin API; ssoadmin.md is its page sso-oidc: ssooidc # IAM Identity Center OIDC REST API events: eventbridge + eventsv2: eventbridgev2 # EventBridge V2's endpoint prefix is "eventsv2" servicediscovery: cloudmap # Cloud Map's SigV4 signing name elasticmapreduce: emr # EMR's SigV4 signing name logs: cloudwatch # CloudWatch Logs facet, at cloudwatch.md diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml index f56bdee593..9586953b95 100644 --- a/tools/docs/services.yaml +++ b/tools/docs/services.yaml @@ -237,6 +237,10 @@ services: doc: docs/services/eventbridge.md sources: - { path: services/eventbridge/EventBridgeHandler.java, mode: switch } + - service: eventbridgev2 + doc: docs/services/eventbridgev2.md + sources: + - { path: services/eventbridgev2/EventBridgeV2Handler.java, mode: switch } - service: firehose doc: docs/services/firehose.md sources: