From c576d3341b92aa5931b98e61cc327acf71f09cd9 Mon Sep 17 00:00:00 2001 From: Kenshin Okinaka Date: Thu, 4 Jun 2026 12:02:05 +0900 Subject: [PATCH] fix(eventbridge): propagate PutEvents call region and account through pattern matching and delivered envelope (#1125) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(eventbridge): propagate PutEvents call region and account through pattern matching and delivered envelope EventBridgeService.putEvents previously had two related defects in how the call's region and account flowed through to rule matching and the delivered EventBridge envelope: 1. buildEventEnvelope hardcoded the envelope's "region" and "account" fields to RegionResolver.getDefaultRegion() / RegionResolver.getAccountId(), regardless of which region/account the PutEvents call was made against. A rule scoped to eu-west-1 would fire correctly for an eu-west-1 PutEvents call (rules are stored per (region, bus)), but the envelope delivered to its target would report region=us-east-1. Downstream consumers / re-routing rules that filter on the envelope region saw an incorrect value. 2. matchesPattern read entry.Region / entry.Account with a fallback to the RegionResolver defaults. For a PutEvents entry without explicit Region (the common case — the AWS SDK doesn't model per-entry region), the pattern's region/account filter saw the resolver default while the envelope (after fix #1) saw the actual call region. Same kind of inconsistency, one step earlier. - putEvents() now defensively copies each entry into a mutable HashMap and fills missing/blank Region / Account from the call context (region argument; accountId if non-null else regionResolver.getAccountId()) at the top of the per-entry loop. matchesPattern, buildEventEnvelope, and captureToArchives all subsequently see the same normalized entry, so a pattern's region/account filter agrees with the delivered envelope. - buildEventEnvelope now takes the PutEvents call's region and accountId and resolves region/account with the same precedence: entry-supplied value wins (cross-region producers, archive replay), then the call's region/accountId, finally the resolver default. For the putEvents path the entry is already normalized, so this is defense-in-depth for any other callers. - A small isBlank(Object) helper centralizes the null + blank-string predicate used in both the entry normalization and the envelope fallback. Tests - Five new EventBridgeServiceTest cases pin the new behavior: * envelope.region equals the PutEvents call's region for a non-default-region rule+target+entry triple (eu-west-1). * entry.Region / entry.Account win when set explicitly (mirrors the archive-replay scenario where the originating envelope's region/account are stamped back onto the re-emitted entry). * default-region call still stamps the resolver default — regression pin so the pre-fix behavior isn't silently restored. * a region-filtered rule for the call region fires on a PutEvents call to that region with no explicit entry.Region (matchesPattern + envelope agree). * a region-filtered rule for the resolver default does NOT fire under a non-default-region PutEvents call — pre-fix this accidentally matched via the resolver default. - All 173 EventBridge tests pass. * fix(eventbridge): default to RegionResolver when normalizing a missing PutEvents region Address okinaka's review on the envelope-region fix: the Region branch of the entry normalization passed the raw `region` argument straight through, so a null/blank `region` would stamp `entry.Region = null`. The matching Account branch already fell back to `regionResolver.getAccountId()` when accountId was null, so the two branches were asymmetric. Apply the same fallback chain to Region — `entry.Region = isBlank(region) ? regionResolver.getDefaultRegion() : region` — and tighten Account's null check to `isBlank(accountId)` for symmetry. No new test: every real caller of EventBridgeService.putEvents (EventBridgeHandler, ScheduleInvoker, PipesTargetInvoker, S3Service) passes a non-null region, and the surrounding bus/rule-prefix lookups also use the raw `region` argument, so a null `region` would short- circuit at the bus lookup before the normalization invariant matters. This is a consistency fix for the in-loop normalization itself; the "normalize once at the top, downstream sees a stable value" invariant Copilot's review established now holds for Region the same way it holds for Account. * style(eventbridge): keep envelope region/account fallback ternaries on one line Match the formatting of the new entry-normalization fallbacks (entry.put("Region", isBlank(region) ? ... : region) — single line) by joining the envelope ternaries that the previous commits left wrapped at the question mark. Same code, just consistent layout. --- .../eventbridge/EventBridgeService.java | 44 ++++++- .../eventbridge/EventBridgeServiceTest.java | 123 ++++++++++++++++++ 2 files changed, 162 insertions(+), 5 deletions(-) diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java index 1a903e6999..522571b8e4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java @@ -618,7 +618,22 @@ public class EventBridgeService { int failed = 0; List> resultEntries = new ArrayList<>(); - for (Map entry : entries) { + for (Map originalEntry : entries) { + // Defensive copy: callers may pass Map.of(...) (immutable) and we don't want to + // mutate caller state regardless. Normalize Region / Account from the PutEvents + // call context up front so matchesPattern, buildEventEnvelope, and the archive + // capture all see the same values — without this, a pattern's region/account + // filter would fall back to the resolver default in matchesPattern while the + // delivered envelope would correctly carry the call's region/account, giving an + // inconsistent observable. + Map entry = new HashMap<>(originalEntry); + if (isBlank(entry.get("Region"))) { + entry.put("Region", isBlank(region) ? regionResolver.getDefaultRegion() : region); + } + if (isBlank(entry.get("Account"))) { + entry.put("Account", isBlank(accountId) ? regionResolver.getAccountId() : accountId); + } + String eventBusNameRaw = (String) entry.get("EventBusName"); String effectiveBus = resolvedBusName(eventBusNameRaw); String busStoreKey = busKey(region, effectiveBus); @@ -645,7 +660,7 @@ public class EventBridgeService { if (matchesPattern(entry, rule.getEventPattern())) { String ruleKey = ruleKey(region, effectiveBus, rule.getName()); List targets = accountGet(targetStore, accountId, ruleKey).orElse(List.of()); - String eventJson = buildEventEnvelope(entry, effectiveBus, eventId); + String eventJson = buildEventEnvelope(entry, effectiveBus, eventId, region, accountId); for (Target target : targets) { invoker.invokeTarget(target, eventJson, region); } @@ -900,20 +915,35 @@ public class EventBridgeService { // ──────────────────────────── Target Routing ──────────────────────────── - private String buildEventEnvelope(Map entry, String busName, String eventId) { + private String buildEventEnvelope(Map entry, String busName, String eventId, + String callRegion, String callAccountId) { try { String source = (String) entry.getOrDefault("Source", ""); String detailType = (String) entry.getOrDefault("DetailType", ""); String detail = (String) entry.getOrDefault("Detail", "{}"); ArrayNode resources = (ArrayNode) entry.getOrDefault("Resources", objectMapper.createArrayNode()); + // Envelope region/account precedence: entry-supplied "Region"/"Account" (set by + // archive replay paths and cross-region producers) wins; otherwise stamp the + // region/account the PutEvents call was made against. Only when neither is + // available do we fall back to the RegionResolver defaults. This keeps the + // envelope consistent with matchesPattern() which also reads entry.Region with + // the same fallback chain. + String envelopeRegion = (String) entry.get("Region"); + if (isBlank(envelopeRegion)) { + envelopeRegion = isBlank(callRegion) ? regionResolver.getDefaultRegion() : callRegion; + } + String envelopeAccount = (String) entry.get("Account"); + if (isBlank(envelopeAccount)) { + envelopeAccount = isBlank(callAccountId) ? regionResolver.getAccountId() : callAccountId; + } ObjectNode node = objectMapper.createObjectNode(); node.put("version", "0"); node.put("id", eventId); node.put("source", source); node.put("detail-type", detailType); - node.put("account", regionResolver.getAccountId()); + node.put("account", envelopeAccount); node.put("time", Instant.now().toString()); - node.put("region", regionResolver.getDefaultRegion()); + node.put("region", envelopeRegion); node.putArray("resources").addAll(resources); node.set("detail", objectMapper.readTree(detail)); node.put("event-bus-name", busName); @@ -941,6 +971,10 @@ public class EventBridgeService { "EventBus not found: " + busName, 404)); } + private static boolean isBlank(Object value) { + return !(value instanceof String s) || s.isBlank(); + } + private static String resolvedBusName(String busName) { if (busName == null || busName.isBlank()) { return "default"; diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java index bda1af8b42..c057a9f3b0 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java @@ -618,4 +618,127 @@ class EventBridgeServiceTest { assertFalse(service.matchesPattern(event, "{\"source\":[\"my.app\"],\"account\":[\"999999999999\"],\"detail\":{\"status\":[\"CONFIRMED\"]}}")); } + + // ─────────────── Envelope region/account propagation ─────────────── + + @Test + void putEvents_envelopeRegionMatchesPutEventsCallRegion() throws Exception { + service.putRule("my-rule", null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED, + "A test rule", null, null, "eu-west-1"); + Target target = new Target(); + target.setId("t1"); + target.setArn("arn:aws:sqs:eu-west-1:000000000000:my-queue"); + service.putTargets("my-rule", null, List.of(target), "eu-west-1"); + + List> entries = List.of( + Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}") + ); + + EventBridgeService.PutEventsResult result = service.putEvents(entries, "eu-west-1"); + assertEquals(0, result.failedCount()); + + org.mockito.ArgumentCaptor json = org.mockito.ArgumentCaptor.forClass(String.class); + verify(invokerMock).invokeTarget(eq(target), json.capture(), eq("eu-west-1")); + com.fasterxml.jackson.databind.JsonNode envelope = OBJECT_MAPPER.readTree(json.getValue()); + assertEquals("eu-west-1", envelope.path("region").asText(), + "envelope.region should reflect the PutEvents call's region, not the resolver default"); + assertEquals("000000000000", envelope.path("account").asText()); + } + + @Test + void putEvents_envelopeRegionFromEntryWinsOverCallRegion() throws Exception { + // Simulates the archive-replay path which stamps "Region" / "Account" on the + // re-emitted entry from the originating event's envelope. + service.putRule("my-rule", null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED, + null, null, null, "us-west-2"); + Target target = new Target(); + target.setId("t1"); + target.setArn("arn:aws:sqs:us-west-2:000000000000:replay-queue"); + service.putTargets("my-rule", null, List.of(target), "us-west-2"); + + java.util.Map entry = new java.util.HashMap<>(); + entry.put("Source", "my.app"); + entry.put("DetailType", "Test"); + entry.put("Detail", "{}"); + entry.put("Region", "ap-northeast-1"); + entry.put("Account", "111111111111"); + + service.putEvents(List.of(entry), "us-west-2"); + + org.mockito.ArgumentCaptor json = org.mockito.ArgumentCaptor.forClass(String.class); + verify(invokerMock).invokeTarget(eq(target), json.capture(), eq("us-west-2")); + com.fasterxml.jackson.databind.JsonNode envelope = OBJECT_MAPPER.readTree(json.getValue()); + assertEquals("ap-northeast-1", envelope.path("region").asText(), + "entry.Region should win over the PutEvents call region"); + assertEquals("111111111111", envelope.path("account").asText(), + "entry.Account should win over the resolver default"); + } + + @Test + void putEvents_matchesPatternUsesCallRegionForRegionFilter() throws Exception { + // A rule with a region-filter for the call region (eu-west-1) must match a + // PutEvents entry that didn't supply Region — the entry should be normalized to + // the call region before matchesPattern() sees it. Without the normalization the + // pattern's region filter would compare against the resolver default (us-east-1) + // and the rule would miss. + service.putRule("region-filtered", null, + "{\"source\":[\"my.app\"],\"region\":[\"eu-west-1\"]}", + null, RuleState.ENABLED, null, null, null, "eu-west-1"); + Target target = new Target(); + target.setId("t1"); + target.setArn("arn:aws:sqs:eu-west-1:000000000000:filtered-queue"); + service.putTargets("region-filtered", null, List.of(target), "eu-west-1"); + + service.putEvents(List.of( + Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}")), "eu-west-1"); + + org.mockito.ArgumentCaptor json = org.mockito.ArgumentCaptor.forClass(String.class); + verify(invokerMock).invokeTarget(eq(target), json.capture(), eq("eu-west-1")); + com.fasterxml.jackson.databind.JsonNode envelope = OBJECT_MAPPER.readTree(json.getValue()); + assertEquals("eu-west-1", envelope.path("region").asText(), + "envelope and pattern matching must agree on the entry's effective region"); + } + + @Test + void putEvents_matchesPatternRejectsWrongRegionFilterUnderNonDefaultCall() { + // The mirror of the above: a rule whose region-filter does NOT match the call + // region must not fire. Pre-fix, an entry without Region would default to + // resolver-default us-east-1 in matchesPattern, accidentally satisfying a filter + // like {"region":["us-east-1"]} even when PutEvents was called against + // eu-west-1. + service.putRule("default-region-filtered", null, + "{\"source\":[\"my.app\"],\"region\":[\"us-east-1\"]}", + null, RuleState.ENABLED, null, null, null, "eu-west-1"); + Target target = new Target(); + target.setId("t1"); + target.setArn("arn:aws:sqs:eu-west-1:000000000000:wrong-region-queue"); + service.putTargets("default-region-filtered", null, List.of(target), "eu-west-1"); + + service.putEvents(List.of( + Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}")), "eu-west-1"); + + verify(invokerMock, org.mockito.Mockito.never()).invokeTarget(eq(target), any(), any()); + } + + @Test + void putEvents_envelopeDefaultsRegressionForDefaultRegionCall() throws Exception { + // Regression: when neither the entry nor the call carries a region (callers in + // the default region), the envelope still stamps the resolver default — same + // behavior as before the fix. + service.putRule("my-rule", null, "{\"source\":[\"my.app\"]}", null, RuleState.ENABLED, + null, null, null, REGION); + Target target = new Target(); + target.setId("t1"); + target.setArn("arn:aws:sqs:us-east-1:000000000000:default-queue"); + service.putTargets("my-rule", null, List.of(target), REGION); + + service.putEvents(List.of( + Map.of("Source", "my.app", "DetailType", "Test", "Detail", "{}")), REGION); + + org.mockito.ArgumentCaptor json = org.mockito.ArgumentCaptor.forClass(String.class); + verify(invokerMock).invokeTarget(eq(target), json.capture(), eq(REGION)); + com.fasterxml.jackson.databind.JsonNode envelope = OBJECT_MAPPER.readTree(json.getValue()); + assertEquals(REGION, envelope.path("region").asText()); + assertEquals("000000000000", envelope.path("account").asText()); + } }