diff --git a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/HeaderEnricher.java b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/HeaderEnricher.java index 28f3f265f..9d3290efc 100644 --- a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/HeaderEnricher.java +++ b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/HeaderEnricher.java @@ -18,6 +18,7 @@ import java.util.Map; import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import org.apache.commons.logging.Log; @@ -50,6 +51,8 @@ class HeaderEnricher implements Function { private final SpelExpressionParser spelParser = new SpelExpressionParser(); + private final Map expressionCache = new ConcurrentHashMap<>(); + private final StandardEvaluationContext evalContext = new StandardEvaluationContext(); @SuppressWarnings("unchecked") @@ -65,25 +68,29 @@ class HeaderEnricher implements Function { @Override public Object apply(Object input) { if (input instanceof Message) { - MessageBuilder messageBuilder = MessageBuilder.fromMessage((Message) input); Map mappings = this.headerExpressions.get("0"); - for (Entry keyValueExpressionEntry : mappings.entrySet()) { - Expression expression = this.spelParser.parseExpression(keyValueExpressionEntry.getValue()); - try { - Object value = expression.getValue(this.evalContext, input, Object.class); - messageBuilder.setHeader(keyValueExpressionEntry.getKey(), value); - } - catch (Exception e) { - String message = "Failed while evaluating expression \"" + keyValueExpressionEntry.getValue() + "\" on incoming message"; - if (logger.isDebugEnabled()) { - logger.warn(message + ": " + input, e); + if (mappings != null && !mappings.isEmpty()) { + MessageBuilder messageBuilder = MessageBuilder.fromMessage((Message) input); + for (Entry keyValueExpressionEntry : mappings.entrySet()) { + Expression expression = this.expressionCache.computeIfAbsent(keyValueExpressionEntry.getValue(), + this.spelParser::parseExpression); + try { + Object value = expression.getValue(this.evalContext, input, Object.class); + messageBuilder.setHeader(keyValueExpressionEntry.getKey(), value); } - else { - logger.warn(message); + catch (Exception e) { + String message = "Failed while evaluating expression \"" + keyValueExpressionEntry.getValue() + + "\" on incoming message"; + if (logger.isDebugEnabled()) { + logger.warn(message, e); + } + else { + logger.warn(message); + } } } + input = messageBuilder.build(); } - input = messageBuilder.build(); } return input; diff --git a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/RoutingFunction.java b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/RoutingFunction.java index b7dbf17d9..41960a2b9 100644 --- a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/RoutingFunction.java +++ b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/RoutingFunction.java @@ -16,6 +16,8 @@ package org.springframework.cloud.function.context.config; +import java.util.Collections; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -42,6 +44,7 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.messaging.Message; import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** @@ -66,6 +69,8 @@ public class RoutingFunction implements Function { */ public static final String DEFAULT_ROUTE_HANDLER = "defaultMessageRoutingHandler"; + private static final int EXPRESSION_CACHE_MAX_SIZE = 256; + private static final Log logger = LogFactory.getLog(RoutingFunction.class); private final StandardEvaluationContext evalContext = new StandardEvaluationContext(); @@ -75,6 +80,14 @@ public class RoutingFunction implements Function { private final SpelExpressionParser spelParser = new SpelExpressionParser(); + private final Map expressionCache = Collections.synchronizedMap( + new LinkedHashMap<>(16, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > EXPRESSION_CACHE_MAX_SIZE; + } + }); + private final FunctionCatalog functionCatalog; private final FunctionProperties functionProperties; @@ -151,7 +164,9 @@ else if (StringUtils.hasText(functionProperties.getDefinition())) { else { throw new IllegalStateException("Failed to establish route, since neither were provided: " + "'spring.cloud.function.definition' as Message header or as application property or " - + "'spring.cloud.function.routing-expression' as application property. Incoming message: " + input); + + "'spring.cloud.function.routing-expression' as application property. Incoming message payload type: " + + ObjectUtils.nullSafeClassName(message.getPayload()) + ", headers: " + + message.getHeaders().keySet()); } } } @@ -242,22 +257,31 @@ private FunctionInvocationWrapper functionFromExpression(String routingExpressio } private FunctionInvocationWrapper functionFromExpression(String routingExpression, Object input, boolean isViaHeader) { - Expression expression = spelParser.parseExpression(routingExpression); + Expression expression = this.parseExpression(routingExpression); if (input instanceof Message) { input = MessageUtils.toCaseInsensitiveHeadersStructure((Message) input); } String definition = isViaHeader ? expression.getValue(this.headerEvalContext, input, String.class) : expression.getValue(this.evalContext, input, String.class); - Assert.hasText(definition, "Failed to resolve function name based on routing expression '" + functionProperties.getRoutingExpression() + "'"); + Assert.hasText(definition, "Failed to resolve function name based on routing expression '" + routingExpression + "'"); FunctionInvocationWrapper function = this.resolveFunction(definition); Assert.notNull(function, "Failed to lookup function to route to based on the expression '" - + functionProperties.getRoutingExpression() + "' which resolved to '" + definition + "' function definition."); + + routingExpression + "' which resolved to '" + definition + "' function definition."); if (logger.isDebugEnabled()) { logger.debug("Resolved function from provided [routing-expression] " + routingExpression); } return function; } + private Expression parseExpression(String routingExpression) { + Expression expression = this.expressionCache.get(routingExpression); + if (expression == null) { + expression = this.spelParser.parseExpression(routingExpression); + this.expressionCache.put(routingExpression, expression); + } + return expression; + } + private FunctionInvocationWrapper resolveFunction(String definition) { FunctionInvocationWrapper function = functionCatalog.lookup(definition); if (function == null) { diff --git a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/catalog/HeaderEnricherTests.java b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/catalog/HeaderEnricherTests.java new file mode 100644 index 000000000..d6fb06beb --- /dev/null +++ b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/catalog/HeaderEnricherTests.java @@ -0,0 +1,94 @@ +/* + * Copyright 2026-present the original author or authors. + * + * Licensed 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 + * + * https://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.springframework.cloud.function.context.catalog; + +import java.util.Map; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.LoggerFactory; + +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +import org.springframework.expression.Expression; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit tests for {@link HeaderEnricher}. + * + * @author Divyansh Kumar + */ +@ExtendWith(OutputCaptureExtension.class) +class HeaderEnricherTests { + + @Test + void testMissingZeroIndexIsSkipped() { + HeaderEnricher enricher = new HeaderEnricher(Map.of("1", Map.of("k", "'v'")), null); + Message input = MessageBuilder.withPayload("hello").build(); + + Object result = enricher.apply(input); + + assertThat(result).isSameAs(input); + } + + @SuppressWarnings("unchecked") + @Test + void testExpressionIsCachedAcrossMessages() { + HeaderEnricher enricher = new HeaderEnricher(Map.of("0", Map.of("enriched", "'ok'")), null); + + Message first = (Message) enricher.apply(MessageBuilder.withPayload("a").build()); + Map cache = (Map) ReflectionTestUtils.getField(enricher, + "expressionCache"); + assertThat(cache).containsOnlyKeys("'ok'"); + Expression firstParsed = cache.get("'ok'"); + + Message second = (Message) enricher.apply(MessageBuilder.withPayload("b").build()); + assertThat(first.getHeaders().get("enriched")).isEqualTo("ok"); + assertThat(second.getHeaders().get("enriched")).isEqualTo("ok"); + assertThat(cache.get("'ok'")).isSameAs(firstParsed); + } + + @Test + void testEvaluationFailureDoesNotLogMessageContent(CapturedOutput output) { + Logger logger = (Logger) LoggerFactory.getLogger(HeaderEnricher.class); + Level previousLevel = logger.getLevel(); + logger.setLevel(Level.DEBUG); + try { + HeaderEnricher enricher = new HeaderEnricher(Map.of("0", Map.of("broken", "headers['missing'].value")), + null); + Message input = MessageBuilder.withPayload("secret-body") + .setHeader("Authorization", "Bearer top-secret") + .build(); + + enricher.apply(input); + + assertThat(output.getOut()).contains("Failed while evaluating expression"); + assertThat(output.getOut()).doesNotContain("secret-body"); + assertThat(output.getOut()).doesNotContain("Bearer top-secret"); + } + finally { + logger.setLevel(previousLevel); + } + } + +} diff --git a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/RoutingFunctionTests.java b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/RoutingFunctionTests.java index df0786d16..8613841cc 100644 --- a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/RoutingFunctionTests.java +++ b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/RoutingFunctionTests.java @@ -41,8 +41,11 @@ import org.springframework.lang.Nullable; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; /** * @@ -378,6 +381,64 @@ public void testMultipleRoutersCaseInsensitiveKeys() { assertThat(function.apply(message)).isEqualTo("HELLO"); } + @SuppressWarnings("rawtypes") + @Test + public void testUnroutableMessageDoesNotExposePayloadOrHeaderValues() { + FunctionCatalog functionCatalog = this.configureCatalog(); + Function function = functionCatalog.lookup(RoutingFunction.FUNCTION_NAME); + Message message = MessageBuilder.withPayload("secret-payload") + .setHeader("Authorization", "Bearer secret-token") + .build(); + + assertThatIllegalStateException().isThrownBy(() -> function.apply(message)) + .withMessageContaining("java.lang.String") + .withMessageContaining("Authorization") + .withMessageNotContaining("secret-payload") + .withMessageNotContaining("Bearer secret-token"); + } + + @SuppressWarnings("rawtypes") + @Test + public void testHeaderRoutingExpressionFailureReportsEvaluatedExpression() { + FunctionCatalog functionCatalog = this.configureCatalog(); + Function function = functionCatalog.lookup(RoutingFunction.FUNCTION_NAME); + + Message emptyResultMessage = MessageBuilder.withPayload("hello") + .setHeader(FunctionProperties.ROUTING_EXPRESSION, "''") + .build(); + assertThatIllegalArgumentException().isThrownBy(() -> function.apply(emptyResultMessage)) + .withMessageContaining("''") + .withMessageNotContaining("'null'"); + + Message unknownFunctionMessage = MessageBuilder.withPayload("hello") + .setHeader(FunctionProperties.ROUTING_EXPRESSION, "'nonExistentFn'") + .build(); + assertThatIllegalArgumentException().isThrownBy(() -> function.apply(unknownFunctionMessage)) + .withMessageContaining("'nonExistentFn'") + .withMessageNotContaining("'null'"); + } + + @SuppressWarnings("unchecked") + @Test + public void testRoutingExpressionCacheBounded() { + FunctionCatalog functionCatalog = this.configureCatalog(); + RoutingFunction router = this.context.getBean(RoutingFunction.class); + assertThat(functionCatalog).isNotNull(); + + for (int i = 0; i < 260; i++) { + String expr = "headers['k'] == '" + i + "' ? 'uppercase' : 'uppercase'"; + Message message = MessageBuilder.withPayload("hello") + .setHeader("k", String.valueOf(i)) + .setHeader(FunctionProperties.ROUTING_EXPRESSION, expr) + .build(); + assertThat(router.apply(message)).isEqualTo("HELLO"); + } + + Map cache = (Map) ReflectionTestUtils.getField(router, "expressionCache"); + assertThat(cache).isNotNull(); + assertThat(cache).hasSize(256); + } + @EnableAutoConfiguration @Configuration protected static class RoutingFunctionConfiguration {