diff --git a/docs/services/eventbridge.md b/docs/services/eventbridge.md index 015f955e97..cc8c140d27 100644 --- a/docs/services/eventbridge.md +++ b/docs/services/eventbridge.md @@ -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 | diff --git a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java index 40d1015897..a5bc393e16 100644 --- a/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/floci/aws/services/eventbridge/EventBridgeService.java @@ -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 REQUIRED_ENTRY_FIELDS = List.of("Source", "DetailType", "Detail"); + private static final Set NUMERIC_OPERATORS = Set.of("=", ">", ">=", "<", "<="); private final StorageBackend busStore; private final StorageBackend 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> fields = pattern.fields(); + while (fields.hasNext()) { + Map.Entry 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 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(); diff --git a/src/main/java/io/floci/aws/services/pipes/PipesFilterMatcher.java b/src/main/java/io/floci/aws/services/pipes/PipesFilterMatcher.java index 2e83caf1a8..98cf4aa9da 100644 --- a/src/main/java/io/floci/aws/services/pipes/PipesFilterMatcher.java +++ b/src/main/java/io/floci/aws/services/pipes/PipesFilterMatcher.java @@ -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"); } diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java index 191cd47e4a..b54e7b92e7 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeServiceTest.java @@ -989,6 +989,99 @@ class EventBridgeServiceTest { assertFalse(service.matchesPattern(event, "{\"detail\":{\"status\":[\"PENDING\"]}}")); } + @Test + void matchesPatternByNumericSeverity() { + Map 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 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 event = Map.of( diff --git a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTestEventPatternIntegrationTest.java b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTestEventPatternIntegrationTest.java index 14d45fb50f..04aee1137d 100644 --- a/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTestEventPatternIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/eventbridge/EventBridgeTestEventPatternIntegrationTest.java @@ -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() diff --git a/src/test/java/io/floci/aws/testing/EventBridgeNumericPatterns.java b/src/test/java/io/floci/aws/testing/EventBridgeNumericPatterns.java new file mode 100644 index 0000000000..43704f7f60 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/EventBridgeNumericPatterns.java @@ -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 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 invalidPatterns() { + Stream 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\":[]}]}}")); + } +}