feat(eventbridgev2): add EventBridge V2 service (#6962)

This commit is contained in:
Ruslan Sovinskyy authored and GitHub committed 2026-11-01 18:44:29 -04:00
1 parent 5680ec4b8f
commit dfaab8ba4c
47 files changed
+4283 -217

No files matched your search

@@ -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.
@@ -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"));
@@ -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) {
@@ -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<String> 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);
}
@@ -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));
@@ -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<String> 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);
}
}
@@ -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<EventBusV2> 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<EventBusV2> 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<SubscriberV2> first = service.listSubscribers(json("{\"EventBusArn\":\"" + orders
+ "\",\"NamePrefix\":\"orders\",\"MaxResults\":1}"), REGION);
assertEquals(List.of("orders-a"), first.items().stream().map(SubscriberV2::getName).toList());
PaginatedResult<SubscriberV2> 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<EventBridgeV2Service.PutEventsResult> 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<SubscriberV2> delivered = ArgumentCaptor.forClass(SubscriberV2.class);
ArgumentCaptor<PublishedEvent> 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<EventBridgeV2Service.PutEventsResult> 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<EventBridgeV2Service.PutEventsResult> 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<Long> 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<Future<?>> 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<Long> 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);
}
}
}
@@ -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<Message> 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<Message> 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<Message> 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<Message> 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);
}
}
@@ -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 %}"));
}
}
@@ -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);
}
}
}
@@ -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<String, Object> 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<String, Object> 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<String, ?> 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 + "\"}")
@@ -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 {
@@ -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 ────────────
@@ -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);
}
}
@@ -741,7 +741,7 @@ class PipesPollerTest {
},
"FilterCriteria": {
"Filters": [
{"Pattern": "{\\\"key\\\": [{\\\"exists\\\": false}]}"}
{"Pattern": "{\\\"key\\\": [null]}"}
]
}
}