Skip to content

Commit ce3edbd

Browse files
committed
GH-1564 Make JsonMessageConverter failure handling null safe and stop logging payloads
A failed conversion of a byte[] payload without a known target class no longer fails with a NullPointerException, the debug log of a failed conversion reports the payload type and the exception instead of the payload itself, and a 'type' parameter that is not listed in META-INF/deserializable.types is logged as ignored. The allow-list is kept in a Set without blank entries. Resolves #1564 Signed-off-by: Oleg Zhurakousky <oleg.zhurakousky@broadcom.com>
1 parent eb92b4c commit ce3edbd

2 files changed

Lines changed: 133 additions & 23 deletions

File tree

‎spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/config/JsonMessageConverter.java‎

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222
import java.lang.reflect.Type;
2323
import java.net.URL;
2424
import java.nio.charset.StandardCharsets;
25-
import java.util.ArrayList;
2625
import java.util.Enumeration;
27-
import java.util.List;
26+
import java.util.LinkedHashSet;
27+
import java.util.Set;
2828

2929
import org.springframework.cloud.function.cloudevent.CloudEventMessageUtils;
3030
import org.springframework.cloud.function.json.JsonMapper;
@@ -37,7 +37,6 @@
3737
import org.springframework.messaging.converter.AbstractMessageConverter;
3838
import org.springframework.messaging.converter.MessageConverter;
3939
import org.springframework.util.ClassUtils;
40-
import org.springframework.util.CollectionUtils;
4140
import org.springframework.util.MimeType;
4241
import org.springframework.util.StringUtils;
4342

@@ -54,7 +53,7 @@ public class JsonMessageConverter extends AbstractMessageConverter {
5453

5554
private final JsonMapper jsonMapper;
5655

57-
private final List<String> deserializableTypes = new ArrayList<>();
56+
private final Set<String> deserializableTypes = new LinkedHashSet<>();
5857

5958
public JsonMessageConverter(JsonMapper jsonMapper) {
6059
this(jsonMapper, new MimeType("application", "json"), new MimeType(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getType(),
@@ -79,7 +78,9 @@ public JsonMessageConverter(JsonMapper jsonMapper, MimeType... supportedMimeType
7978
// need to split in case if delimited
8079
String[] keys = line.split(",");
8180
for (int i = 0; i < keys.length; i++) {
82-
this.deserializableTypes.add(keys[i].trim());
81+
if (StringUtils.hasText(keys[i])) {
82+
this.deserializableTypes.add(keys[i].trim());
83+
}
8384
}
8485
}
8586
}
@@ -120,22 +121,22 @@ protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @
120121
}
121122
Type convertToType = this.getResolvedType(targetClass, conversionHint);
122123
if (convertToType == null || convertToType == Object.class) {
123-
if (!CollectionUtils.isEmpty(this.deserializableTypes)) {
124-
MimeType mimeType = getMimeType(message.getHeaders());
125-
String type = mimeType != null ? mimeType.getParameter("type") : null;
126-
if (StringUtils.hasText(type) && this.deserializableTypes.contains(type)) {
127-
try {
128-
convertToType = this.loadClass(type);
129-
}
130-
catch (ClassNotFoundException | LinkageError e) {
131-
throw new IllegalArgumentException("Failed to load class `" + type + "` specified by the provided content-type: " + mimeType, e);
132-
}
124+
MimeType mimeType = getMimeType(message.getHeaders());
125+
String type = mimeType != null ? mimeType.getParameter("type") : null;
126+
if (StringUtils.hasText(type) && this.deserializableTypes.contains(type)) {
127+
try {
128+
convertToType = this.loadClass(type);
133129
}
134-
else {
135-
return message.getPayload();
130+
catch (ClassNotFoundException | LinkageError e) {
131+
throw new IllegalArgumentException("Failed to load class `" + type + "` specified by the provided content-type: " + mimeType, e);
136132
}
137133
}
138134
else {
135+
if (StringUtils.hasText(type) && logger.isDebugEnabled()) {
136+
logger.debug("Ignoring the 'type' parameter '" + StringUtils.truncate(type, 100)
137+
+ "' of the content type since the type is not on the allow-list ('META-INF/deserializable.types') "
138+
+ "and the payload is passed on as is");
139+
}
139140
return message.getPayload();
140141
}
141142
}
@@ -147,15 +148,14 @@ protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @
147148
return this.jsonMapper.fromJson(message.getPayload(), convertToType);
148149
}
149150
catch (Exception e) {
150-
if (message.getPayload() instanceof byte[] && String.class.isAssignableFrom(targetClass)) {
151+
if (message.getPayload() instanceof byte[] && targetClass != null
152+
&& String.class.isAssignableFrom(targetClass)) {
151153
return new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
152154
}
153155
else if (logger.isDebugEnabled()) {
154-
Object payload = message.getPayload();
155-
if (payload instanceof byte[]) {
156-
payload = new String((byte[]) payload, StandardCharsets.UTF_8);
157-
}
158-
logger.debug("Failed to convert value: " + payload + " to: " + targetClass, e);
156+
// the payload itself is not logged since it may hold sensitive data and be arbitrarily large
157+
logger.debug("Failed to convert a payload of type " + message.getPayload().getClass().getName()
158+
+ " to: " + (targetClass != null ? targetClass : convertToType), e);
159159
}
160160
}
161161
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/*
2+
* Copyright 2026-present the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.cloud.function.context.config;
18+
19+
import java.nio.charset.StandardCharsets;
20+
import java.util.List;
21+
22+
import ch.qos.logback.classic.Level;
23+
import ch.qos.logback.classic.Logger;
24+
import ch.qos.logback.classic.spi.ILoggingEvent;
25+
import ch.qos.logback.core.read.ListAppender;
26+
import org.junit.jupiter.api.AfterEach;
27+
import org.junit.jupiter.api.BeforeEach;
28+
import org.junit.jupiter.api.Test;
29+
import org.slf4j.LoggerFactory;
30+
import tools.jackson.databind.ObjectMapper;
31+
32+
import org.springframework.cloud.function.context.config.JsonMessageConverterTests.Person;
33+
import org.springframework.cloud.function.json.JacksonMapper;
34+
import org.springframework.messaging.Message;
35+
import org.springframework.messaging.MessageHeaders;
36+
import org.springframework.messaging.support.MessageBuilder;
37+
38+
import static org.assertj.core.api.Assertions.assertThat;
39+
40+
/**
41+
* Tests for the handling of unexpected input by {@link JsonMessageConverter}.
42+
*
43+
* @author Oleg Zhurakousky
44+
*/
45+
public class JsonMessageConverterRobustnessTests {
46+
47+
private final Logger logger = (Logger) LoggerFactory.getLogger(JsonMessageConverter.class);
48+
49+
private final ListAppender<ILoggingEvent> appender = new ListAppender<>();
50+
51+
private Level originalLevel;
52+
53+
@BeforeEach
54+
void attach() {
55+
this.originalLevel = this.logger.getLevel();
56+
this.logger.setLevel(Level.DEBUG);
57+
this.appender.start();
58+
this.logger.addAppender(this.appender);
59+
}
60+
61+
@AfterEach
62+
void detach() {
63+
this.logger.detachAppender(this.appender);
64+
this.logger.setLevel(this.originalLevel);
65+
}
66+
67+
private JsonMessageConverter converter() {
68+
return new JsonMessageConverter(new JacksonMapper(new ObjectMapper()));
69+
}
70+
71+
private static Message<byte[]> typed(String body, String type) {
72+
return MessageBuilder.withPayload(body.getBytes(StandardCharsets.UTF_8))
73+
.setHeader(MessageHeaders.CONTENT_TYPE, "application/json;type=" + type).build();
74+
}
75+
76+
@Test
77+
public void failedConversionWithoutTargetClassReturnsNull() {
78+
assertThat(converter().convertFromInternal(typed("not json", Person.class.getName()), null, null)).isNull();
79+
assertThat(converter().convertFromInternal(typed("not json", Person.class.getName()), Object.class, null))
80+
.isNull();
81+
}
82+
83+
@Test
84+
public void failedConversionDoesNotLogThePayload() {
85+
String secret = "s3cr3t-token-value";
86+
assertThat(converter().convertFromInternal(typed("{\"name\": " + secret, Person.class.getName()),
87+
Person.class, null)).isNull();
88+
List<String> messages = this.appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
89+
assertThat(messages).isNotEmpty().noneMatch(m -> m.contains(secret));
90+
}
91+
92+
@Test
93+
public void typeThatIsNotOnTheAllowListIsNotLoadedAndTheReasonIsLogged() {
94+
String type = "java.lang.ProcessBuilder";
95+
Message<byte[]> message = typed("{\"a\":1}", type);
96+
assertThat(converter().convertFromInternal(message, Object.class, null)).isSameAs(message.getPayload());
97+
assertThat(this.appender.list.stream().map(ILoggingEvent::getFormattedMessage))
98+
.anyMatch(m -> m.contains(type) && m.contains("allow"));
99+
}
100+
101+
@Test
102+
public void deeplyNestedJsonIsRejectedInsteadOfExhaustingTheStack() {
103+
String nested = "[".repeat(200_000) + "]".repeat(200_000);
104+
Message<byte[]> message = MessageBuilder.withPayload(nested.getBytes(StandardCharsets.UTF_8))
105+
.setHeader(MessageHeaders.CONTENT_TYPE, "application/json").build();
106+
assertThat(converter().convertFromInternal(message, Object.class, null)).isNotNull();
107+
assertThat(converter().convertFromInternal(message, List.class, null)).isNull();
108+
}
109+
110+
}

0 commit comments

Comments
 (0)