Skip to content
Merged
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
16 changes: 16 additions & 0 deletions src/main/java/com/rabbitmq/tools/json/JSONReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ public class JSONReader {
private static final Object COLON = new Object();
private static final Object COMMA = new Object();

private static final int MAX_NESTING_DEPTH = 100;

private static final Map<Character, Character> escapes = new HashMap<Character, Character>();
static {
escapes.put(Character.valueOf('"'), Character.valueOf('"'));
Expand All @@ -71,6 +73,7 @@ public class JSONReader {
private CharacterIterator it;
private char c;
private Object token;
private int depth;
private final StringBuilder buf = new StringBuilder();

private char next() {
Expand Down Expand Up @@ -100,6 +103,7 @@ else if (c == '/' && next() == '/') {
public Object read(String string) {
it = new StringCharacterIterator(string);
c = it.first();
depth = 0;
return read();
}

Expand All @@ -112,17 +116,21 @@ private Object read() {
next();
ret = string(sep);
} else if (c == '[') {
enterNested();
next();
ret = array();
depth--;
} else if (c == ']') {
ret = ARRAY_END;
next();
} else if (c == ',') {
ret = COMMA;
next();
} else if (c == '{') {
enterNested();
next();
ret = object();
depth--;
} else if (c == '}') {
ret = OBJECT_END;
next();
Expand All @@ -148,6 +156,14 @@ private Object read() {
return ret;
}

private void enterNested() {
if (++depth > MAX_NESTING_DEPTH) {
throw new IllegalStateException(
"Maximum nesting depth (" + MAX_NESTING_DEPTH + ") exceeded while parsing JSON (around character "
+ (it.getIndex() - it.getBeginIndex()) + ")");
}
}

private Object object() {
Map<String, Object> ret = new HashMap<String, Object>();
String key = (String) read(); // JSON keys must be strings
Expand Down
100 changes: 100 additions & 0 deletions src/test/java/com/rabbitmq/client/test/JSONReadWriteTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,14 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;

import com.rabbitmq.client.Channel;
import com.rabbitmq.tools.json.JSONReader;
import com.rabbitmq.tools.json.JSONWriter;
import com.rabbitmq.tools.jsonrpc.JsonRpcServer;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;

Expand Down Expand Up @@ -129,4 +134,99 @@ public void truncatedLineCommentShouldThrow() {
assertEquals(1, ((java.util.Map<?, ?>) new JSONReader().read("// c\n{\"a\":1}")).get("a"));
}

@Test
public void deeplyNestedInputShouldThrow() {
assertThrows(IllegalStateException.class, () -> new JSONReader().read(nestedArrays(101)));
assertThrows(IllegalStateException.class, () -> new JSONReader().read(nestedObjects(101)));
assertThrows(IllegalStateException.class, () -> new JSONReader().read(nestedArrays(100_000)));
assertThrows(IllegalStateException.class, () -> new JSONReader().read(nestedObjects(100_000)));
// arrays and objects count towards the same limit
assertEquals(100, depth(new JSONReader().read(mixed(50))));
assertThrows(IllegalStateException.class, () -> new JSONReader().read("[" + mixed(50) + "]"));
}

@Test
public void nestingUpToLimitShouldBeAccepted() {
assertEquals(100, depth(new JSONReader().read(nestedArrays(100))));
assertEquals(100, depth(new JSONReader().read(nestedObjects(100))));
// depth is about nesting, not about the number of sibling structures
StringBuilder siblings = new StringBuilder("[");
for (int i = 0; i < 1000; i++) {
siblings.append(i == 0 ? "" : ",").append(nestedArrays(50));
}
siblings.append("]");
assertEquals(1000, ((List<?>) new JSONReader().read(siblings.toString())).size());
// the reader can be reused after a failure
JSONReader reader = new JSONReader();
assertThrows(IllegalStateException.class, () -> reader.read(nestedArrays(101)));
assertEquals(100, depth(reader.read(nestedArrays(100))));
}

@Test
public void deeplyNestedJsonRpcRequestShouldGetBadRequestResponse() throws Exception {
JsonRpcServer server = new JsonRpcServer(mock(Channel.class), "q", EchoService.class,
(EchoService) input -> input);

String response = server.doCall(
"{\"version\":\"1.1\",\"method\":\"echo\",\"params\":[" + nestedArrays(100_000) + "]}");
Map<?, ?> error = (Map<?, ?>) ((Map<?, ?>) new JSONReader().read(response)).get("error");
assertEquals(400, error.get("code"));

response = server.doCall("{\"version\":\"1.1\",\"method\":\"echo\",\"params\":[\"hello\"]}");
assertEquals("hello", ((Map<?, ?>) new JSONReader().read(response)).get("result"));
}

public interface EchoService {
String echo(String input);
}

private static String nestedArrays(int depth) {
StringBuilder sb = new StringBuilder(depth * 2);
for (int i = 0; i < depth; i++) {
sb.append('[');
}
for (int i = 0; i < depth; i++) {
sb.append(']');
}
return sb.toString();
}

private static String nestedObjects(int depth) {
StringBuilder sb = new StringBuilder(depth * 6);
for (int i = 0; i < depth; i++) {
sb.append("{\"a\":");
}
sb.append('1');
for (int i = 0; i < depth; i++) {
sb.append('}');
}
return sb.toString();
}

private static String mixed(int pairs) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < pairs; i++) {
sb.append("[{\"a\":");
}
sb.append('1');
for (int i = 0; i < pairs; i++) {
sb.append("}]");
}
return sb.toString();
}

private static int depth(Object value) {
int depth = 0;
while (value instanceof List || value instanceof Map) {
depth++;
if (value instanceof List) {
List<?> list = (List<?>) value;
value = list.isEmpty() ? null : list.get(0);
} else {
value = ((Map<?, ?>) value).get("a");
}
}
return depth;
}

}
Loading