You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@streampipes.apache.org by ri...@apache.org on 2026/10/07 14:48:37 UTC
(streampipes) 01/01: fix: restrict Kamelet transform configuration
This is an automated email from the ASF dual-hosted git repository.
dominikriemer pushed a commit to branch fix/camel-yaml-validation
in repository https://gitbox.apache.org/repos/asf/streampipes.git
commit 51f07ca8a70b92147c700a9ea66164f9bd8330e2
Author: Dominik Riemer <do...@gmail.com>
AuthorDate: Wed Oct 7 16:33:42 2026 +0200
fix: restrict Kamelet transform configuration
---
.../streampipes-connectors-camel/README.md | 58 +++++
.../streampipes-connectors-camel/pom.xml | 11 +
.../config/KameletSinkStaticPropertyProvider.java | 3 +-
.../transform/KameletTransformRouteLoader.java | 241 ++++++++++----------
.../transform/KameletTransformRouteLoaderTest.java | 243 +++++++++++++++++++++
5 files changed, 435 insertions(+), 121 deletions(-)
diff --git a/streampipes-extensions/streampipes-connectors-camel/README.md b/streampipes-extensions/streampipes-connectors-camel/README.md
new file mode 100644
index 0000000000..1cfcb2504a
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-camel/README.md
@@ -0,0 +1,58 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to you under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+# Kamelet transform steps
+
+The optional **Transform Steps (YAML)** field supports a data-only subset, evaluated
+before delivery to the configured Kamelet sink. Empty input and `[]` forward the
+mapped message unchanged. Existing event-map, JSON and mapped-field payload modes
+and header mappings remain available.
+
+Supported steps are `setBody`, `setHeader` and `removeHeader` (also spelled
+`set-body`, `set-header` and `remove-header`). Each list entry contains exactly one
+step. `setHeader` and `removeHeader` require a literal `name` containing only ASCII
+letters, digits, underscores or hyphens (1–128 characters). Names starting with
+`Camel`, regardless of case, are reserved for endpoint control and rejected.
+
+`setBody` and `setHeader` require exactly one of:
+
+- `constant`: a quoted YAML string, used literally without placeholder expansion.
+- `simple`: exactly `${body}` or `${body[field]}`. The latter reads one top-level
+ map key containing ASCII letters, digits, underscores or hyphens. It returns
+ null for an absent key or a non-map body. No methods, nested access or string
+ interpolation are evaluated.
+
+```yaml
+- setHeader:
+ name: example
+ simple: "${body[myField]}"
+- setBody:
+ constant: "literal payload"
+- removeHeader:
+ name: temporary
+```
+
+All other steps, options, expression languages, user-selected endpoints and nested
+DSL constructs are rejected before installing the route. YAML must contain a
+single document; duplicate keys and aliases are rejected. Limits are 16,384 Java
+string characters, 64 steps and four collection levels.
+
+This is a restricted data transformation interpreter, not a sandbox for arbitrary
+Camel code. Installed Kamelet templates, their components, endpoint parameters
+and extension code remain trusted and are not constrained by this interpreter.
+Previously accepted transforms outside this subset must be replaced with supported
+data mappings or implemented in an operator-reviewed extension.
diff --git a/streampipes-extensions/streampipes-connectors-camel/pom.xml b/streampipes-extensions/streampipes-connectors-camel/pom.xml
index 4aa99b958f..c1152e086d 100644
--- a/streampipes-extensions/streampipes-connectors-camel/pom.xml
+++ b/streampipes-extensions/streampipes-connectors-camel/pom.xml
@@ -67,6 +67,7 @@
<groupId>org.apache.camel</groupId>
<artifactId>camel-kamelet</artifactId>
</dependency>
+ <!-- Required for installed Kamelet templates, never for user transform fragments. -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-yaml-dsl</artifactId>
@@ -79,6 +80,16 @@
<groupId>org.hdrhistogram</groupId>
<artifactId>HdrHistogram</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-params</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
diff --git a/streampipes-extensions/streampipes-connectors-camel/src/main/java/org/apache/streampipes/extensions/connectors/camel/kamelet/config/KameletSinkStaticPropertyProvider.java b/streampipes-extensions/streampipes-connectors-camel/src/main/java/org/apache/streampipes/extensions/connectors/camel/kamelet/config/KameletSinkStaticPropertyProvider.java
index 7c160d625b..b1453f8302 100644
--- a/streampipes-extensions/streampipes-connectors-camel/src/main/java/org/apache/streampipes/extensions/connectors/camel/kamelet/config/KameletSinkStaticPropertyProvider.java
+++ b/streampipes-extensions/streampipes-connectors-camel/src/main/java/org/apache/streampipes/extensions/connectors/camel/kamelet/config/KameletSinkStaticPropertyProvider.java
@@ -194,7 +194,8 @@ public class KameletSinkStaticPropertyProvider {
Labels.from(
ADVANCED_TRANSFORM_STEPS_KEY,
"Transform Steps (YAML)",
- "Provide a Camel YAML steps fragment that runs before the message is sent to the Kamelet."
+ "Use setBody, setHeader or removeHeader; string constant or simple ${body}/${body[field]} only. "
+ + "Camel control headers and other Camel DSL constructs are not supported."
),
CodeLanguage.None,
"""
diff --git a/streampipes-extensions/streampipes-connectors-camel/src/main/java/org/apache/streampipes/extensions/connectors/camel/kamelet/transform/KameletTransformRouteLoader.java b/streampipes-extensions/streampipes-connectors-camel/src/main/java/org/apache/streampipes/extensions/connectors/camel/kamelet/transform/KameletTransformRouteLoader.java
index 3f7ec7ab46..1da3cff14f 100644
--- a/streampipes-extensions/streampipes-connectors-camel/src/main/java/org/apache/streampipes/extensions/connectors/camel/kamelet/transform/KameletTransformRouteLoader.java
+++ b/streampipes-extensions/streampipes-connectors-camel/src/main/java/org/apache/streampipes/extensions/connectors/camel/kamelet/transform/KameletTransformRouteLoader.java
@@ -22,157 +22,158 @@ import org.apache.streampipes.commons.exceptions.SpConfigurationException;
import org.apache.streampipes.commons.exceptions.SpRuntimeException;
import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
-import org.apache.camel.dsl.yaml.YamlRoutesBuilderLoader;
-import org.apache.camel.spi.Resource;
import org.snakeyaml.engine.v2.api.Load;
import org.snakeyaml.engine.v2.api.LoadSettings;
+import org.snakeyaml.engine.v2.api.lowlevel.Parse;
+import org.snakeyaml.engine.v2.exceptions.YamlEngineException;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+/**
+ * Interprets a deliberately small data-only subset of Camel YAML.
+ * Never pass user configuration to Camel's DSL or expression loaders: those execute trusted code.
+ * The entry and destination URIs must be supplied by the installed extension, not by this fragment.
+ */
public class KameletTransformRouteLoader {
- private static final Load YAML_LOADER = new Load(LoadSettings.builder().build());
- private static final Set<String> FORBIDDEN_KEYS = Set.of(
- "route",
- "from",
- "templatedRoute",
- "routeTemplate",
- "routeConfiguration",
- "routeConfigurations",
- "rest",
- "beans"
- );
+ private static final int MAX_LENGTH = 16_384;
+ private static final int MAX_STEPS = 64;
+ private static final LoadSettings SETTINGS = LoadSettings.builder()
+ .setAllowDuplicateKeys(false)
+ .setMaxAliasesForCollections(0)
+ .setCodePointLimit(MAX_LENGTH)
+ .build();
+ private static final Pattern FIELD_EXPRESSION = Pattern.compile("\\$\\{body\\[([a-zA-Z0-9_-]+)]}");
+ private static final Pattern HEADER_NAME = Pattern.compile("[a-zA-Z0-9_-]{1,128}");
public void addRoute(CamelContext camelContext,
String routeId,
String fromUri,
String toUri,
String transformStepsYaml) throws Exception {
- if (transformStepsYaml == null || transformStepsYaml.isBlank()) {
- camelContext.addRoutes(new RouteBuilder() {
- @Override
- public void configure() {
- from(fromUri)
- .routeId(routeId)
- .to(toUri);
- }
- });
- return;
- }
-
- validateSteps(transformStepsYaml);
-
- YamlRoutesBuilderLoader loader = new YamlRoutesBuilderLoader();
- loader.setCamelContext(camelContext);
-
- camelContext.addRoutes(loader.doLoadRouteBuilder(new InMemoryResource(
- "in-memory:" + routeId + ".yaml",
- buildRouteYaml(routeId, fromUri, toUri, transformStepsYaml)
- )));
+ // Validate the complete fragment before registering any route or running any processor.
+ List<Processor> steps = parseSteps(transformStepsYaml);
+ camelContext.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(fromUri)
+ .routeId(routeId)
+ .process(exchange -> {
+ for (Processor step : steps) {
+ step.process(exchange);
+ }
+ })
+ .to(toUri);
+ }
+ });
}
- private void validateSteps(String transformStepsYaml) {
- Object parsed = YAML_LOADER.loadFromString(transformStepsYaml);
- if (!(parsed instanceof List<?> list)) {
- throw new SpRuntimeException(new SpConfigurationException(
- "Advanced transform steps must be a YAML list of Camel steps."
- ));
+ private List<Processor> parseSteps(String yaml) {
+ if (yaml == null || yaml.isBlank()) {
+ return List.of();
}
-
- validateNode(list);
- }
-
- private void validateNode(Object node) {
- if (node instanceof List<?> list) {
- list.forEach(this::validateNode);
- } else if (node instanceof Map<?, ?> map) {
- for (Map.Entry<?, ?> entry : map.entrySet()) {
- String key = String.valueOf(entry.getKey());
- if (FORBIDDEN_KEYS.contains(key)) {
- throw new SpRuntimeException(new SpConfigurationException(
- "Advanced transform steps may not declare Camel routes, beans or from clauses."
- ));
+ if (yaml.length() > MAX_LENGTH) {
+ throw invalid();
+ }
+ Object parsed;
+ try {
+ // Bound nesting before constructing collections, and disallow all aliases (including scalars).
+ int depth = 0;
+ for (var event : new Parse(SETTINGS).parseString(yaml)) {
+ switch (event.getEventId()) {
+ case MappingStart, SequenceStart -> {
+ if (++depth > 4) {
+ throw invalid();
+ }
+ }
+ case MappingEnd, SequenceEnd -> depth--;
+ case Alias -> throw invalid();
+ default -> { }
}
- validateNode(entry.getValue());
}
+ parsed = new Load(SETTINGS).loadFromString(yaml);
+ } catch (YamlEngineException e) {
+ // Do not expose configuration values or parser snippets in errors.
+ throw invalid();
}
- }
-
- private String buildRouteYaml(String routeId,
- String fromUri,
- String toUri,
- String transformStepsYaml) {
- return """
- - route:
- id: '%s'
- from:
- uri: '%s'
- steps:
- %s
- - to:
- uri: '%s'
- """.formatted(
- escapeYaml(routeId),
- escapeYaml(fromUri),
- indentSteps(transformStepsYaml),
- escapeYaml(toUri)
- );
- }
-
- private String indentSteps(String transformStepsYaml) {
- StringBuilder builder = new StringBuilder();
- String[] lines = transformStepsYaml.replace("\r\n", "\n").split("\n", -1);
-
- for (String line : lines) {
- if (line.isBlank()) {
- builder.append('\n');
- } else {
- builder.append(" ").append(line).append('\n');
+ if (!(parsed instanceof List<?> list) || list.size() > MAX_STEPS) {
+ throw invalid();
+ }
+ List<Processor> steps = new ArrayList<>();
+ for (Object item : list) {
+ if (!(item instanceof Map<?, ?> step) || step.size() != 1) {
+ throw invalid();
+ }
+ var entry = step.entrySet().iterator().next();
+ if (!(entry.getValue() instanceof Map<?, ?> options)) {
+ throw invalid();
+ }
+ switch (String.valueOf(entry.getKey())) {
+ case "setBody", "set-body" -> {
+ Function<Exchange, Object> value = expression(options, false);
+ steps.add(exchange -> exchange.getMessage().setBody(value.apply(exchange)));
+ }
+ case "setHeader", "set-header" -> {
+ String name = headerName(options);
+ Function<Exchange, Object> value = expression(options, true);
+ steps.add(exchange -> exchange.getMessage().setHeader(name, value.apply(exchange)));
+ }
+ case "removeHeader", "remove-header" -> {
+ if (!options.keySet().equals(Set.of("name"))) {
+ throw invalid();
+ }
+ String name = headerName(options);
+ steps.add(exchange -> exchange.getMessage().removeHeader(name));
+ }
+ default -> throw invalid();
}
}
-
- return builder.toString();
- }
-
- private String escapeYaml(String value) {
- return value.replace("'", "''");
+ return List.copyOf(steps);
}
- private static final class InMemoryResource implements Resource {
-
- private final String location;
- private final byte[] content;
-
- private InMemoryResource(String location,
- String content) {
- this.location = location;
- this.content = content.getBytes(StandardCharsets.UTF_8);
+ private Function<Exchange, Object> expression(Map<?, ?> options, boolean header) {
+ String language = options.containsKey("constant") ? "constant" : "simple";
+ Set<String> keys = header ? Set.of("name", language) : Set.of(language);
+ if (!options.keySet().equals(keys) || !(options.get(language) instanceof String value)) {
+ throw invalid();
}
-
- @Override
- public String getScheme() {
- return "in-memory";
+ if (language.equals("constant")) {
+ return exchange -> value;
}
-
- @Override
- public String getLocation() {
- return location;
+ // Compatibility with the shipped example, without Simple/OGNL, property or bean resolution.
+ if (value.equals("${body}")) {
+ return exchange -> exchange.getMessage().getBody();
}
-
- @Override
- public boolean exists() {
- return true;
+ var matcher = FIELD_EXPRESSION.matcher(value);
+ if (!matcher.matches()) {
+ throw invalid();
}
+ String field = matcher.group(1);
+ return exchange -> exchange.getMessage().getBody() instanceof Map<?, ?> body ? body.get(field) : null;
+ }
- @Override
- public InputStream getInputStream() {
- return new ByteArrayInputStream(content);
+ private String headerName(Map<?, ?> options) {
+ if (!(options.get("name") instanceof String name) || !HEADER_NAME.matcher(name).matches()
+ || name.regionMatches(true, 0, "Camel", 0, 5)) {
+ // Camel-prefixed headers can override endpoint operations, destinations and other control options.
+ throw invalid();
}
+ return name;
+ }
+
+ private SpRuntimeException invalid() {
+ return new SpRuntimeException(new SpConfigurationException(
+ "Transform YAML supports only setBody, setHeader and removeHeader with literal string constants "
+ + "or simple ${body}/${body[field]} references. Camel control headers, other DSL constructs, "
+ + "aliases and oversized fragments are not allowed."
+ ));
}
}
diff --git a/streampipes-extensions/streampipes-connectors-camel/src/test/java/org/apache/streampipes/extensions/connectors/camel/kamelet/transform/KameletTransformRouteLoaderTest.java b/streampipes-extensions/streampipes-connectors-camel/src/test/java/org/apache/streampipes/extensions/connectors/camel/kamelet/transform/KameletTransformRouteLoaderTest.java
new file mode 100644
index 0000000000..e861fc1556
--- /dev/null
+++ b/streampipes-extensions/streampipes-connectors-camel/src/test/java/org/apache/streampipes/extensions/connectors/camel/kamelet/transform/KameletTransformRouteLoaderTest.java
@@ -0,0 +1,243 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.extensions.connectors.camel.kamelet.transform;
+
+import org.apache.streampipes.commons.exceptions.SpRuntimeException;
+import org.apache.streampipes.dataformat.JsonDataFormatDefinition;
+import org.apache.streampipes.extensions.connectors.camel.kamelet.message.KameletEventMessageMapper;
+import org.apache.streampipes.extensions.connectors.camel.kamelet.message.KameletHeaderMapping;
+import org.apache.streampipes.extensions.connectors.camel.kamelet.message.KameletMessageMapping;
+import org.apache.streampipes.model.runtime.Event;
+import org.apache.streampipes.model.runtime.field.PrimitiveField;
+
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class KameletTransformRouteLoaderTest {
+
+ private final KameletTransformRouteLoader loader = new KameletTransformRouteLoader();
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @ValueSource(strings = {" ", "[]"})
+ void forwardsWithoutTransform(String yaml) throws Exception {
+ try (var context = context()) {
+ loader.addRoute(context, "transform", "direct:input", "direct:output", yaml);
+ context.start();
+ try (var producer = context.createProducerTemplate()) {
+ assertEquals("original", producer.requestBody("direct:input", "original"));
+ }
+ }
+ }
+
+ @Test
+ void appliesDataOnlyStepsAndDeliversToConfiguredDestination() throws Exception {
+ try (var context = context()) {
+ loader.addRoute(context, "transform", "direct:input", "direct:output", """
+ - setHeader:
+ name: example
+ simple: "${body[myField]}"
+ - set-header:
+ name: literal
+ constant: "{{env:PRIVATE}} ${bean:unused}"
+ - setHeader:
+ name: temporary
+ constant: "remove me"
+ - remove-header:
+ name: temporary
+ - set-body:
+ simple: "${body[myField]}"
+ """);
+ context.start();
+ try (var producer = context.createProducerTemplate()) {
+ var result = producer.request("direct:input", exchange ->
+ exchange.getMessage().setBody(Map.of("myField", "value")));
+ assertNull(result.getException());
+ assertEquals("value", result.getMessage().getBody());
+ assertEquals("value", result.getMessage().getHeader("example"));
+ assertEquals("{{env:PRIVATE}} ${bean:unused}", result.getMessage().getHeader("literal"));
+ assertNull(result.getMessage().getHeader("temporary"));
+ assertEquals(true, result.getMessage().getHeader("delivered"));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "- setBody: {constant: 'literal'}",
+ "- setBody: {simple: '${body}'}"
+ })
+ void supportsBodyAssignment(String yaml) throws Exception {
+ try (var context = context()) {
+ loader.addRoute(context, "transform", "direct:input", "direct:output", yaml);
+ context.start();
+ try (var producer = context.createProducerTemplate()) {
+ assertEquals(yaml.contains("constant") ? "literal" : "original",
+ producer.requestBody("direct:input", "original"));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {
+ "- setBody: {simple: '${type:java.lang.System}'}",
+ "- setHeader: {name: value, simple: '${bean:untrusted}'}",
+ "- setBody: {simple: '${body.getClass()}'}",
+ "- setBody: {simple: '${body[myField].getClass()}'}",
+ "- setBody: {simple: '{{untrusted}}'}",
+ "- setBody: {simple: '$simple{body}'}",
+ "- setBody: {groovy: 'return 1'}",
+ "- setBody: {expression: {simple: '${body}'}}",
+ "- setBody: {constant: 'value', simple: '${body}'}",
+ "- setBody: {constant: {value: nested}}",
+ "- setBody: {constant: 42}",
+ "- setHeader: {name: CamelHttpUri, constant: 'unused'}",
+ "- setHeader: {name: cAmElControl, constant: 'unused'}",
+ "- setHeader: {name: '{{name}}', constant: 'unused'}",
+ "- bean: {ref: untrusted}",
+ "- process: {ref: untrusted}",
+ "- to: {uri: 'bean:untrusted'}",
+ "- to: {uri: 'class:java.lang.String'}",
+ "- to: {uri: 'direct:other'}",
+ "- toD: '${body}'",
+ "- script: {groovy: 'return 1'}",
+ "- choice: {when: [{simple: 'true', steps: [{to: 'direct:other'}]}]}",
+ "- route: {from: 'direct:other'}",
+ "- beans: []",
+ "- unknown: {}",
+ "- setBody: {constant: one, constant: two}",
+ "- &step setBody: {constant: value}\n- *step",
+ "- setBody: {constant: &value literal}\n- setBody: {constant: *value}",
+ "- setBody: {constant: !!java.lang.String value}",
+ "- setBody: {constant: value}\n---\n- setBody: {constant: other}",
+ "setBody: {constant: value}",
+ "- setBody: {constant: value}\n removeHeader: {name: other}",
+ "- setBody: [",
+ "- null"
+ })
+ void rejectsUnsupportedConfigurationBeforeInstallingAnyRoute(String yaml) throws Exception {
+ try (var context = new DefaultCamelContext()) {
+ // Even a valid prefix must not be installed when a later step is invalid.
+ assertThrows(SpRuntimeException.class, () -> loader.addRoute(context, "transform",
+ "direct:input", "direct:output", "- setBody: {constant: valid}\n" + yaml));
+ assertTrue(context.getRouteDefinitions().isEmpty());
+ assertTrue(context.getEndpoints().isEmpty());
+ }
+ }
+
+ @Test
+ void rejectsExcessiveSizeStepCountAndNesting() throws Exception {
+ for (String yaml : new String[] {
+ "- setBody: {constant: '" + "x".repeat(16_384) + "'}",
+ "- setBody: {constant: value}\n".repeat(65),
+ "[".repeat(100) + "]".repeat(100)
+ }) {
+ try (var context = new DefaultCamelContext()) {
+ assertThrows(SpRuntimeException.class, () -> loader.addRoute(context, "transform",
+ "direct:input", "direct:output", yaml));
+ assertTrue(context.getRouteDefinitions().isEmpty());
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(KameletMessageMapping.PayloadMode.class)
+ void preservesExistingMessageMapping(KameletMessageMapping.PayloadMode mode) throws Exception {
+ var event = new Event();
+ event.addField(new PrimitiveField("myField", "myField", "value"));
+ String selector = event.getFields().keySet().iterator().next();
+ var mapping = new KameletMessageMapping(mode, selector,
+ List.of(new KameletHeaderMapping("mapped", selector)), null);
+ var message = new KameletEventMessageMapper().mapEvent(event, mapping, new JsonDataFormatDefinition());
+ try (var context = context()) {
+ loader.addRoute(context, "transform", "direct:input", "direct:output", null);
+ context.start();
+ try (var producer = context.createProducerTemplate()) {
+ var result = producer.request("direct:input", exchange -> {
+ exchange.getMessage().setBody(message.body());
+ exchange.getMessage().setHeaders(message.headers());
+ });
+ assertNull(result.getException());
+ assertEquals(message.body(), result.getMessage().getBody());
+ assertEquals("value", result.getMessage().getHeader("mapped"));
+ assertEquals(message.headers().get(KameletEventMessageMapper.EVENT_JSON_HEADER),
+ result.getMessage().getHeader(KameletEventMessageMapper.EVENT_JSON_HEADER));
+ assertEquals(true, result.getMessage().getHeader("delivered"));
+ }
+ }
+ }
+
+ @Test
+ void deliversThroughAnInstalledKameletTemplate() throws Exception {
+ try (var context = context()) {
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ routeTemplate("local-sink").from("kamelet:source").to("direct:output");
+ }
+ });
+ loader.addRoute(context, "transform", "direct:input", "kamelet:local-sink", """
+ - setBody:
+ simple: "${body[myField]}"
+ """);
+ context.start();
+ try (var producer = context.createProducerTemplate()) {
+ var result = producer.request("direct:input", exchange ->
+ exchange.getMessage().setBody(Map.of("myField", "value")));
+ assertNull(result.getException());
+ assertEquals("value", result.getMessage().getBody());
+ assertEquals(true, result.getMessage().getHeader("delivered"));
+ }
+ }
+ }
+
+ @Test
+ void reportsInvalidYamlWithoutEchoingConfiguration() throws Exception {
+ try (var context = new DefaultCamelContext()) {
+ var error = assertThrows(SpRuntimeException.class, () -> loader.addRoute(context, "transform",
+ "direct:input", "direct:output", "- setBody: {constant: private-value, constant: duplicate}"));
+ assertTrue(error.getMessage().contains("setBody"));
+ assertTrue(!error.getMessage().contains("private-value"));
+ }
+ }
+
+ private DefaultCamelContext context() throws Exception {
+ var context = new DefaultCamelContext();
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:output").process(exchange -> exchange.getMessage().setHeader("delivered", true));
+ }
+ });
+ return context;
+ }
+}