mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(eventbridge): deliver events to event-bus targets (#1814)
* feat(eventbridge): deliver events to event-bus targets * fix(eventbridge): skip null resources when republishing to event-bus targets * fix(eventbridge): validate Detail and resolve account for bus targets readTree accepts any well-formed JSON value, so an input override producing "hello" or [1,2] passed the guard and reached the target bus as a scalar detail, with putEvents reporting success — a silent malformation rather than the intended warn-and-drop. The pass-through arm had the same hole. Both arms now share one isObject() check. Bus targets also went through the two-arg putEvents overload, which passes a null accountId, so a cross-account bus ARN resolved in the caller's account and surfaced only as a warning. Thread the ARN's account through, as SQS targets already do via the queue URL. Same-account and account-less ARNs still forward null: only that path carries the legacy-key fallback in AccountAwareStorageBackend.get(). * docs(eventbridge): document event-bus target behavior and limits * fix(eventbridge): cap bus-to-bus forwarding at one hop, matching AWS
This commit is contained in:
1 parent
f34e0b5655
commit
50fe67dde6
5 files changed
+659
-2
No files matched your search
@@ -98,3 +98,26 @@ aws events put-events \
|
||||
--entries '[{"Source":"myapp","DetailType":"test","Detail":"{}"}]' \
|
||||
--endpoint-url $AWS_ENDPOINT_URL
|
||||
```
|
||||
|
||||
## Event Bus Targets
|
||||
|
||||
A rule can target another event bus by ARN: the event is republished there, and that bus's own rules evaluate it and fan out normally. `Source`, `DetailType`, `Resources` and the originating `account`/`region` carry over, and each hop gets a new event id.
|
||||
|
||||
```bash
|
||||
aws events put-targets \
|
||||
--rule order-placed-rule \
|
||||
--event-bus-name my-bus \
|
||||
--targets '[{
|
||||
"Id": "forward-to-domain-bus",
|
||||
"Arn": "arn:aws:events:us-east-1:000000000000:event-bus/domain-bus"
|
||||
}]' \
|
||||
--endpoint-url $AWS_ENDPOINT_URL
|
||||
```
|
||||
|
||||
## Current Behavior
|
||||
|
||||
- `PutEvents` reports success once the source bus accepts an event, so target delivery failures surface only as a `WARN` in the Floci logs.
|
||||
- A `Detail` forwarded to an event bus must be a JSON object, as in AWS; anything else is dropped, including an `InputPath` selecting a scalar such as `$.detail.orderId` or an envelope carrying `"detail": null`.
|
||||
- A bus ARN naming another account is forwarded under that account, so the target bus and its rules resolve there.
|
||||
- Onward delivery from that bus follows each target type: SQS resolves cross-account, while Lambda, SNS, Batch and Firehose resolve in the caller's account.
|
||||
- An event is forwarded between buses only once, matching AWS: a bus that received an event from another bus does not forward it on to a third. The second hop is dropped with only a `WARN` rather than reported to the caller.
|
||||
+92
-1
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.batch.BatchService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.Target;
|
||||
@@ -18,7 +19,9 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -26,11 +29,17 @@ public class EventBridgeInvoker {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EventBridgeInvoker.class);
|
||||
|
||||
// AWS can't route an event from a sender bus on to a third bus; the second hop is dropped.
|
||||
private static final int MAX_BUS_TO_BUS_DEPTH = 1;
|
||||
private static final ThreadLocal<Integer> BUS_TO_BUS_DEPTH = ThreadLocal.withInitial(() -> 0);
|
||||
|
||||
private final LambdaService lambdaService;
|
||||
private final SqsService sqsService;
|
||||
private final SnsService snsService;
|
||||
private final BatchService batchService;
|
||||
private final FirehoseService firehoseService;
|
||||
private final EventBridgeService eventBridgeService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final String baseUrl;
|
||||
|
||||
@@ -40,6 +49,8 @@ public class EventBridgeInvoker {
|
||||
SnsService snsService,
|
||||
BatchService batchService,
|
||||
FirehoseService firehoseService,
|
||||
EventBridgeService eventBridgeService,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper,
|
||||
EmulatorConfig config) {
|
||||
this.lambdaService = lambdaService;
|
||||
@@ -47,6 +58,8 @@ public class EventBridgeInvoker {
|
||||
this.snsService = snsService;
|
||||
this.batchService = batchService;
|
||||
this.firehoseService = firehoseService;
|
||||
this.eventBridgeService = eventBridgeService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
this.baseUrl = config.baseUrl();
|
||||
}
|
||||
@@ -56,7 +69,9 @@ public class EventBridgeInvoker {
|
||||
SnsService snsService,
|
||||
ObjectMapper objectMapper,
|
||||
EmulatorConfig config) {
|
||||
this(lambdaService, sqsService, snsService, null, null, objectMapper, config);
|
||||
this(lambdaService, sqsService, snsService,
|
||||
null /* batch */, null /* firehose */, null /* eventBridge */, null /* regionResolver */,
|
||||
objectMapper, config);
|
||||
}
|
||||
|
||||
public void invokeTarget(Target target, String eventJson, String region) {
|
||||
@@ -114,6 +129,82 @@ public class EventBridgeInvoker {
|
||||
// without appending a newline; the delivery-side NDJSON flush handles separation.
|
||||
firehoseService.putRecord(streamName, new Record(payload.getBytes(StandardCharsets.UTF_8)));
|
||||
LOG.debugv("EventBridge delivered to Firehose: {0}", arn);
|
||||
} else if (arn.contains(":events:") && arn.contains(":event-bus/")) {
|
||||
if (eventBridgeService == null) {
|
||||
LOG.warnv("EventBridge event-bus target missing EventBridge service: {0}", arn);
|
||||
return;
|
||||
}
|
||||
// Relies on putEvents delivering targets synchronously.
|
||||
int depth = BUS_TO_BUS_DEPTH.get();
|
||||
if (depth >= MAX_BUS_TO_BUS_DEPTH) {
|
||||
LOG.warnv("EventBridge bus-to-bus depth {0} exceeded at target {1}; dropping", depth, arn);
|
||||
return;
|
||||
}
|
||||
String targetRegion = extractRegionFromArn(arn, region);
|
||||
// Input overrides shape only Detail; the rest of the entry comes from the original
|
||||
// event envelope, matching AWS event-bus target semantics.
|
||||
JsonNode envelope = objectMapper.readTree(eventJson);
|
||||
boolean inputOverridden = target.getInput() != null
|
||||
|| target.getInputPath() != null
|
||||
|| target.getInputTransformer() != null;
|
||||
JsonNode detailNode;
|
||||
if (inputOverridden) {
|
||||
try {
|
||||
detailNode = objectMapper.readTree(payload);
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("EventBridge event-bus target {0} requires JSON Detail; dropping non-JSON input: {1}",
|
||||
arn, e.getMessage());
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
detailNode = envelope.get("detail");
|
||||
if (detailNode == null) {
|
||||
detailNode = objectMapper.createObjectNode();
|
||||
}
|
||||
}
|
||||
// readTree accepts any well-formed JSON value; AWS emits an event only when
|
||||
// Detail is an object, and both arms can produce a scalar or array.
|
||||
if (!detailNode.isObject()) {
|
||||
LOG.warnv("EventBridge event-bus target {0} requires a JSON object Detail; dropping: {1}",
|
||||
arn, detailNode);
|
||||
return;
|
||||
}
|
||||
String detailBody = detailNode.toString();
|
||||
Map<String, Object> entry = new HashMap<>();
|
||||
// putEvents accepts a full event-bus ARN as EventBusName and validates it.
|
||||
entry.put("EventBusName", arn);
|
||||
entry.put("Source", envelope.path("source").asText(""));
|
||||
entry.put("DetailType", envelope.path("detail-type").asText(""));
|
||||
entry.put("Detail", detailBody);
|
||||
// AWS keeps the originating account/region; blank falls back inside putEvents.
|
||||
entry.put("Region", envelope.path("region").asText(""));
|
||||
entry.put("Account", envelope.path("account").asText(""));
|
||||
if (envelope.hasNonNull("resources") && envelope.get("resources").isArray()) {
|
||||
entry.put("Resources", envelope.get("resources"));
|
||||
}
|
||||
// null routes through RequestContext, the only path carrying the legacy-key
|
||||
// fallback; Arn.accountId() is "" when the ARN omits the account segment.
|
||||
String targetAccount = AwsArnUtils.parse(arn).accountId();
|
||||
String currentAccount = regionResolver != null ? regionResolver.getAccountId() : null;
|
||||
String forwardAccount = targetAccount == null || targetAccount.isBlank()
|
||||
|| targetAccount.equals(currentAccount)
|
||||
? null
|
||||
: targetAccount;
|
||||
BUS_TO_BUS_DEPTH.set(depth + 1);
|
||||
try {
|
||||
var result = eventBridgeService.putEvents(List.of(entry), targetRegion, forwardAccount);
|
||||
if (result.failedCount() > 0) {
|
||||
LOG.warnv("EventBridge event-bus target {0} rejected event: {1}", arn, result.entries());
|
||||
} else {
|
||||
LOG.debugv("EventBridge delivered to EventBus: {0}", arn);
|
||||
}
|
||||
} finally {
|
||||
if (depth == 0) {
|
||||
BUS_TO_BUS_DEPTH.remove();
|
||||
} else {
|
||||
BUS_TO_BUS_DEPTH.set(depth);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
LOG.warnv("EventBridge: unsupported target ARN type: {0}", arn);
|
||||
}
|
||||
|
||||
+9
-1
@@ -650,7 +650,15 @@ public class EventBridgeService {
|
||||
return putEvents(entries, region, null);
|
||||
}
|
||||
|
||||
private PutEventsResult putEvents(List<Map<String, Object>> entries, String region, String accountId) {
|
||||
/**
|
||||
* Publishes entries to a bus, optionally naming the account the bus lives in.
|
||||
*
|
||||
* @param accountId account owning the target bus, or {@code null} to resolve against the
|
||||
* caller's request context. Only {@code null} carries the un-prefixed
|
||||
* legacy-key fallback in {@link AccountAwareStorageBackend#get}, so pass
|
||||
* {@code null} whenever the target is in the caller's own account.
|
||||
*/
|
||||
public PutEventsResult putEvents(List<Map<String, Object>> entries, String region, String accountId) {
|
||||
int failed = 0;
|
||||
List<Map<String, String>> resultEntries = new ArrayList<>();
|
||||
|
||||
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
/**
|
||||
* End-to-end EventBridge bus→bus target delivery: a rule on the source bus targets a
|
||||
* second event bus by ARN, whose rule then delivers to SQS. Mirrors a two-bus routing
|
||||
* topology where a shared bus forwards domain-scoped events to a domain-specific bus.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class EventBridgeBusToBusIntegrationTest {
|
||||
|
||||
private static final String SQS_CT = "application/x-amz-json-1.0";
|
||||
private static final String EB_CT = "application/x-amz-json-1.1";
|
||||
|
||||
private static final String SOURCE_BUS = "b2b-source-bus";
|
||||
private static final String TARGET_BUS = "b2b-target-bus";
|
||||
private static final String QUEUE = "b2b-sink-queue";
|
||||
private static final String FORWARD_RULE = "b2b-forward-rule";
|
||||
private static final String SINK_RULE = "b2b-sink-rule";
|
||||
|
||||
private static final String XA_SOURCE_BUS = "xa-source-bus";
|
||||
private static final String XA_TARGET_BUS = "xa-target-bus";
|
||||
private static final String XA_QUEUE = "xa-sink-queue";
|
||||
private static final String XA_FORWARD_RULE = "xa-forward-rule";
|
||||
private static final String XA_SINK_RULE = "xa-sink-rule";
|
||||
|
||||
private static final String AUTH_1_EVENTS = "AWS4-HMAC-SHA256 "
|
||||
+ "Credential=000000000001/20260805/us-east-1/events/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
private static final String AUTH_2_EVENTS = "AWS4-HMAC-SHA256 "
|
||||
+ "Credential=000000000002/20260805/us-east-1/events/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
private static final String AUTH_2_SQS = "AWS4-HMAC-SHA256 "
|
||||
+ "Credential=000000000002/20260805/us-east-1/sqs/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
|
||||
private static String xaQueueUrl;
|
||||
private static String xaQueuePath;
|
||||
private static String xaTargetBusArn;
|
||||
|
||||
private static String queueUrl;
|
||||
private static String queueArn;
|
||||
private static String targetBusArn;
|
||||
|
||||
private static final String HOP_A = "hop-bus-a";
|
||||
private static final String HOP_B = "hop-bus-b";
|
||||
private static final String HOP_C = "hop-bus-c";
|
||||
private static final String HOP_B_QUEUE = "hop-sink-b";
|
||||
private static final String HOP_C_QUEUE = "hop-sink-c";
|
||||
|
||||
private static String hopBQueueUrl;
|
||||
private static String hopBQueuePath;
|
||||
private static String hopCQueueUrl;
|
||||
private static String hopCQueuePath;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void setupBusesQueueAndRules() {
|
||||
// Two custom buses
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus")
|
||||
.body("{\"Name\":\"" + SOURCE_BUS + "\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
targetBusArn = given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus")
|
||||
.body("{\"Name\":\"" + TARGET_BUS + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("EventBusArn");
|
||||
|
||||
// SQS sink
|
||||
queueUrl = given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.CreateQueue")
|
||||
.body("{\"QueueName\":\"" + QUEUE + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("QueueUrl");
|
||||
|
||||
queueArn = given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")
|
||||
.body("{\"QueueUrl\":\"" + queueUrl + "\",\"AttributeNames\":[\"All\"]}")
|
||||
.when().post("/0000000000/" + QUEUE).then().statusCode(200)
|
||||
.extract().jsonPath().getString("Attributes.QueueArn");
|
||||
|
||||
// Rule on source bus → target bus (the branch under test)
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.body("{\"Name\":\"" + FORWARD_RULE + "\",\"EventBusName\":\"" + SOURCE_BUS + "\","
|
||||
+ "\"EventPattern\":\"{\\\"source\\\":[\\\"myapp.orders\\\"]}\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body("{\"Rule\":\"" + FORWARD_RULE + "\",\"EventBusName\":\"" + SOURCE_BUS + "\","
|
||||
+ "\"Targets\":[{\"Id\":\"forward\",\"Arn\":\"" + targetBusArn + "\"}]}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
// Rule on target bus → SQS
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.body("{\"Name\":\"" + SINK_RULE + "\",\"EventBusName\":\"" + TARGET_BUS + "\","
|
||||
+ "\"EventPattern\":\"{\\\"source\\\":[\\\"myapp.orders\\\"]}\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body("{\"Rule\":\"" + SINK_RULE + "\",\"EventBusName\":\"" + TARGET_BUS + "\","
|
||||
+ "\"Targets\":[{\"Id\":\"sink\",\"Arn\":\"" + queueArn + "\"}]}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void publishOnSourceBus_forwardsThroughTargetBus_toSqs() {
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutEvents")
|
||||
.body("""
|
||||
{"Entries":[{
|
||||
"EventBusName":"%s",
|
||||
"Source":"myapp.orders",
|
||||
"DetailType":"Order.Created",
|
||||
"Resources":["arn:aws:s3:::b2b-bucket"],
|
||||
"Detail":"{\\"orderId\\":\\"o-1\\"}"
|
||||
}]}
|
||||
""".formatted(SOURCE_BUS))
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
|
||||
.body("{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":2}")
|
||||
.when().post("/0000000000/" + QUEUE)
|
||||
.then().statusCode(200)
|
||||
.body("Messages", hasSize(1))
|
||||
.body("Messages[0].Body", containsString("\"source\":\"myapp.orders\""))
|
||||
.body("Messages[0].Body", containsString("\"detail-type\":\"Order.Created\""))
|
||||
// Detail must be unwrapped, not the whole envelope re-wrapped.
|
||||
.body("Messages[0].Body", containsString("\"detail\":{\"orderId\":\"o-1\"}"))
|
||||
.body("Messages[0].Body", containsString("\"resources\":[\"arn:aws:s3:::b2b-bucket\"]"))
|
||||
.body("Messages[0].Body", containsString("\"event-bus-name\":\"" + TARGET_BUS + "\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void setupCrossAccountTopology() {
|
||||
// Source bus in account 1.
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus")
|
||||
.header("Authorization", AUTH_1_EVENTS)
|
||||
.body("{\"Name\":\"" + XA_SOURCE_BUS + "\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
// Target bus in account 2 — the ARN it returns carries account 2.
|
||||
xaTargetBusArn = given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus")
|
||||
.header("Authorization", AUTH_2_EVENTS)
|
||||
.body("{\"Name\":\"" + XA_TARGET_BUS + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("EventBusArn");
|
||||
|
||||
// SQS sink in account 2. SQS is the only target type that resolves
|
||||
// cross-account today, so it is the only sink that can prove delivery here.
|
||||
xaQueueUrl = given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.CreateQueue")
|
||||
.header("Authorization", AUTH_2_SQS)
|
||||
.body("{\"QueueName\":\"" + XA_QUEUE + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("QueueUrl");
|
||||
xaQueuePath = URI.create(xaQueueUrl).getPath();
|
||||
|
||||
String xaQueueArn = given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")
|
||||
.header("Authorization", AUTH_2_SQS)
|
||||
.body("{\"QueueUrl\":\"" + xaQueueUrl + "\",\"AttributeNames\":[\"All\"]}")
|
||||
.when().post(xaQueuePath).then().statusCode(200)
|
||||
.extract().jsonPath().getString("Attributes.QueueArn");
|
||||
|
||||
// Rule on account 2's target bus → its own SQS queue.
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.header("Authorization", AUTH_2_EVENTS)
|
||||
.body("{\"Name\":\"" + XA_SINK_RULE + "\",\"EventBusName\":\"" + XA_TARGET_BUS + "\","
|
||||
+ "\"EventPattern\":\"{\\\"source\\\":[\\\"myapp.xa\\\"]}\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.header("Authorization", AUTH_2_EVENTS)
|
||||
.body("{\"Rule\":\"" + XA_SINK_RULE + "\",\"EventBusName\":\"" + XA_TARGET_BUS + "\","
|
||||
+ "\"Targets\":[{\"Id\":\"sink\",\"Arn\":\"" + xaQueueArn + "\"}]}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
// Rule on account 1's source bus → account 2's bus, by ARN.
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.header("Authorization", AUTH_1_EVENTS)
|
||||
.body("{\"Name\":\"" + XA_FORWARD_RULE + "\",\"EventBusName\":\"" + XA_SOURCE_BUS + "\","
|
||||
+ "\"EventPattern\":\"{\\\"source\\\":[\\\"myapp.xa\\\"]}\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.header("Authorization", AUTH_1_EVENTS)
|
||||
.body("{\"Rule\":\"" + XA_FORWARD_RULE + "\",\"EventBusName\":\"" + XA_SOURCE_BUS + "\","
|
||||
+ "\"Targets\":[{\"Id\":\"forward\",\"Arn\":\"" + xaTargetBusArn + "\"}]}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void publishInAccountOne_forwardsToAccountTwoBus_andReachesItsQueue() {
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutEvents")
|
||||
.header("Authorization", AUTH_1_EVENTS)
|
||||
.body("""
|
||||
{"Entries":[{
|
||||
"EventBusName":"%s",
|
||||
"Source":"myapp.xa",
|
||||
"DetailType":"Order.Created",
|
||||
"Detail":"{\\"orderId\\":\\"xa-1\\"}"
|
||||
}]}
|
||||
""".formatted(XA_SOURCE_BUS))
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
|
||||
.header("Authorization", AUTH_2_SQS)
|
||||
.body("{\"QueueUrl\":\"" + xaQueueUrl + "\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":2}")
|
||||
.when().post(xaQueuePath)
|
||||
.then().statusCode(200)
|
||||
.body("Messages", hasSize(1))
|
||||
.body("Messages[0].Body", containsString("\"detail\":{\"orderId\":\"xa-1\"}"))
|
||||
.body("Messages[0].Body", containsString("\"event-bus-name\":\"" + XA_TARGET_BUS + "\""))
|
||||
// The envelope keeps the originating account, not the target bus's.
|
||||
.body("Messages[0].Body", containsString("\"account\":\"000000000001\""));
|
||||
}
|
||||
|
||||
/**
|
||||
* A -> B -> C with a sink on both B and C, so an empty C queue means the hop was capped
|
||||
* rather than the chain never having been wired.
|
||||
*/
|
||||
@Test
|
||||
@Order(5)
|
||||
void setupThreeBusChain() {
|
||||
for (String bus : new String[]{HOP_A, HOP_B, HOP_C}) {
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.CreateEventBus")
|
||||
.body("{\"Name\":\"" + bus + "\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
String busBArn = given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DescribeEventBus")
|
||||
.body("{\"Name\":\"" + HOP_B + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Arn");
|
||||
String busCArn = given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.DescribeEventBus")
|
||||
.body("{\"Name\":\"" + HOP_C + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("Arn");
|
||||
|
||||
hopBQueueUrl = createQueue(HOP_B_QUEUE);
|
||||
hopBQueuePath = URI.create(hopBQueueUrl).getPath();
|
||||
hopCQueueUrl = createQueue(HOP_C_QUEUE);
|
||||
hopCQueuePath = URI.create(hopCQueueUrl).getPath();
|
||||
|
||||
// A -> B, B -> C, plus an SQS sink on each of B and C.
|
||||
putForwardRule(HOP_A, "hop-a-to-b", busBArn);
|
||||
putForwardRule(HOP_B, "hop-b-to-c", busCArn);
|
||||
putForwardRule(HOP_B, "hop-b-sink", queueArnFor(hopBQueueUrl, HOP_B_QUEUE));
|
||||
putForwardRule(HOP_C, "hop-c-sink", queueArnFor(hopCQueueUrl, HOP_C_QUEUE));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void forwardingStopsAfterOneHop() {
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutEvents")
|
||||
.body("""
|
||||
{"Entries":[{
|
||||
"EventBusName":"%s",
|
||||
"Source":"myapp.hop",
|
||||
"DetailType":"Order.Created",
|
||||
"Detail":"{\\"orderId\\":\\"hop-1\\"}"
|
||||
}]}
|
||||
""".formatted(HOP_A))
|
||||
.when().post("/").then().statusCode(200);
|
||||
|
||||
// Hop one delivered: B received the event.
|
||||
given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
|
||||
.body("{\"QueueUrl\":\"" + hopBQueueUrl + "\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":2}")
|
||||
.when().post(hopBQueuePath).then().statusCode(200)
|
||||
.body("Messages", hasSize(1))
|
||||
.body("Messages[0].Body", containsString("\"detail\":{\"orderId\":\"hop-1\"}"));
|
||||
|
||||
// Hop two dropped: C never received it, even though B has a rule targeting C.
|
||||
given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.ReceiveMessage")
|
||||
.body("{\"QueueUrl\":\"" + hopCQueueUrl + "\",\"MaxNumberOfMessages\":1,\"WaitTimeSeconds\":2}")
|
||||
.when().post(hopCQueuePath).then().statusCode(200)
|
||||
.body("Messages", anyOf(nullValue(), hasSize(0)));
|
||||
}
|
||||
|
||||
private static String createQueue(String name) {
|
||||
return given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.CreateQueue")
|
||||
.body("{\"QueueName\":\"" + name + "\"}")
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().jsonPath().getString("QueueUrl");
|
||||
}
|
||||
|
||||
private static String queueArnFor(String queueUrl, String name) {
|
||||
return given().contentType(SQS_CT).header("X-Amz-Target", "AmazonSQS.GetQueueAttributes")
|
||||
.body("{\"QueueUrl\":\"" + queueUrl + "\",\"AttributeNames\":[\"All\"]}")
|
||||
.when().post(URI.create(queueUrl).getPath()).then().statusCode(200)
|
||||
.extract().jsonPath().getString("Attributes.QueueArn");
|
||||
}
|
||||
|
||||
private static void putForwardRule(String bus, String ruleName, String targetArn) {
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutRule")
|
||||
.body("{\"Name\":\"" + ruleName + "\",\"EventBusName\":\"" + bus + "\","
|
||||
+ "\"EventPattern\":\"{\\\"source\\\":[\\\"myapp.hop\\\"]}\"}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
given().contentType(EB_CT).header("X-Amz-Target", "AWSEvents.PutTargets")
|
||||
.body("{\"Rule\":\"" + ruleName + "\",\"EventBusName\":\"" + bus + "\","
|
||||
+ "\"Targets\":[{\"Id\":\"t\",\"Arn\":\"" + targetArn + "\"}]}")
|
||||
.when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
+212
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eventbridge;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.batch.BatchService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
|
||||
import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
|
||||
@@ -15,6 +16,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.mockito.ArgumentCaptor;
|
||||
@@ -29,6 +31,8 @@ class EventBridgeInvokerTest {
|
||||
private SqsService sqsService;
|
||||
private BatchService batchService;
|
||||
private FirehoseService firehoseService;
|
||||
private EventBridgeService eventBridgeService;
|
||||
private RegionResolver regionResolver;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -37,12 +41,19 @@ class EventBridgeInvokerTest {
|
||||
SnsService snsService = mock(SnsService.class);
|
||||
batchService = mock(BatchService.class);
|
||||
firehoseService = mock(FirehoseService.class);
|
||||
eventBridgeService = mock(EventBridgeService.class);
|
||||
regionResolver = mock(RegionResolver.class);
|
||||
when(regionResolver.getAccountId()).thenReturn("000000000000");
|
||||
when(eventBridgeService.putEvents(anyList(), anyString(), any()))
|
||||
.thenReturn(new EventBridgeService.PutEventsResult(0, List.of()));
|
||||
invoker = new EventBridgeInvoker(
|
||||
lambdaService,
|
||||
sqsService,
|
||||
snsService,
|
||||
batchService,
|
||||
firehoseService,
|
||||
eventBridgeService,
|
||||
regionResolver,
|
||||
new ObjectMapper(),
|
||||
mock(io.github.hectorvent.floci.config.EmulatorConfig.class)
|
||||
);
|
||||
@@ -236,4 +247,205 @@ class EventBridgeInvokerTest {
|
||||
InputTransformer transformer = new InputTransformer(Map.of(), null);
|
||||
assertEquals(eventJson, invoker.applyInputTransformer(transformer, eventJson));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void invokeTarget_eventBusTarget_republishesEventToTargetBus() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
String event = "{\"source\":\"myapp.orders\",\"detail-type\":\"Order.Created\","
|
||||
+ "\"resources\":[\"arn:aws:s3:::b\"],\"detail\":{\"orderId\":\"o-1\"}}";
|
||||
|
||||
invoker.invokeTarget(target, event, "eu-west-1");
|
||||
|
||||
ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(eventBridgeService).putEvents(captor.capture(), eq("eu-west-1"), isNull());
|
||||
List<Map<String, Object>> entries = captor.getValue();
|
||||
assertEquals(1, entries.size());
|
||||
Map<String, Object> entry = entries.get(0);
|
||||
assertEquals("arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
entry.get("EventBusName"));
|
||||
assertEquals("myapp.orders", entry.get("Source"));
|
||||
assertEquals("Order.Created", entry.get("DetailType"));
|
||||
assertEquals("{\"orderId\":\"o-1\"}", entry.get("Detail"));
|
||||
assertEquals("[\"arn:aws:s3:::b\"]", entry.get("Resources").toString());
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithInputTransformer_usesOriginalSourceAndTransformedDetail() {
|
||||
InputTransformer transformer = new InputTransformer(
|
||||
Map.of("id", "$.detail.orderId"),
|
||||
"{\"remapped\":\"<id>\"}");
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
target.setInputTransformer(transformer);
|
||||
String event = "{\"source\":\"myapp.orders\",\"detail-type\":\"Order.Created\","
|
||||
+ "\"detail\":{\"orderId\":\"o-1\"}}";
|
||||
|
||||
invoker.invokeTarget(target, event, "eu-west-1");
|
||||
|
||||
ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(eventBridgeService).putEvents(captor.capture(), eq("eu-west-1"), isNull());
|
||||
Map<String, Object> entry = captor.getValue().get(0);
|
||||
assertEquals("myapp.orders", entry.get("Source"));
|
||||
assertEquals("Order.Created", entry.get("DetailType"));
|
||||
assertEquals("{\"remapped\":\"o-1\"}", entry.get("Detail"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void invokeTarget_eventBusTarget_preservesOriginAccountAndRegion() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
String event = "{\"source\":\"myapp.orders\",\"detail-type\":\"Order.Created\","
|
||||
+ "\"account\":\"111122223333\",\"region\":\"eu-central-1\","
|
||||
+ "\"detail\":{\"orderId\":\"o-1\"}}";
|
||||
|
||||
invoker.invokeTarget(target, event, "eu-west-1");
|
||||
|
||||
ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(eventBridgeService).putEvents(captor.capture(), eq("eu-west-1"), isNull());
|
||||
Map<String, Object> entry = captor.getValue().get(0);
|
||||
assertEquals("111122223333", entry.get("Account"));
|
||||
assertEquals("eu-central-1", entry.get("Region"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithNullResources_omitsResourcesEntry() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
String event = "{\"source\":\"myapp.orders\",\"detail-type\":\"Order.Created\","
|
||||
+ "\"resources\":null,\"detail\":{\"orderId\":\"o-1\"}}";
|
||||
|
||||
invoker.invokeTarget(target, event, "eu-west-1");
|
||||
|
||||
ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(eventBridgeService).putEvents(captor.capture(), eq("eu-west-1"), isNull());
|
||||
Map<String, Object> entry = captor.getValue().get(0);
|
||||
assertFalse(entry.containsKey("Resources"));
|
||||
assertEquals("{\"orderId\":\"o-1\"}", entry.get("Detail"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithNonJsonInput_dropsWithoutPublishing() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
target.setInputTransformer(new InputTransformer(
|
||||
Map.of("bucket", "$.detail.bucket.name"),
|
||||
"bucket=<bucket>"));
|
||||
|
||||
invoker.invokeTarget(target, "{\"source\":\"aws.s3\"}", "eu-west-1");
|
||||
|
||||
verify(eventBridgeService, never()).putEvents(anyList(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithoutEventBridgeService_skipsWithoutThrowing() {
|
||||
EventBridgeInvoker bare = new EventBridgeInvoker(
|
||||
mock(LambdaService.class),
|
||||
sqsService,
|
||||
mock(SnsService.class),
|
||||
new ObjectMapper(),
|
||||
mock(io.github.hectorvent.floci.config.EmulatorConfig.class));
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
|
||||
assertDoesNotThrow(() -> bare.invokeTarget(target, "{\"detail\":{}}", "eu-west-1"));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetInAnotherAccount_forwardsUnderArnAccount() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000002:event-bus/other-account-bus",
|
||||
null, null);
|
||||
String event = "{\"source\":\"myapp.orders\",\"detail-type\":\"Order.Created\","
|
||||
+ "\"detail\":{\"orderId\":\"o-1\"}}";
|
||||
|
||||
invoker.invokeTarget(target, event, "eu-west-1");
|
||||
|
||||
ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
|
||||
verify(eventBridgeService).putEvents(captor.capture(), eq("eu-west-1"), eq("000000000002"));
|
||||
assertEquals("arn:aws:events:eu-west-1:000000000002:event-bus/other-account-bus",
|
||||
captor.getValue().get(0).get("EventBusName"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetInSameAccount_forwardsWithNullAccount() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
|
||||
invoker.invokeTarget(target, "{\"source\":\"s\",\"detail\":{}}", "eu-west-1");
|
||||
|
||||
verify(eventBridgeService).putEvents(anyList(), eq("eu-west-1"), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithAccountlessArn_forwardsWithNullAccount() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1::event-bus/my-target-bus",
|
||||
null, null);
|
||||
|
||||
// Distinct from the same-account case: accountId() is "" here, not null.
|
||||
invoker.invokeTarget(target, "{\"source\":\"s\",\"detail\":{}}", "eu-west-1");
|
||||
|
||||
verify(eventBridgeService).putEvents(anyList(), eq("eu-west-1"), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithScalarJsonInput_dropsWithoutPublishing() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
"\"hello\"", null);
|
||||
|
||||
invoker.invokeTarget(target, "{\"source\":\"myapp.orders\",\"detail\":{}}", "eu-west-1");
|
||||
|
||||
verify(eventBridgeService, never()).putEvents(anyList(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithArrayInput_dropsWithoutPublishing() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
"[1,2]", null);
|
||||
|
||||
invoker.invokeTarget(target, "{\"source\":\"myapp.orders\",\"detail\":{}}", "eu-west-1");
|
||||
|
||||
verify(eventBridgeService, never()).putEvents(anyList(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithNumericInput_dropsWithoutPublishing() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
"123", null);
|
||||
|
||||
invoker.invokeTarget(target, "{\"source\":\"myapp.orders\",\"detail\":{}}", "eu-west-1");
|
||||
|
||||
verify(eventBridgeService, never()).putEvents(anyList(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void invokeTarget_eventBusTargetWithScalarEnvelopeDetail_dropsWithoutPublishing() {
|
||||
Target target = new Target("id1",
|
||||
"arn:aws:events:eu-west-1:000000000000:event-bus/my-target-bus",
|
||||
null, null);
|
||||
// No input override: the scalar arrives on the envelope itself, which the
|
||||
// PutEvents handler permits today.
|
||||
String event = "{\"source\":\"myapp.orders\",\"detail-type\":\"Order.Created\","
|
||||
+ "\"detail\":\"hello\"}";
|
||||
|
||||
invoker.invokeTarget(target, event, "eu-west-1");
|
||||
|
||||
verify(eventBridgeService, never()).putEvents(anyList(), anyString(), any());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user