fix(eventbridge): match numeric comparison patterns (#7695) (#7700)

Add numeric comparisons to the shared matcher used by TestEventPattern and PutEvents. Validate all numeric filters before testing events or mutating rules, including nested patterns and every $or branch. Match numeric and literal filters against event array elements without splitting range bounds across different values.

Add service and AWS SDK success/error regressions.

Validation: 293 focused tests pass; zero Checkstyle violations.

Fixes #7695

The validator accepted arbitrary operator/number pairs, allowing repeated bounds, equality mixed with bounds, and unordered ranges. Restrict filters to a single comparison or a lower bound followed by a strictly greater upper bound.

Add SDK rejection and rule-preservation regressions and valid range boundary controls. All 386 focused tests, Checkstyle, docs-check, and partition-check pass.

Keep the new range boundary cases aligned with the surrounding parameter tables. This also requests fresh CI checks on the verified PR history.

Use one testing fixture for valid comparisons and invalid patterns in both the service and SDK suites. Preserve the union of existing cases, including nested and matching alternative branches, so both layers exercise the same matrix.

Validation: 402 focused EventBridge tests pass with no skips and zero Checkstyle violations.

Expose PipesFilterMatcher.matchesNumeric and use it from EventBridge instead of maintaining a second comparison loop. Retain the null and numeric-form guards.

Use AwsTestClients.create directly in the EventBridge SDK tests and remove the custom SDK client builder and injected endpoint.

Validation: all 463 EventBridge service, EventBridge SDK, and Pipes matcher tests pass, with no skips and zero Checkstyle violations.
This commit is contained in:
jwoa95 authored and GitHub committed 2026-11-10 09:08:43 -04:00
1 parent 09ac552cf7
commit 9c989d7457
6 files changed
+348 -7

No files matched your search

+23
View File
@@ -54,6 +54,29 @@
characters. Empty or overlong tokens return `ValidationException`; unrecognized
cursors within those bounds return `InvalidToken`.
## Numeric event patterns
`TestEventPattern` and `PutEvents` rule routing support `numeric` comparisons on
JSON number fields using `=`, `>`, `>=`, `<`, and `<=`. Both bounds of a range
must match. For example,
`{"detail":{"severity":[{"numeric":[">=",7,"<",9]}]}}` matches severity `7` or `8`,
but excludes `6`, `9`, the string `"7"`, and missing or null values.
For array-valued fields, a numeric filter matches when at least one number in the
array satisfies all comparisons. The range above matches `[3,8]` but excludes
`[3,9]`; separate elements cannot satisfy separate bounds of the same range.
`PutRule` and `TestEventPattern` reject malformed numeric filters with
`InvalidEventPatternException` (HTTP 400), independently of the supplied event.
The comparison array must contain either one operator/number pair or a lower bound
(`>` or `>=`) followed by an upper bound (`<` or `<=`). Equality (`=`) must stand
alone. Range endpoints must be strictly increasing, even when both bounds are
inclusive. Repeated bounds, reversed bounds, and extra comparisons are rejected.
Nested patterns and every `$or` branch are validated before a rule is saved;
rejected updates preserve the existing rule.
See [AWS numeric matching](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-pattern-operators.html#filtering-numeric-matching).
## Configuration
| Variable | Default | Description |
@@ -40,6 +40,7 @@ import io.floci.aws.services.eventbridge.model.ReplayState;
import io.floci.aws.services.eventbridge.model.Rule;
import io.floci.aws.services.eventbridge.model.RuleState;
import io.floci.aws.services.eventbridge.model.Target;
import io.floci.aws.services.pipes.PipesFilterMatcher;
import io.floci.aws.services.resourcegroupstagging.ResourceGroupsTaggingService;
import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
@@ -69,6 +70,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
private static final Logger LOG = Logger.getLogger(EventBridgeService.class);
private static final int MAX_LIST_LIMIT = 100;
private static final List<String> REQUIRED_ENTRY_FIELDS = List.of("Source", "DetailType", "Detail");
private static final Set<String> NUMERIC_OPERATORS = Set.of("=", ">", ">=", "<", "<=");
private final StorageBackend<String, EventBus> busStore;
private final StorageBackend<String, Rule> ruleStore;
@@ -357,6 +359,9 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
throw new AwsException("ValidationException",
"Parameter(s) EventPattern or ScheduleExpression must be specified.", 400);
}
if (eventPattern != null && !eventPattern.isBlank()) {
validateEventPattern(eventPattern);
}
String effectiveBus = resolvedBusName(busName);
ensureBusExists(effectiveBus, region);
@@ -1130,12 +1135,7 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
if (eventJson == null || eventJson.isBlank()) {
throw new AwsException("InvalidEventPatternException", "Event is required.", 400);
}
try {
objectMapper.readTree(eventPattern);
} catch (Exception e) {
throw new AwsException("InvalidEventPatternException",
"Event pattern is not valid JSON: " + e.getMessage(), 400);
}
validateEventPattern(eventPattern);
JsonNode event;
try {
event = objectMapper.readTree(eventJson);
@@ -1170,6 +1170,43 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
return matchesPattern(entry, eventPattern);
}
private void validateEventPattern(String eventPattern) {
JsonNode pattern;
try {
pattern = objectMapper.readTree(eventPattern);
} catch (JsonProcessingException e) {
throw new AwsException("InvalidEventPatternException",
"Event pattern is not valid JSON: " + e.getMessage(), 400);
}
if (pattern == null || !pattern.isObject()) {
throw new AwsException("InvalidEventPatternException", "Event pattern must be a JSON object.", 400);
}
validateNumericPatterns(pattern);
}
private void validateNumericPatterns(JsonNode pattern) {
Iterator<Map.Entry<String, JsonNode>> fields = pattern.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
JsonNode expected = field.getValue();
if ("$or".equals(field.getKey()) && expected.isArray()) {
for (JsonNode branch : expected) {
validateNumericPatterns(branch);
}
} else if (expected.isObject()) {
validateNumericPatterns(expected);
} else if (expected.isArray()) {
for (JsonNode filter : expected) {
if (filter.isObject() && filter.has("numeric") && !isValidNumericFilter(filter.get("numeric"))) {
throw new AwsException("InvalidEventPatternException",
"numeric must contain one comparison or a lower bound followed by an upper bound"
+ " with a strictly greater endpoint.", 400);
}
}
}
}
}
boolean matchesPattern(Map<String, Object> event, String eventPattern) {
if (eventPattern == null || eventPattern.isBlank()) {
return true;
@@ -1319,6 +1356,14 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
}
private boolean matchesArrayField(JsonNode arrayNode, JsonNode actual) {
if (actual != null && actual.isArray()) {
for (JsonNode value : actual) {
if (matchesArrayField(arrayNode, value)) {
return true;
}
}
return false;
}
for (JsonNode element : arrayNode) {
if (matchesSingleElement(element, actual)) {
return true;
@@ -1340,6 +1385,11 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
if (element.has("equals-ignore-case")) {
return value != null && value.equalsIgnoreCase(element.get("equals-ignore-case").asText());
}
if (element.has("numeric")) {
JsonNode comparisons = element.get("numeric");
return actual != null && isValidNumericFilter(comparisons)
&& PipesFilterMatcher.matchesNumeric(comparisons, actual);
}
if (element.has("anything-but")) {
JsonNode anythingBut = element.get("anything-but");
if (anythingBut.isValueNode()) {
@@ -1368,6 +1418,27 @@ public class EventBridgeService implements ResourceProvider, StoredResourceArns
return matchesExactValue(element, actual);
}
private boolean isValidNumericFilter(JsonNode comparisons) {
if (!comparisons.isArray() || (comparisons.size() != 2 && comparisons.size() != 4)) {
return false;
}
for (int i = 0; i < comparisons.size(); i += 2) {
JsonNode operator = comparisons.get(i);
if (!operator.isTextual() || !NUMERIC_OPERATORS.contains(operator.textValue())
|| !comparisons.get(i + 1).isNumber()) {
return false;
}
}
if (comparisons.size() == 2) {
return true;
}
String lowerOperator = comparisons.get(0).textValue();
String upperOperator = comparisons.get(2).textValue();
return (">".equals(lowerOperator) || ">=".equals(lowerOperator))
&& ("<".equals(upperOperator) || "<=".equals(upperOperator))
&& comparisons.get(1).decimalValue().compareTo(comparisons.get(3).decimalValue()) < 0;
}
private boolean matchesExactValue(JsonNode expected, JsonNode actual) {
if (expected.isNull()) {
return actual != null && actual.isNull();
@@ -259,7 +259,7 @@ public class PipesFilterMatcher {
return prefix ? text.startsWith(affix.asText()) : text.endsWith(affix.asText());
}
private static boolean matchesNumeric(JsonNode conditions, JsonNode value) {
public static boolean matchesNumeric(JsonNode conditions, JsonNode value) {
if (!conditions.isArray() || conditions.isEmpty() || conditions.size() % 2 != 0) {
throw new IllegalArgumentException("numeric takes pairs of a comparison and a number");
}
@@ -989,6 +989,99 @@ class EventBridgeServiceTest {
assertFalse(service.matchesPattern(event, "{\"detail\":{\"status\":[\"PENDING\"]}}"));
}
@Test
void matchesPatternByNumericSeverity() {
Map<String, Object> event = Map.of("Detail", "{\"severity\":7}");
assertTrue(service.matchesPattern(event, "{\"detail\":{\"severity\":[7]}}"));
assertTrue(service.matchesPattern(event, "{\"detail\":{\"severity\":[{\"numeric\":[\">=\",7]}]}}"));
assertTrue(service.matchesPattern(event, "{\"detail\":{\"severity\":[{\"numeric\":[\">=\",6]}]}}"));
}
@ParameterizedTest
@MethodSource("io.floci.aws.testing.EventBridgeNumericPatterns#cases")
void matchesPatternByNumericComparison(String value, String comparisons, boolean expected) {
Map<String, Object> event = Map.of("Detail", "{\"value\":" + value + "}");
String pattern = "{\"detail\":{\"value\":[{\"numeric\":[" + comparisons + "]}]}}";
assertEquals(expected, service.matchesPattern(event, pattern));
assertEquals(expected, service.testEventPattern(pattern, "{\"detail\":{\"value\":" + value + "}}"));
service.putRule("valid-numeric", null, pattern, null, RuleState.ENABLED, null, null, null, REGION);
assertEquals(pattern, service.describeRule("valid-numeric", null, REGION).getEventPattern());
}
@ParameterizedTest
@MethodSource("io.floci.aws.testing.EventBridgeNumericPatterns#invalidPatterns")
void malformedNumericComparisonIsRejectedByPublicApis(String pattern) {
for (String detail : List.of("{\"severity\":7}", "{\"severity\":\"7\"}", "{}")) {
AwsException error = assertThrows(AwsException.class,
() -> service.testEventPattern(pattern, "{\"source\":\"example.test\",\"detail\":" + detail + "}"));
assertEquals("InvalidEventPatternException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
}
AwsException error = assertThrows(AwsException.class, () -> service.putRule(
"invalid-numeric", null, pattern, null, RuleState.ENABLED, null, null, null, REGION));
assertEquals("InvalidEventPatternException", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertTrue(service.listRules(null, null, REGION).isEmpty());
}
@Test
void invalidNumericUpdateDoesNotMutateExistingRule() {
String original = "{\"detail\":{\"value\":[7]}}";
service.putRule("existing", null, original, null, RuleState.ENABLED, null, null, null, REGION);
assertThrows(AwsException.class, () -> service.putRule("existing", null,
"{\"detail\":{\"value\":[{\"numeric\":[]}]}}", null,
RuleState.ENABLED, null, null, null, REGION));
assertEquals(original, service.describeRule("existing", null, REGION).getEventPattern());
}
@Test
void numericFieldNameIsNotConfusedWithNumericOperator() {
assertTrue(service.testEventPattern("{\"detail\":{\"numeric\":[7]}}", "{\"detail\":{\"numeric\":7}}"));
}
@Test
void exactLiteralsMatchArrayElements() {
assertTrue(service.testEventPattern("{\"detail\":{\"value\":[7]}}", "{\"detail\":{\"value\":[3,7]}}"));
assertFalse(service.testEventPattern("{\"detail\":{\"value\":[7]}}", "{\"detail\":{\"value\":[3,6]}}"));
}
@Test
void numericComparisonDoesNotMatchMissingField() {
assertFalse(service.matchesPattern(Map.of("Detail", "{}"),
"{\"detail\":{\"value\":[{\"numeric\":[\">=\",0]}]}}"));
}
@Test
void numericComparisonsCanBeAlternativesToLiterals() {
String pattern = "{\"detail\":{\"value\":[{\"numeric\":[\"<\",0]},\"unknown\",{\"numeric\":[\">=\",7]}]}}";
assertTrue(service.matchesPattern(Map.of("Detail", "{\"value\":-1}"), pattern));
assertTrue(service.matchesPattern(Map.of("Detail", "{\"value\":\"unknown\"}"), pattern));
assertTrue(service.matchesPattern(Map.of("Detail", "{\"value\":7}"), pattern));
assertFalse(service.matchesPattern(Map.of("Detail", "{\"value\":3}"), pattern));
}
@ParameterizedTest
@ValueSource(ints = {6, 7, 8})
void putEventsDispatchesOnlyWhenNumericSeverityMatches(int severity) {
Rule rule = service.putRule("severity-rule", null,
"{\"detail\":{\"severity\":[{\"numeric\":[\">=\",7]}]}}", null,
RuleState.ENABLED, null, null, null, REGION);
Target target = new Target("t1", "arn:aws:sns:us-east-1:000000000000:alerts", null, null);
service.putTargets("severity-rule", null, List.of(target), REGION);
EventBridgeService.PutEventsResult result = service.putEvents(List.of(Map.of(
"Source", "example.test", "DetailType", "Example", "Detail", "{\"severity\":" + severity + "}")), REGION);
assertEquals(0, result.failedCount());
verify(dispatcherMock, Mockito.times(severity >= 7 ? 1 : 0))
.dispatch(eq(rule.getArn()), eq(target), anyString(), eq(REGION), any());
}
@Test
void matchesPatternByResources() {
Map<String, Object> event = Map.of(
@@ -1,12 +1,22 @@
package io.floci.aws.services.eventbridge;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.eventbridge.EventBridgeClient;
import software.amazon.awssdk.services.eventbridge.model.InvalidEventPatternException;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@QuarkusTest
class EventBridgeTestEventPatternIntegrationTest {
@@ -19,6 +29,71 @@ class EventBridgeTestEventPatternIntegrationTest {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@ParameterizedTest
@MethodSource("io.floci.aws.testing.EventBridgeNumericPatterns#cases")
void numericComparisonThroughSdk(String value, String comparisons, boolean expected) {
try (EventBridgeClient client = AwsTestClients.create(EventBridgeClient.builder(), "test", Region.EU_WEST_2)) {
String event = """
{"version":"0","id":"numeric-test","detail-type":"Example","source":"example.test",
"account":"000000000000","time":"2026-11-06T00:00:00Z","region":"eu-west-2",
"resources":[],"detail":{"severity":%s}}
""".formatted(value);
String pattern = "{\"detail\":{\"severity\":[{\"numeric\":[" + comparisons + "]}]}}";
assertEquals(expected, client.testEventPattern(request -> request
.eventPattern(pattern).event(event)).result());
String name = "valid-numeric-pattern";
client.putRule(request -> request.name(name).eventPattern(pattern));
try {
assertEquals(pattern, client.describeRule(request -> request.name(name)).eventPattern());
} finally {
client.deleteRule(request -> request.name(name));
}
}
}
@ParameterizedTest
@MethodSource("io.floci.aws.testing.EventBridgeNumericPatterns#invalidPatterns")
void invalidNumericPatternsRaiseSdkErrors(String pattern) {
try (EventBridgeClient client = AwsTestClients.create(EventBridgeClient.builder(), "test", Region.EU_WEST_2)) {
for (String detail : List.of("{\"severity\":7}", "{\"severity\":\"7\"}", "{}")) {
String event = """
{"version":"0","id":"numeric-test","detail-type":"Example","source":"example.test",
"account":"000000000000","time":"2026-11-06T00:00:00Z","region":"eu-west-2",
"resources":[],"detail":%s}
""".formatted(detail);
InvalidEventPatternException error = assertThrows(InvalidEventPatternException.class,
() -> client.testEventPattern(request -> request.eventPattern(pattern).event(event)));
assertEquals(400, error.statusCode());
assertEquals("InvalidEventPatternException", error.awsErrorDetails().errorCode());
}
InvalidEventPatternException error = assertThrows(InvalidEventPatternException.class,
() -> client.putRule(request -> request.name("invalid-numeric-pattern").eventPattern(pattern)));
assertEquals(400, error.statusCode());
assertEquals("InvalidEventPatternException", error.awsErrorDetails().errorCode());
}
}
@ParameterizedTest
@MethodSource("io.floci.aws.testing.EventBridgeNumericPatterns#invalidPatterns")
void invalidNumericUpdatePreservesExistingRuleThroughSdk(String pattern) {
try (EventBridgeClient client = AwsTestClients.create(EventBridgeClient.builder(), "test", Region.EU_WEST_2)) {
String name = "numeric-update-preservation";
String original = "{\"detail\":{\"severity\":[7]}}";
client.putRule(request -> request.name(name).eventPattern(original).description("original"));
try {
InvalidEventPatternException error = assertThrows(InvalidEventPatternException.class,
() -> client.putRule(request -> request.name(name).eventPattern(pattern).description("changed")));
assertEquals(400, error.statusCode());
assertEquals("InvalidEventPatternException", error.awsErrorDetails().errorCode());
assertEquals(original, client.describeRule(request -> request.name(name)).eventPattern());
assertEquals("original", client.describeRule(request -> request.name(name)).description());
} finally {
client.deleteRule(request -> request.name(name));
}
}
}
@Test
void sourceMatch() {
given()
@@ -0,0 +1,79 @@
package io.floci.aws.testing;
import org.junit.jupiter.params.provider.Arguments;
import java.util.stream.Stream;
/** Numeric pattern cases shared by the EventBridge service and SDK tests. */
public final class EventBridgeNumericPatterns {
private EventBridgeNumericPatterns() {
}
public static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("7", "\">=\",7", true),
Arguments.of("7", "\">=\",6", true),
Arguments.of("6", "\">=\",7", false),
Arguments.of("7", "\">\",7", false),
Arguments.of("8", "\">\",7", true),
Arguments.of("6", "\"<\",7", true),
Arguments.of("7", "\"<\",7", false),
Arguments.of("7", "\"<=\",7", true),
Arguments.of("8", "\"<=\",7", false),
Arguments.of("7.0", "\"=\",7", true),
Arguments.of("3.018e2", "\"=\",301.8", true),
Arguments.of("7", "\"=\",8", false),
Arguments.of("-2.5", "\">\",-3,\"<=\",0", true),
Arguments.of("0", "\">\",-3,\"<=\",0", true),
Arguments.of("-3", "\">\",-3,\"<=\",0", false),
Arguments.of("1", "\">\",-3,\"<=\",0", false),
Arguments.of("-0.0", "\"=\",0", true),
Arguments.of("\"7\"", "\">=\",7", false),
Arguments.of("true", "\">=\",0", false),
Arguments.of("null", "\">=\",0", false),
Arguments.of("{}", "\">=\",0", false),
Arguments.of("[3,7]", "\">=\",7", true),
Arguments.of("[3,6]", "\">=\",7", false),
Arguments.of("[3,9]", "\">=\",7,\"<\",9", false),
Arguments.of("[3,8]", "\">=\",7,\"<\",9", true),
Arguments.of("[\"7\"]", "\">=\",7", false),
Arguments.of("[]", "\">=\",7", false),
Arguments.of("6", "\">\",6,\"<\",8", false),
Arguments.of("7", "\">\",6,\"<\",8", true),
Arguments.of("8", "\">\",6,\"<\",8", false),
Arguments.of("6", "\">\",6,\"<=\",8", false),
Arguments.of("7", "\">\",6,\"<=\",8", true),
Arguments.of("8", "\">\",6,\"<=\",8", true),
Arguments.of("6", "\">=\",6,\"<\",8", true),
Arguments.of("7", "\">=\",6,\"<\",8", true),
Arguments.of("8", "\">=\",6,\"<\",8", false),
Arguments.of("6", "\">=\",6,\"<=\",8", true),
Arguments.of("7", "\">=\",6,\"<=\",8", true),
Arguments.of("8", "\">=\",6,\"<=\",8", true),
Arguments.of("8", "\"<\",7", false),
Arguments.of("301.8", "\"=\",3.018e2", true),
Arguments.of("7", "\">\",6,\"<=\",7", true),
Arguments.of("8", "\">\",6,\"<=\",7", false));
}
public static Stream<String> invalidPatterns() {
Stream<String> invalidFilters = Stream.of("null", "7", "{}", "[]", "[\">=\"]", "[\">=\",7,\"<\"]",
"[\"!=\",7]", "[7,7]", "[\">=\",\"7\"]", "[\">=\",null]", "[\">=\",true]",
"[\">\",0,\">\",1]", "[\">=\",0,\">\",1]",
"[\">\",0,\">=\",1]", "[\">=\",0,\">=\",1]",
"[\"<\",9,\"<\",7]", "[\"<=\",9,\"<=\",7]",
"[\"=\",7,\">\",6]", "[\">\",6,\"=\",7]",
"[\"=\",7,\"=\",7]", "[\"<\",9,\">\",7]",
"[\"<=\",9,\">=\",7]", "[\">\",9,\"<\",7]",
"[\">=\",9,\"<=\",7]", "[\">\",7,\"<\",7]",
"[\">\",7,\"<=\",7]", "[\">=\",7,\"<\",7]",
"[\">=\",7,\"<=\",7]", "[\">\",0,\"<\",9,\"<\",8]")
.map(filter -> "{\"detail\":{\"severity\":[{\"numeric\":" + filter + "}]}}");
return Stream.concat(invalidFilters, Stream.of(
"{\"detail\":{\"nested\":{\"severity\":[{\"numeric\":[]}]}}}",
"{\"$or\":[{\"source\":[\"example.test\"]},{\"detail\":{\"severity\":[{\"numeric\":[]}]}}]}",
"{\"detail\":{\"$or\":[{\"severity\":[7]},{\"severity\":[{\"numeric\":[]}] }]}}",
"{\"detail\":{\"severity\":[7,{\"numeric\":[]}]}}"));
}
}