From 8c1ae77406fa9644475e180d90db38c06e74f4ad Mon Sep 17 00:00:00 2001 From: seonwoo_jung <79202163+seonwooj0810@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:19:45 +0900 Subject: [PATCH] GH-1564 Make JsonMessageConverter failure handling null safe and stop logging payloads A failed conversion of a byte[] payload with no target class (allowed when the content type carries a `type` parameter) no longer fails with a NullPointerException in the String fallback, and returns null instead. The debug message of a failed conversion now names the payload type and the target type rather than the payload itself. A `type` parameter that is not listed in META-INF/deserializable.types, or used while no allow-list is present at all, is now reported at debug level when it is ignored. The allow-list is kept in a Set and blank entries are skipped. Resolves #1564 Signed-off-by: seonwoo_jung <79202163+seonwooj0810@users.noreply.github.com> --- .../context/config/JsonMessageConverter.java | 45 ++++++----- ...ssageConverterAllowlistPackagingTests.java | 42 +++++++++++ .../config/JsonMessageConverterTests.java | 74 +++++++++++++++++++ 3 files changed, 137 insertions(+), 24 deletions(-) diff --git a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/JsonMessageConverter.java b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/JsonMessageConverter.java index fe268ab98..25140dc57 100644 --- a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/JsonMessageConverter.java +++ b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/JsonMessageConverter.java @@ -22,9 +22,9 @@ import java.lang.reflect.Type; import java.net.URL; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.Enumeration; -import java.util.List; +import java.util.LinkedHashSet; +import java.util.Set; import org.springframework.cloud.function.cloudevent.CloudEventMessageUtils; import org.springframework.cloud.function.json.JsonMapper; @@ -37,7 +37,6 @@ import org.springframework.messaging.converter.AbstractMessageConverter; import org.springframework.messaging.converter.MessageConverter; import org.springframework.util.ClassUtils; -import org.springframework.util.CollectionUtils; import org.springframework.util.MimeType; import org.springframework.util.StringUtils; @@ -54,7 +53,7 @@ public class JsonMessageConverter extends AbstractMessageConverter { private final JsonMapper jsonMapper; - private final List deserializableTypes = new ArrayList<>(); + private final Set deserializableTypes = new LinkedHashSet<>(); public JsonMessageConverter(JsonMapper jsonMapper) { this(jsonMapper, new MimeType("application", "json"), new MimeType(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getType(), @@ -78,8 +77,10 @@ public JsonMessageConverter(JsonMapper jsonMapper, MimeType... supportedMimeType for (String line : reader.lines().toList()) { // need to split in case if delimited String[] keys = line.split(","); - for (int i = 0; i < keys.length; i++) { - this.deserializableTypes.add(keys[i].trim()); + for (String key : keys) { + if (StringUtils.hasText(key)) { + this.deserializableTypes.add(key.trim()); + } } } } @@ -120,22 +121,21 @@ protected Object convertFromInternal(Message message, Class targetClass, @ } Type convertToType = this.getResolvedType(targetClass, conversionHint); if (convertToType == null || convertToType == Object.class) { - if (!CollectionUtils.isEmpty(this.deserializableTypes)) { - MimeType mimeType = getMimeType(message.getHeaders()); - String type = mimeType != null ? mimeType.getParameter("type") : null; - if (StringUtils.hasText(type) && this.deserializableTypes.contains(type)) { - try { - convertToType = this.loadClass(type); - } - catch (ClassNotFoundException | LinkageError e) { - throw new IllegalArgumentException("Failed to load class `" + type + "` specified by the provided content-type: " + mimeType, e); - } + MimeType mimeType = getMimeType(message.getHeaders()); + String type = mimeType != null ? mimeType.getParameter("type") : null; + if (StringUtils.hasText(type) && this.deserializableTypes.contains(type)) { + try { + convertToType = this.loadClass(type); } - else { - return message.getPayload(); + catch (ClassNotFoundException | LinkageError e) { + throw new IllegalArgumentException("Failed to load class `" + type + "` specified by the provided content-type: " + mimeType, e); } } else { + if (StringUtils.hasText(type) && logger.isDebugEnabled()) { + logger.debug("Ignoring type `" + type + "` specified by the provided content-type, since it is not listed " + + "in any META-INF/deserializable.types resource; passing the payload on as is"); + } return message.getPayload(); } } @@ -147,15 +147,12 @@ protected Object convertFromInternal(Message message, Class targetClass, @ return this.jsonMapper.fromJson(message.getPayload(), convertToType); } catch (Exception e) { - if (message.getPayload() instanceof byte[] && String.class.isAssignableFrom(targetClass)) { + if (message.getPayload() instanceof byte[] && targetClass != null && String.class.isAssignableFrom(targetClass)) { return new String((byte[]) message.getPayload(), StandardCharsets.UTF_8); } else if (logger.isDebugEnabled()) { - Object payload = message.getPayload(); - if (payload instanceof byte[]) { - payload = new String((byte[]) payload, StandardCharsets.UTF_8); - } - logger.debug("Failed to convert value: " + payload + " to: " + targetClass, e); + logger.debug("Failed to convert payload of type " + message.getPayload().getClass().getName() + + " to: " + convertToType, e); } } } diff --git a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/JsonMessageConverterAllowlistPackagingTests.java b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/JsonMessageConverterAllowlistPackagingTests.java index d5540819e..f3d2a68ca 100644 --- a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/JsonMessageConverterAllowlistPackagingTests.java +++ b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/JsonMessageConverterAllowlistPackagingTests.java @@ -26,18 +26,26 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; +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.junit.jupiter.api.io.TempDir; +import org.slf4j.LoggerFactory; import tools.jackson.databind.ObjectMapper; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.cloud.function.json.JacksonMapper; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.support.MessageBuilder; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.util.MimeTypeUtils; import static org.assertj.core.api.Assertions.assertThat; +@ExtendWith(OutputCaptureExtension.class) public class JsonMessageConverterAllowlistPackagingTests { private static final String ALLOWLIST = "META-INF/deserializable.types"; @@ -51,6 +59,40 @@ public void readsAllowlistFromDirectoryOnClasspath(@TempDir Path temp) throws Ex assertThat(convertWithAllowlistAt(directory.toUri().toURL())).isInstanceOf(Person.class); } + @Test + public void logsIgnoredTypeParameterWhenNoAllowlistIsPresent(@TempDir Path temp, CapturedOutput output) throws Exception { + Path directory = Files.createDirectories(temp.resolve("classes")); + Logger converterLogger = (Logger) LoggerFactory.getLogger(JsonMessageConverter.class); + Level originalLevel = converterLogger.getLevel(); + converterLogger.setLevel(Level.DEBUG); + try { + assertThat(convertWithAllowlistAt(directory.toUri().toURL())).isEqualTo("{\"name\":\"bill\"}"); + assertThat(output).contains("Ignoring type `" + Person.class.getName() + "`"); + } + finally { + converterLogger.setLevel(originalLevel); + } + } + + @Test + @SuppressWarnings("unchecked") + public void ignoresBlankAllowlistEntries(@TempDir Path temp) throws Exception { + Path directory = temp.resolve("classes"); + Path metaInf = Files.createDirectories(directory.resolve("META-INF")); + Files.writeString(metaInf.resolve("deserializable.types"), " , \n\n" + Person.class.getName() + ", ,\n"); + + ClassLoader original = Thread.currentThread().getContextClassLoader(); + try (URLClassLoader loader = allowlistLoader(directory.toUri().toURL())) { + Thread.currentThread().setContextClassLoader(loader); + JsonMessageConverter converter = new JsonMessageConverter(new JacksonMapper(new ObjectMapper())); + assertThat((Iterable) ReflectionTestUtils.getField(converter, "deserializableTypes")) + .containsExactly(Person.class.getName()); + } + finally { + Thread.currentThread().setContextClassLoader(original); + } + } + @Test public void readsAllowlistNestedInsideJarOnClasspath(@TempDir Path temp) throws Exception { URL jar = jarContainingAllowlist(temp.resolve("allowlist.jar"), Person.class.getName()); diff --git a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/JsonMessageConverterTests.java b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/JsonMessageConverterTests.java index c40d96101..d5ce1c6d2 100644 --- a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/JsonMessageConverterTests.java +++ b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/config/JsonMessageConverterTests.java @@ -16,9 +16,20 @@ package org.springframework.cloud.function.context.config; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.LoggerFactory; import tools.jackson.databind.ObjectMapper; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.cloud.function.json.JacksonMapper; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; @@ -27,14 +38,31 @@ import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatNoException; /** * * @author Oleg Zhurakousky * */ +@ExtendWith(OutputCaptureExtension.class) public class JsonMessageConverterTests { + private final Logger converterLogger = (Logger) LoggerFactory.getLogger(JsonMessageConverter.class); + + private Level originalLevel; + + @BeforeEach + public void enableDebugLogging() { + this.originalLevel = this.converterLogger.getLevel(); + this.converterLogger.setLevel(Level.DEBUG); + } + + @AfterEach + public void restoreLogging() { + this.converterLogger.setLevel(this.originalLevel); + } + @Test public void testTypeInference() { JsonMessageConverter converter = new JsonMessageConverter(new JacksonMapper(new ObjectMapper())); @@ -59,6 +87,52 @@ public void testTypeInference() { assertThat(converter.convertFromInternal(message, null, null)).isInstanceOf(Person.class); } + @Test + public void failedConversionOfByteArrayWithoutTargetClassReturnsNull() { + JsonMessageConverter converter = new JsonMessageConverter(new JacksonMapper(new ObjectMapper())); + Message message = MessageBuilder.withPayload("not json".getBytes(StandardCharsets.UTF_8)) + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON.toString() + ";type=" + Person.class.getName()).build(); + assertThat(converter.canConvertFrom(message, null)).isTrue(); + assertThat(converter.convertFromInternal(message, null, null)).isNull(); + } + + @Test + public void failedConversionOfByteArrayToStringReturnsPayloadAsString() { + JsonMessageConverter converter = new JsonMessageConverter(new JacksonMapper(new ObjectMapper())); + Message message = MessageBuilder.withPayload("not json".getBytes(StandardCharsets.UTF_8)) + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build(); + assertThat(converter.convertFromInternal(message, String.class, null)).isEqualTo("not json"); + } + + @Test + public void failedConversionDoesNotLogPayload(CapturedOutput output) { + JsonMessageConverter converter = new JsonMessageConverter(new JacksonMapper(new ObjectMapper())); + Message message = MessageBuilder.withPayload("{\"name\":\"top-secret-value\"".getBytes(StandardCharsets.UTF_8)) + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build(); + assertThat(converter.convertFromInternal(message, Person.class, null)).isNull(); + assertThat(output).contains("Failed to convert payload of type [B to: " + Person.class); + assertThat(output).doesNotContain("top-secret-value"); + } + + @Test + public void typeNotInAllowListIsIgnoredWithDebugMessage(CapturedOutput output) { + JsonMessageConverter converter = new JsonMessageConverter(new JacksonMapper(new ObjectMapper())); + Message message = MessageBuilder.withPayload("{\"name\":\"bill\"}") + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON.toString() + ";type=com.example.NotAllowed").build(); + assertThat(converter.convertFromInternal(message, null, null)).isEqualTo("{\"name\":\"bill\"}"); + assertThat(output).contains("Ignoring type `com.example.NotAllowed`") + .contains("META-INF/deserializable.types"); + } + + @Test + public void deeplyNestedJsonIsRejected() { + JsonMessageConverter converter = new JsonMessageConverter(new JacksonMapper(new ObjectMapper())); + String json = "{\"a\":".repeat(5000) + "1" + "}".repeat(5000); + Message message = MessageBuilder.withPayload(json) + .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON).build(); + assertThatNoException().isThrownBy(() -> assertThat(converter.convertFromInternal(message, Map.class, null)).isNull()); + } + public static class Person { private String name;