Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

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

private final JsonMapper jsonMapper;

private final List<String> deserializableTypes = new ArrayList<>();
private final Set<String> deserializableTypes = new LinkedHashSet<>();

public JsonMessageConverter(JsonMapper jsonMapper) {
this(jsonMapper, new MimeType("application", "json"), new MimeType(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getType(),
Expand All @@ -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());
}
}
}
}
Expand Down Expand Up @@ -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();
}
}
Expand All @@ -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);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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<String>) 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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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()));
Expand All @@ -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<byte[]> 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<byte[]> 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<byte[]> 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<String> 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<String> 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;

Expand Down
Loading