Skip to content
Closed
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 @@ -278,6 +278,9 @@ public class CommonParameter {
public int maxHeaderListSize;
@Getter
@Setter
public int maxJsonRecursionDepth = 100;
@Getter
@Setter
public boolean isRpcReflectionServiceEnable;
@Getter
@Setter
Expand Down
1 change: 1 addition & 0 deletions common/src/main/java/org/tron/core/Constant.java
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ public class Constant {
public static final String NODE_NET_MAX_TRX_PER_SECOND = "node.netMaxTrxPerSecond";
public static final String NODE_RPC_MAX_CONNECTION_AGE_IN_MILLIS = "node.rpc.maxConnectionAgeInMillis";
public static final String NODE_RPC_MAX_MESSAGE_SIZE = "node.rpc.maxMessageSize";
public static final String NODE_HTTP_JSON_MAX_RECURSION_DEPTH = "node.http.json.maxRecursionDepth";

public static final String NODE_RPC_MAX_HEADER_LIST_SIZE = "node.rpc.maxHeaderListSize";

Expand Down
4 changes: 4 additions & 0 deletions framework/src/main/java/org/tron/core/config/args/Args.java
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ public static void clearParam() {
PARAMETER.allowTvmBlob = 0;
PARAMETER.rpcMaxRstStream = 0;
PARAMETER.rpcSecondsPerWindow = 0;
PARAMETER.maxJsonRecursionDepth = 100;
}

/**
Expand Down Expand Up @@ -784,6 +785,9 @@ public static void setParam(final Config config) {
? config.getInt(Constant.NODE_RPC_MAX_HEADER_LIST_SIZE)
: GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE;

PARAMETER.maxJsonRecursionDepth = config.hasPath(Constant.NODE_HTTP_JSON_MAX_RECURSION_DEPTH)
? config.getInt(Constant.NODE_HTTP_JSON_MAX_RECURSION_DEPTH) : 100;

PARAMETER.isRpcReflectionServiceEnable =
config.hasPath(Constant.NODE_RPC_REFLECTION_SERVICE)
&& config.getBoolean(Constant.NODE_RPC_REFLECTION_SERVICE);
Expand Down
134 changes: 134 additions & 0 deletions framework/src/main/java/org/tron/core/services/http/JsonValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
package org.tron.core.services.http;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.fasterxml.jackson.core.exc.StreamConstraintsException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.tron.core.config.args.Args;

/**
* JSON validation and parsing utility using Jackson.
*/
@Slf4j(topic = "API")
public class JsonValidator {

private static final JsonFactory JSON_FACTORY;
private static final ObjectMapper OBJECT_MAPPER;

private static final int MAX_NESTING_DEPTH = Args.getInstance().getMaxJsonRecursionDepth();

private static final String VISIBLE_FIELD = "visible";

static {
StreamReadConstraints constraints = StreamReadConstraints.builder()
.maxNestingDepth(MAX_NESTING_DEPTH)
.build();

JSON_FACTORY = JsonFactory.builder()
.streamReadConstraints(constraints)
.build();

OBJECT_MAPPER = new ObjectMapper(JSON_FACTORY);

logger.info("Jackson JSON validator initialized: maxNestingDepth={}", MAX_NESTING_DEPTH);
}

/**
* Parse JSON and extract the "visible" field value.
* This method both validates constraints AND extracts the field in one pass.
*
* @param json JSON string
* @return value of "visible" field, or false if not present
* @throws IllegalArgumentException if JSON violates constraints
* @throws Exception if parsing fails
*/
public static boolean parseAndGetVisible(String json)
throws IllegalArgumentException, Exception {
if (json == null || json.isEmpty()) {
return false;
}

try {
JsonNode root = OBJECT_MAPPER.readTree(json);

if (root.has(VISIBLE_FIELD)) {
JsonNode visibleNode = root.get(VISIBLE_FIELD);

if (visibleNode.isBoolean()) {
return visibleNode.asBoolean();
} else if (visibleNode.isTextual()) {
return Boolean.parseBoolean(visibleNode.asText());
}
}

return false;
} catch (StreamConstraintsException e) {
logger.warn("JSON constraint violation in parseAndGetVisible: {}", e.getMessage());
throw new IllegalArgumentException("JSON validation failed: " + e.getMessage(), e);
} catch (JsonProcessingException e) {
logger.debug("JSON parsing failed in parseAndGetVisible: {}", e.getMessage());
throw new Exception("Invalid JSON format: " + e.getMessage(), e);
}
}

/**
* Parse JSON and extract a string field value.
*
* @param json JSON string
* @param fieldName field name to extract
* @return field value, or null if not present
* @throws IllegalArgumentException if JSON violates constraints
* @throws Exception if parsing fails
*/
public static String parseAndGetString(String json, String fieldName)
throws IllegalArgumentException, Exception {
if (json == null || json.isEmpty()) {
return null;
}

try {
JsonNode root = OBJECT_MAPPER.readTree(json);

if (root.has(fieldName)) {
JsonNode node = root.get(fieldName);
return node.isNull() ? null : node.asText();
}

return null;

} catch (com.fasterxml.jackson.core.exc.StreamConstraintsException e) {
logger.warn("JSON constraint violation: {}", e.getMessage());
throw new IllegalArgumentException(
"JSON validation failed: " + e.getMessage(), e);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
logger.debug("JSON parsing failed: {}", e.getMessage());
throw new Exception("Invalid JSON format: " + e.getMessage(), e);
}
}

/**
* Check if string is syntactically valid JSON.
* Lighter validation without full parsing.
*
* @param json string to check
* @return true if valid JSON syntax
*/
public static boolean isValidJson(String json) {
if (json == null || json.isEmpty()) {
return false;
}

try (JsonParser parser = JSON_FACTORY.createParser(json)) {
while (parser.nextToken() != null) {
// Just check syntax
}
return true;
} catch (Exception e) {
return false;
}
}
}
26 changes: 12 additions & 14 deletions framework/src/main/java/org/tron/core/services/http/Util.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Expand Down Expand Up @@ -347,15 +346,19 @@ public static boolean existVisible(final HttpServletRequest request) {
}

public static boolean getVisiblePost(final String input) {
boolean visible = false;
if (StringUtil.isNotBlank(input)) {
JSONObject jsonObject = JSON.parseObject(input);
if (jsonObject.containsKey(VISIBLE)) {
visible = Boolean.parseBoolean(jsonObject.getString(VISIBLE));
}
if (StringUtil.isBlank(input)) {
return false;
}

return visible;
try {
return JsonValidator.parseAndGetVisible(input);
} catch (IllegalArgumentException e) {
logger.warn("JSON constraint violation in POST body: {}", e.getMessage());
throw e;
} catch (Exception e) {
logger.debug("Failed to parse visible field from POST body: {}", e.getMessage());
return false;
}
}

public static String getContractType(final String input) {
Expand Down Expand Up @@ -635,11 +638,6 @@ public static String getJsonString(String str) {
}

public static boolean isValidJson(String json) {
try {
JSON.parse(json);
return true;
} catch (Exception e) {
return false;
}
return JsonValidator.isValidJson(json);
}
}
4 changes: 4 additions & 0 deletions framework/src/test/java/org/tron/common/ParameterTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,10 @@ public void testCommonParameter() {
assertEquals(200, parameter.getMaxMessageSize());
parameter.setMaxHeaderListSize(100);
assertEquals(100, parameter.getMaxHeaderListSize());

parameter.setMaxJsonRecursionDepth(120);
assertEquals(120, parameter.getMaxJsonRecursionDepth());

parameter.setRpcReflectionServiceEnable(false);
assertFalse(parameter.isRpcReflectionServiceEnable);
parameter.setValidateSignThreadNum(5);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ public void get() {
Assert.assertEquals(Long.MAX_VALUE, parameter.getMaxConnectionAgeInMillis());
Assert.assertEquals(GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE, parameter.getMaxMessageSize());
Assert.assertEquals(GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, parameter.getMaxHeaderListSize());
Assert.assertEquals(100, parameter.getMaxJsonRecursionDepth());
Assert.assertEquals(1L, parameter.getAllowCreationOfContracts());
Assert.assertEquals(0, parameter.getConsensusLogicOptimization());

Expand Down Expand Up @@ -178,6 +179,7 @@ public void testInitService() {
Assert.assertFalse(Args.getInstance().isJsonRpcHttpPBFTNodeEnable());
Assert.assertEquals(5000, Args.getInstance().getJsonRpcMaxBlockRange());
Assert.assertEquals(1000, Args.getInstance().getJsonRpcMaxSubTopics());
Assert.assertEquals(100, Args.getInstance().getMaxJsonRecursionDepth());
Args.clearParam();
// test set all true value
storage.put("node.rpc.enable", "true");
Expand All @@ -191,6 +193,7 @@ public void testInitService() {
storage.put("node.jsonrpc.httpPBFTEnable", "true");
storage.put("node.jsonrpc.maxBlockRange", "10");
storage.put("node.jsonrpc.maxSubTopics", "20");
storage.put("node.http.json.maxRecursionDepth", "50");
config = ConfigFactory.defaultOverrides().withFallback(ConfigFactory.parseMap(storage));
// test value
Args.setParam(config);
Expand All @@ -205,6 +208,7 @@ public void testInitService() {
Assert.assertTrue(Args.getInstance().isJsonRpcHttpPBFTNodeEnable());
Assert.assertEquals(10, Args.getInstance().getJsonRpcMaxBlockRange());
Assert.assertEquals(20, Args.getInstance().getJsonRpcMaxSubTopics());
Assert.assertEquals(50, Args.getInstance().getMaxJsonRecursionDepth());
Args.clearParam();
// test set all false value
storage.put("node.rpc.enable", "false");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package org.tron.core.services.http;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class JsonValidatorTest {
@Test
public void testParseAndGetVisibleTrue() throws Exception {
String json = "{\"visible\":true,\"other\":\"value\"}";
assertTrue(JsonValidator.parseAndGetVisible(json));
}

@Test
public void testParseAndGetVisibleFalse() throws Exception {
String json = "{\"visible\":false}";
assertFalse(JsonValidator.parseAndGetVisible(json));
}

@Test
public void testParseAndGetVisibleStringTrue() throws Exception {
String json = "{\"visible\":\"true\"}";
assertTrue(JsonValidator.parseAndGetVisible(json));
}

@Test
public void testParseAndGetVisibleNotPresent() throws Exception {
String json = "{\"other\":\"value\"}";
assertFalse(JsonValidator.parseAndGetVisible(json));
}

@Test(expected = IllegalArgumentException.class)
public void testParseAndGetVisibleDeepNesting() throws Exception {
StringBuilder json = new StringBuilder("{\"visible\":true,\"x\":");
for (int i = 0; i < 150; i++) {
json.append("{\"x\":");
}
json.append("1");
for (int i = 0; i < 150; i++) {
json.append("}");
}
json.append("}");

// Should throw due to depth constraint
JsonValidator.parseAndGetVisible(json.toString());
}

@Test
public void testParseAndGetString() throws Exception {
String json = "{\"contractType\":\"TransferContract\"}";
String result = JsonValidator.parseAndGetString(json, "contractType");
assertEquals("TransferContract", result);
}

@Test
public void testParseAndGetStringNotPresent() throws Exception {
String json = "{\"other\":\"value\"}";
String result = JsonValidator.parseAndGetString(json, "missing");
assertNull(result);
}

@Test(expected = Exception.class)
public void testParseAndGetVisibleMalformedJson() throws Exception {
String json = "{invalid json}";
JsonValidator.parseAndGetVisible(json);
}
}