Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(eventbridge): AWS-conformant InputTransformer from CloudFormation and PutTargets (#1885)

Luis Ruiz Pavón9b3aee6a0305
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index d2fb915a47..5b43c33b82 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -20,6 +20,7 @@ import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.eventbridge.model.BatchParameters;
import io.github.hectorvent.floci.services.eventbridge.model.EventBus;
+import io.github.hectorvent.floci.services.eventbridge.model.InputTransformer;
import io.github.hectorvent.floci.services.eventbridge.model.RuleState;
import io.github.hectorvent.floci.services.eventbridge.model.SqsParameters;
import io.github.hectorvent.floci.services.eventbridge.model.Target;
@@ -3651,6 +3652,7 @@ public class CloudFormationResourceProvisioner {
String inputPath = resolved.path("InputPath").asText(null);
if (targetId != null && targetArn != null) {
Target target = new Target(targetId, targetArn, input, inputPath);
+ target.setInputTransformer(InputTransformer.fromJson(resolved.path("InputTransformer")));
JsonNode sqsParamsNode = resolved.path("SqsParameters");
if (!sqsParamsNode.isMissingNode() && sqsParamsNode.isObject()) {
String messageGroupId = sqsParamsNode.path("MessageGroupId").asText(null);
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java
index 1a91513385..7c19ebb741 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeHandler.java
@@ -223,16 +223,7 @@ public class EventBridgeHandler {
input.isEmpty() ? null : input,
inputPath.isEmpty() ? null : inputPath
);
- JsonNode transformerNode = t.path("InputTransformer");
- if (!transformerNode.isMissingNode() && transformerNode.isObject()) {
- Map<String, String> pathsMap = new HashMap<>();
- JsonNode pathsNode = transformerNode.path("InputPathsMap");
- if (pathsNode.isObject()) {
- pathsNode.fields().forEachRemaining(e -> pathsMap.put(e.getKey(), e.getValue().asText()));
- }
- String template = transformerNode.path("InputTemplate").asText(null);
- target.setInputTransformer(new InputTransformer(pathsMap, template));
- }
+ target.setInputTransformer(InputTransformer.fromJson(t.path("InputTransformer")));
JsonNode sqsParamsNode = t.path("SqsParameters");
if (!sqsParamsNode.isMissingNode() && sqsParamsNode.isObject()) {
String messageGroupId = sqsParamsNode.path("MessageGroupId").asText(null);
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
index a0b291150d..460a4b9367 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvoker.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eventbridge;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.MissingNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -224,30 +225,90 @@ public class EventBridgeInvoker {
if (template == null) {
return eventJson;
}
- String result = template;
+ Map<String, JsonNode> resolved = new LinkedHashMap<>();
for (var e : transformer.getInputPathsMap().entrySet()) {
- String value = extractJsonPath(e.getValue(), eventJson);
- result = result.replace("<" + e.getKey() + ">", value != null ? value : "");
+ resolved.put(e.getKey(), extractNode(e.getValue(), eventJson));
}
- return result;
+ StringBuilder out = new StringBuilder(template.length() + 32);
+ boolean inString = false;
+ for (int i = 0; i < template.length(); i++) {
+ char c = template.charAt(i);
+ if (c == '<') {
+ int close = template.indexOf('>', i + 1);
+ if (close >= 0) {
+ String name = template.substring(i + 1, close);
+ if (resolved.containsKey(name)) {
+ JsonNode node = resolved.get(name);
+ out.append(inString ? rawValue(node) : jsonValue(node));
+ i = close;
+ continue;
+ }
+ }
+ out.append(c);
+ continue;
+ }
+ if (c == '"' && !isEscaped(template, i)) {
+ inString = !inString;
+ }
+ out.append(c);
+ }
+ return out.toString();
}
- String extractJsonPath(String jsonPath, String eventJson) {
+ // JSON representation for a value-position placeholder: strings quoted+escaped, objects/arrays/
+ // numbers/bools literal JSON, missing/null empty.
+ private String jsonValue(JsonNode node) {
+ if (node == null || node.isMissingNode() || node.isNull()) {
+ return "";
+ }
+ return node.toString();
+ }
+
+ // Raw value for a placeholder inside a quoted string: JSON-escaped, no surrounding quotes.
+ private String rawValue(JsonNode node) {
+ if (node == null || node.isMissingNode() || node.isNull()) {
+ return "";
+ }
+ String raw = node.isValueNode() ? node.asText() : node.toString();
+ try {
+ String quoted = objectMapper.writeValueAsString(raw); // "escaped"
+ return quoted.substring(1, quoted.length() - 1); // strip surrounding quotes
+ } catch (Exception e) {
+ LOG.warnv("Failed to JSON-escape raw template value ''{0}'': {1}", raw, e.getMessage());
+ return raw;
+ }
+ }
+
+ private static boolean isEscaped(String s, int i) {
+ int backslashes = 0;
+ for (int j = i - 1; j >= 0 && s.charAt(j) == '\\'; j--) {
+ backslashes++;
+ }
+ return (backslashes & 1) == 1;
+ }
+
+ JsonNode extractNode(String jsonPath, String eventJson) {
if (jsonPath == null || eventJson == null) {
- return null;
+ return MissingNode.getInstance();
}
try {
- String pointer = (jsonPath.startsWith("$") ? jsonPath.substring(1) : jsonPath)
- .replace('.', '/');
- JsonNode node = objectMapper.readTree(eventJson).at(pointer);
- if (node.isMissingNode() || node.isNull()) {
- return null;
- }
- return node.isTextual() ? node.asText() : node.toString();
+ return objectMapper.readTree(eventJson).at(toPointer(jsonPath));
} catch (Exception e) {
LOG.warnv("Failed to extract JSONPath {0}: {1}", jsonPath, e.getMessage());
+ return MissingNode.getInstance();
+ }
+ }
+
+ private static String toPointer(String jsonPath) {
+ return (jsonPath.startsWith("$") ? jsonPath.substring(1) : jsonPath).replace('.', '/');
+ }
+
+ String extractJsonPath(String jsonPath, String eventJson) {
+ JsonNode node = extractNode(jsonPath, eventJson);
+ if (node.isMissingNode() || node.isNull()) {
return null;
}
+ return node.isTextual() ? node.asText() : node.toString();
}
private Map<String, String> parametersFromBatchPayload(String payload) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/InputTransformer.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/InputTransformer.java
index a81d4eb0fb..2b473d41e0 100644
--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/InputTransformer.java
+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/model/InputTransformer.java
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.eventbridge.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.databind.JsonNode;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.HashMap;
@@ -20,6 +21,18 @@ public class InputTransformer {
this.inputTemplate = inputTemplate;
}
+ public static InputTransformer fromJson(JsonNode transformerNode) {
+ if (transformerNode == null || transformerNode.isMissingNode() || !transformerNode.isObject()) {
+ return null;
+ }
+ Map<String, String> pathsMap = new HashMap<>();
+ JsonNode pathsNode = transformerNode.path("InputPathsMap");
+ if (pathsNode.isObject()) {
+ pathsNode.fields().forEachRemaining(e -> pathsMap.put(e.getKey(), e.getValue().asText()));
+ }
+ return new InputTransformer(pathsMap, transformerNode.path("InputTemplate").asText(null));
+ }
+
public Map<String, String> getInputPathsMap() { return inputPathsMap; }
public void setInputPathsMap(Map<String, String> inputPathsMap) {
this.inputPathsMap = inputPathsMap != null ? inputPathsMap : new HashMap<>();
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index 74511cc1cd..ddae332581 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -10436,6 +10436,90 @@ class CloudFormationIntegrationTest {
.body("endpointConfiguration.vpcEndpointIds", contains("vpce-12345678"));
}
+ @Test
+ void createStack_eventBridgeRuleWithInputTransformer_deliversTransformedBodyToSqs() {
+ String template = """
+ {
+ "Resources": {
+ "TargetQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": { "QueueName": "cfn-it-transform-queue" }
+ },
+ "MyRule": {
+ "Type": "AWS::Events::Rule",
+ "Properties": {
+ "Name": "cfn-it-transform-rule",
+ "EventPattern": { "source": ["cfn.transform.test"] },
+ "Targets": [
+ {
+ "Id": "T0",
+ "Arn": { "Fn::GetAtt": ["TargetQueue", "Arn"] },
+ "InputTransformer": {
+ "InputPathsMap": { "e": "$.detail.eventName" },
+ "InputTemplate": "{\\"e\\":<e>}"
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-it-transform-stack")
+ .formParam("TemplateBody", template)
+ .when().post("/").then().statusCode(200).body(containsString("<StackId>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", "cfn-it-transform-stack")
+ .when().post("/")
+ .then().statusCode(200).body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
+
+ // The transformer survived CFN provisioning.
+ given()
+ .contentType("application/x-amz-json-1.1")
+ .header("X-Amz-Target", "AWSEvents.ListTargetsByRule")
+ .body("{\"Rule\":\"cfn-it-transform-rule\"}")
+ .when().post("/")
+ .then().statusCode(200)
+ .body("Targets[0].InputTransformer.InputTemplate", equalTo("{\"e\":<e>}"));
+
+ given()
+ .contentType("application/x-amz-json-1.1")
+ .header("X-Amz-Target", "AWSEvents.PutEvents")
+ .body("""
+ {"Entries":[{"Source":"cfn.transform.test","DetailType":"t",
+ "Detail":"{\\"eventName\\":\\"site.created\\"}"}]}
+ """)
+ .when().post("/")
+ .then().statusCode(200).body("FailedEntryCount", equalTo(0));
+
+ String getUrlXml = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", "cfn-it-transform-queue")
+ .when().post("/")
+ .then().statusCode(200).extract().body().asString();
+ String queueUrl = getUrlXml.substring(
+ getUrlXml.indexOf("<QueueUrl>") + "<QueueUrl>".length(),
+ getUrlXml.indexOf("</QueueUrl>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ReceiveMessage")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("MaxNumberOfMessages", "1")
+ .formParam("WaitTimeSeconds", "0")
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("{&quot;e&quot;:&quot;site.created&quot;}"));
+ }
+
@Test
void createStack_withEventBus_createsRealBusAndResolvesRefAndGetAtt() {
String template = """
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInputTransformerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInputTransformerIntegrationTest.java
new file mode 100644
index 0000000000..7e4247cd5a
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInputTransformerIntegrationTest.java
@@ -0,0 +1,78 @@
+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.Test;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+
+@QuarkusTest
+class EventBridgeInputTransformerIntegrationTest {
+
+ @BeforeAll
+ static void configureRestAssured() {
+ RestAssuredJsonUtils.configureAwsContentTypes();
+ }
+
+ @Test
+ void putTargetsInputTransformer_deliversTransformedBodyToSqs() {
+ // Queue to receive the transformed event.
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateQueue")
+ .formParam("QueueName", "eb-it-native-queue")
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-amz-json-1.1")
+ .header("X-Amz-Target", "AWSEvents.PutRule")
+ .body("{\"Name\":\"eb-it-native-rule\",\"EventPattern\":\"{\\\"source\\\":[\\\"eb.native.test\\\"]}\"}")
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-amz-json-1.1")
+ .header("X-Amz-Target", "AWSEvents.PutTargets")
+ .body("""
+ {"Rule":"eb-it-native-rule","Targets":[{
+ "Id":"T0",
+ "Arn":"arn:aws:sqs:us-east-1:000000000000:eb-it-native-queue",
+ "InputTransformer":{
+ "InputPathsMap":{"e":"$.detail.eventName"},
+ "InputTemplate":"{\\"e\\":<e>}"
+ }
+ }]}
+ """)
+ .when().post("/").then().statusCode(200).body("FailedEntryCount", equalTo(0));
+
+ given()
+ .contentType("application/x-amz-json-1.1")
+ .header("X-Amz-Target", "AWSEvents.PutEvents")
+ .body("""
+ {"Entries":[{"Source":"eb.native.test","DetailType":"t",
+ "Detail":"{\\"eventName\\":\\"site.created\\"}"}]}
+ """)
+ .when().post("/").then().statusCode(200).body("FailedEntryCount", equalTo(0));
+
+ String getUrlXml = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetQueueUrl")
+ .formParam("QueueName", "eb-it-native-queue")
+ .when().post("/").then().statusCode(200).extract().body().asString();
+ String queueUrl = getUrlXml.substring(
+ getUrlXml.indexOf("<QueueUrl>") + "<QueueUrl>".length(),
+ getUrlXml.indexOf("</QueueUrl>"));
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ReceiveMessage")
+ .formParam("QueueUrl", queueUrl)
+ .formParam("MaxNumberOfMessages", "1")
+ .formParam("WaitTimeSeconds", "0")
+ .when().post("/")
+ .then().statusCode(200)
+ .body(containsString("{&quot;e&quot;:&quot;site.created&quot;}"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerTest.java
index cf76ef4e6b..5a21a7c0c8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeInvokerTest.java
@@ -263,6 +263,55 @@ class EventBridgeInvokerTest {
assertEquals(eventJson, invoker.applyInputTransformer(transformer, eventJson));
}
+ @Test
+ void applyInputTransformer_valuePosition_stringIsQuoted() {
+ String event = "{\"detail\":{\"eventName\":\"site.created\"}}";
+ InputTransformer t = new InputTransformer(
+ java.util.Map.of("e", "$.detail.eventName"), "{\"e\":<e>}");
+ assertEquals("{\"e\":\"site.created\"}", invoker.applyInputTransformer(t, event));
+ }
+
+ @Test
+ void applyInputTransformer_valuePosition_objectNumberBoolAsIs() {
+ String event = "{\"detail\":{\"count\":42,\"ok\":true,\"payload\":{\"id\":\"abc\"}}}";
+ InputTransformer t = new InputTransformer(
+ java.util.Map.of("c", "$.detail.count", "o", "$.detail.ok", "p", "$.detail.payload"),
+ "{\"c\":<c>,\"o\":<o>,\"p\":<p>}");
+ assertEquals("{\"c\":42,\"o\":true,\"p\":{\"id\":\"abc\"}}", invoker.applyInputTransformer(t, event));
+ }
+
+ @Test
+ void applyInputTransformer_valuePosition_missingIsEmpty() {
+ String event = "{\"detail\":{}}";
+ InputTransformer t = new InputTransformer(
+ java.util.Map.of("e", "$.detail.nope"), "prefix:<e>:suffix");
+ assertEquals("prefix::suffix", invoker.applyInputTransformer(t, event));
+ }
+
+ @Test
+ void applyInputTransformer_insideString_interpolatesRaw() {
+ String event = "{\"detail\":{\"user\":\"alice\",\"eventName\":\"site.created\"}}";
+ InputTransformer t = new InputTransformer(
+ java.util.Map.of("user", "$.detail.user", "e", "$.detail.eventName"),
+ "\"<user> did <e>\"");
+ assertEquals("\"alice did site.created\"", invoker.applyInputTransformer(t, event));
+ }
+
+ @Test
+ void applyInputTransformer_quotedWholeToken_rawBetweenQuotes() {
+ String event = "{\"detail\":{\"eventName\":\"site.created\"}}";
+ InputTransformer t = new InputTransformer(
+ java.util.Map.of("e", "$.detail.eventName"), "{\"e\":\"<e>\"}");
+ assertEquals("{\"e\":\"site.created\"}", invoker.applyInputTransformer(t, event));
+ }
+
+ @Test
+ void applyInputTransformer_unknownVarLeftLiteral() {
+ String event = "{\"detail\":{}}";
+ InputTransformer t = new InputTransformer(java.util.Map.of(), "{\"x\":<unknown>}");
+ assertEquals("{\"x\":<unknown>}", invoker.applyInputTransformer(t, event));
+ }
+
@SuppressWarnings("unchecked")
@Test
void invokeTarget_eventBusTarget_republishesEventToTargetBus() {
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/model/InputTransformerTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/model/InputTransformerTest.java
new file mode 100644
index 0000000000..d68834d324
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/model/InputTransformerTest.java
@@ -0,0 +1,28 @@
+package io.github.hectorvent.floci.services.eventbridge.model;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+class InputTransformerTest {
+
+ private static final ObjectMapper M = new ObjectMapper();
+
+ @Test
+ void fromJson_parsesPathsMapAndTemplate() throws Exception {
+ var node = M.readTree("{\"InputPathsMap\":{\"e\":\"$.detail.eventName\"},"
+ + "\"InputTemplate\":\"{\\\"e\\\":<e>}\"}");
+ InputTransformer t = InputTransformer.fromJson(node);
+ assertEquals("$.detail.eventName", t.getInputPathsMap().get("e"));
+ assertEquals("{\"e\":<e>}", t.getInputTemplate());
+ }
+
+ @Test
+ void fromJson_missingOrNonObject_returnsNull() throws Exception {
+ assertNull(InputTransformer.fromJson(null));
+ assertNull(InputTransformer.fromJson(M.readTree("{}").path("InputTransformer")));
+ assertNull(InputTransformer.fromJson(M.readTree("\"not-an-object\"")));
+ }
+}