diff --git a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java index 615b714df00..74b71b2e8c6 100644 --- a/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java +++ b/framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java @@ -35,6 +35,7 @@ public class JsonRpcServlet extends RateLimiterServlet { private static final ObjectMapper MAPPER = buildMapper(); private static final ObjectMapper OUTBOUND_MAPPER = new ObjectMapper(); + private static final String INVALID_REQUEST_MESSAGE = "Invalid Request"; private static ObjectMapper buildMapper() { JsonFactory factory = JsonFactory.builder() @@ -125,21 +126,22 @@ private void doPostInternal(HttpServletRequest req, HttpServletResponse resp) th } if (!rootNode.isObject() && !rootNode.isArray()) { - writeJsonRpcError(resp, JsonRpcError.INVALID_REQUEST, "Invalid Request", null, false); + writeJsonRpcError(resp, JsonRpcError.INVALID_REQUEST, INVALID_REQUEST_MESSAGE, null, false); return; } boolean isBatch = rootNode.isArray(); if (isBatch && rootNode.isEmpty()) { - writeJsonRpcError(resp, JsonRpcError.INVALID_REQUEST, "Invalid Request", null, false); + writeJsonRpcError(resp, JsonRpcError.INVALID_REQUEST, INVALID_REQUEST_MESSAGE, null, false); return; } - if (!isBatch && hasInvalidRequestId(rootNode)) { - writeJsonRpcError(resp, JsonRpcError.INVALID_REQUEST, "Invalid Request", null, false); + if (!isBatch && hasInvalidVersion(rootNode)) { + writeJsonRpcError(resp, JsonRpcError.INVALID_REQUEST, + INVALID_REQUEST_MESSAGE + ": jsonrpc must be \"2.0\"", rootNode.get("id"), false); return; } - if (!isBatch && hasScalarParams(rootNode)) { - writeJsonRpcError(resp, JsonRpcError.INVALID_REQUEST, "Invalid Request", + if (!isBatch && isInvalidRequest(rootNode)) { + writeJsonRpcError(resp, JsonRpcError.INVALID_REQUEST, INVALID_REQUEST_MESSAGE, rootNode.get("id"), false); return; } @@ -202,9 +204,14 @@ private void handleBatch(HttpServletResponse resp, JsonNode rootNode, int maxRes for (int i = 0; i < rootNode.size(); i++) { JsonNode subRequest = rootNode.get(i); - if (!subRequest.isObject() || hasInvalidRequestId(subRequest) - || hasScalarParams(subRequest)) { - ObjectNode errNode = buildErrorNode(JsonRpcError.INVALID_REQUEST, "Invalid Request", + String invalidRequest = null; + if (subRequest.isObject() && hasInvalidVersion(subRequest)) { + invalidRequest = INVALID_REQUEST_MESSAGE + ": jsonrpc must be \"2.0\""; + } else if (isInvalidRequest(subRequest)) { + invalidRequest = INVALID_REQUEST_MESSAGE; + } + if (invalidRequest != null) { + ObjectNode errNode = buildErrorNode(JsonRpcError.INVALID_REQUEST, invalidRequest, subRequest.get("id")); if (!overflow) { byte[] errBytes = MAPPER.writeValueAsBytes(errNode); @@ -369,6 +376,29 @@ private ObjectNode buildErrorNode(JsonRpcError error, String message, JsonNode i return errorObj; } + private boolean hasInvalidVersion(JsonNode request) { + JsonNode version = request.get("jsonrpc"); + return version == null || !version.isTextual() || !"2.0".equals(version.asText()); + } + + private boolean isInvalidRequest(JsonNode request) { + return !request.isObject() || hasInvalidRequestId(request) || hasNullRequestId(request) + || hasScalarParams(request) || hasInvalidMethod(request); + } + + // Stricter than the spec and geth, which both answer a null id normally. jsonrpc4j invokes + // the method but treats a null id as a notification and discards a successful result, so the + // caller never sees the outcome of a call that took effect. Reject it before dispatch instead; + // a request without an id is still dispatched as a notification. + private boolean hasNullRequestId(JsonNode request) { + return request.has("id") && request.get("id").isNull(); + } + + private boolean hasInvalidMethod(JsonNode request) { + JsonNode method = request.get("method"); + return method == null || !method.isTextual() || method.asText().isEmpty(); + } + private static boolean hasInvalidRequestId(JsonNode request) { return request.has("id") && !isValidRequestId(request.get("id")); } diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcServletTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcServletTest.java index b91779b9052..72cf2386de5 100644 --- a/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcServletTest.java +++ b/framework/src/test/java/org/tron/core/services/jsonrpc/JsonRpcServletTest.java @@ -102,7 +102,7 @@ public void emptyBody_returnsParseError() throws Exception { @Test public void batchExceedsLimit_returnsExceedLimitAsArray() throws Exception { CommonParameter.getInstance().jsonRpcMaxBatchSize = 2; - MockHttpServletResponse resp = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse resp = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsString()); assertTrue("batch error response must be a JSON array", body.isArray()); @@ -121,7 +121,7 @@ public void batchWithinLimit_proceedsToRpcServer() throws Exception { return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("[{\"id\":1},{\"id\":2}]"); + MockHttpServletResponse resp = doPost(withEnvelope("[{\"id\":1},{\"id\":2}]")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsByteArray()); assertTrue("batch response must be a JSON array", body.isArray()); @@ -157,17 +157,102 @@ public void invalidRequestIdTypes_returnInvalidRequestWithoutDispatch() throws E } @Test - public void nullRequestId_isNotRejectedByServletValidation() throws Exception { - int[] callCount = {0}; + public void nullRequestId_returnsInvalidRequestWithoutDispatch() throws Exception { + MockHttpServletResponse resp = doPost("{\"jsonrpc\":\"2.0\",\"method\":\"web3_clientVersion\"," + + "\"params\":[],\"id\":null}"); + + assertInvalidRequest(MAPPER.readTree(resp.getContentAsByteArray()), + "Invalid Request", "null"); + verifyNoInteractions(mockRpcServer); + } + + @Test + public void invalidVersion_returnsInvalidRequestWithoutDispatch() throws Exception { + String[] versions = {"", "\"jsonrpc\":\"1.0\",", "\"jsonrpc\":2.0,", + "\"jsonrpc\":null,", "\"jsonrpc\":\"2.0 \","}; + + for (String version : versions) { + MockHttpServletResponse resp = doPost( + "{" + version + "\"method\":\"web3_clientVersion\",\"params\":[],\"id\":7}"); + assertInvalidRequest(MAPPER.readTree(resp.getContentAsByteArray()), + "Invalid Request: jsonrpc must be \"2.0\"", "7"); + } + + verifyNoInteractions(mockRpcServer); + } + + @Test + public void invalidVersion_takesPrecedenceOverOtherEnvelopeErrors() throws Exception { + String request = "{\"jsonrpc\":\"1.0\",\"method\":5,\"id\":{}}"; + + assertInvalidRequest(MAPPER.readTree(doPost(request).getContentAsByteArray()), + "Invalid Request: jsonrpc must be \"2.0\"", "null"); + JsonNode batch = MAPPER.readTree(doPost("[" + request + "]").getContentAsByteArray()); + assertEquals(1, batch.size()); + assertInvalidRequest(batch.get(0), "Invalid Request: jsonrpc must be \"2.0\"", "null"); + verifyNoInteractions(mockRpcServer); + } + + @Test + public void invalidMethod_returnsInvalidRequestWithoutDispatch() throws Exception { + String[] methods = {"", "\"method\":\"\",", "\"method\":5,", "\"method\":null,", + "\"method\":[],"}; + + for (String method : methods) { + MockHttpServletResponse resp = doPost( + "{\"jsonrpc\":\"2.0\"," + method + "\"params\":[],\"id\":\"a\"}"); + assertInvalidRequest(MAPPER.readTree(resp.getContentAsByteArray()), + "Invalid Request", "\"a\""); + } + + verifyNoInteractions(mockRpcServer); + } + + @Test + public void invalidEnvelopeWithoutId_isAnsweredRatherThanTreatedAsNotification() + throws Exception { + MockHttpServletResponse resp = doPost("{\"method\":\"web3_clientVersion\"}"); + + assertInvalidRequest(MAPPER.readTree(resp.getContentAsByteArray()), + "Invalid Request: jsonrpc must be \"2.0\"", "null"); + resp = doPost("{\"jsonrpc\":\"2.0\",\"params\":[]}"); + assertInvalidRequest(MAPPER.readTree(resp.getContentAsByteArray()), + "Invalid Request", "null"); + verifyNoInteractions(mockRpcServer); + } + + @Test + public void batchInvalidEnvelope_rejectsOnlyOffendingElements() throws Exception { + List dispatched = new ArrayList<>(); doAnswer(inv -> { - callCount[0]++; + JsonNode request = MAPPER.readTree((InputStream) inv.getArgument(0)); + dispatched.add(request); + OutputStream out = inv.getArgument(1); + out.write(("{\"jsonrpc\":\"2.0\",\"result\":\"ok\",\"id\":" + + request.get("id") + "}").getBytes(StandardCharsets.UTF_8)); return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - doPost("{\"jsonrpc\":\"2.0\",\"method\":\"web3_clientVersion\"," - + "\"params\":[],\"id\":null}"); + MockHttpServletResponse resp = doPost("[" + + "{\"jsonrpc\":\"2.0\",\"method\":\"web3_clientVersion\",\"id\":1}," + + "{\"method\":\"web3_clientVersion\",\"id\":2}," + + "{\"jsonrpc\":\"2.0\",\"method\":3,\"id\":3}," + + "{\"jsonrpc\":\"2.0\",\"method\":\"web3_clientVersion\",\"id\":null}," + + "{\"jsonrpc\":\"2.0\",\"params\":[]}," + + "{\"jsonrpc\":\"2.0\",\"method\":\"web3_clientVersion\",\"id\":5}" + + "]"); - assertEquals("a null id is valid JSON-RPC input and must reach dispatch", 1, callCount[0]); + JsonNode body = MAPPER.readTree(resp.getContentAsByteArray()); + assertEquals(6, body.size()); + assertEquals("ok", body.get(0).get("result").asText()); + assertInvalidRequest(body.get(1), "Invalid Request: jsonrpc must be \"2.0\"", "2"); + assertInvalidRequest(body.get(2), "Invalid Request", "3"); + assertInvalidRequest(body.get(3), "Invalid Request", "null"); + assertInvalidRequest(body.get(4), "Invalid Request", "null"); + assertEquals("ok", body.get(5).get("result").asText()); + assertEquals("only valid requests should reach jsonrpc4j", 2, dispatched.size()); + assertEquals(1, dispatched.get(0).get("id").asInt()); + assertEquals(5, dispatched.get(1).get("id").asInt()); } @Test @@ -321,7 +406,7 @@ public void batchLimitDisabled_largeBatchAllowed() throws Exception { if (i > 0) { sb.append(','); } - sb.append("{}"); + sb.append("{\"jsonrpc\":\"2.0\",\"method\":\"eth_blockNumber\"}"); } sb.append("]"); MockHttpServletResponse resp = doPost(sb.toString()); @@ -337,7 +422,8 @@ public void batchLimitDisabled_largeBatchAllowed() throws Exception { public void rpcServerThrowsRuntimeException_returnsInternalError() throws Exception { doThrow(new RuntimeException("server exploded")).when(mockRpcServer) .handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("{\"method\":\"eth_blockNumber\",\"id\":42}"); + MockHttpServletResponse resp = doPost( + withEnvelope("{\"method\":\"eth_blockNumber\",\"id\":42}")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsString()); assertFalse(body.isArray()); @@ -351,7 +437,8 @@ public void rpcServerThrowsIOException_returnsInternalError() throws Exception { doThrow(new IOException("server exploded")).when(mockRpcServer) .handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("{\"method\":\"eth_blockNumber\",\"id\":42}"); + MockHttpServletResponse resp = doPost( + withEnvelope("{\"method\":\"eth_blockNumber\",\"id\":42}")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsByteArray()); @@ -365,7 +452,7 @@ public void notificationIOException_returnsEmptyResponse() throws Exception { doThrow(new IOException("server exploded")).when(mockRpcServer) .handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("{\"method\":\"eth_blockNumber\"}"); + MockHttpServletResponse resp = doPost(withEnvelope("{\"method\":\"eth_blockNumber\"}")); assertEquals(200, resp.getStatus()); assertEquals("application/json-rpc", resp.getContentType()); @@ -380,8 +467,8 @@ public void singleAssertionError_discardsPartialOutputAndReturnsInternalError() throw new AssertionError("assertion-sensitive-marker"); }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - assertSingleInternalError(doPost("{\"id\":42}"), "42"); - assertSingleInternalError(doPost("{\"id\":\"request-1\"}"), "\"request-1\""); + assertSingleInternalError(doPost(withEnvelope("{\"id\":42}")), "42"); + assertSingleInternalError(doPost(withEnvelope("{\"id\":\"request-1\"}")), "\"request-1\""); } @Test @@ -389,21 +476,13 @@ public void singleAssertionErrorWithoutId_keepsEmptyResponse() throws Exception doThrow(new AssertionError("assertion-sensitive-marker")).when(mockRpcServer) .handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse response = doPost("{\"method\":\"eth_blockNumber\"}"); + MockHttpServletResponse response = doPost(withEnvelope("{\"method\":\"eth_blockNumber\"}")); assertEquals(200, response.getStatus()); assertEquals("application/json-rpc", response.getContentType()); assertEquals(0, response.getContentAsByteArray().length); } - @Test - public void singleAssertionErrorWithNullId_keepsErrorResponse() throws Exception { - doThrow(new AssertionError("assertion-sensitive-marker")).when(mockRpcServer) - .handleRequest(any(InputStream.class), any(OutputStream.class)); - - assertSingleInternalError(doPost("{\"method\":\"eth_blockNumber\",\"id\":null}"), "null"); - } - @Test public void singleWrappedAssertionError_propagatesFatalCauseWithoutLogging() throws Exception { StackOverflowError fatal = new StackOverflowError("fatal-marker"); @@ -427,7 +506,7 @@ public void batchRpcServerThrows_internalErrorIsArray() throws Exception { doThrow(new RuntimeException("boom")).when(mockRpcServer) .handleRequest(any(InputStream.class), any(OutputStream.class)); MockHttpServletResponse resp = doPost( - "[{\"method\":\"eth_blockNumber\",\"id\":\"request-1\"}]"); + withEnvelope("[{\"method\":\"eth_blockNumber\",\"id\":\"request-1\"}]")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsString()); assertTrue("batch internal error must be an array", body.isArray()); @@ -442,7 +521,7 @@ public void batchRpcServerThrowsIOException_internalErrorIsArray() throws Except .handleRequest(any(InputStream.class), any(OutputStream.class)); MockHttpServletResponse resp = doPost( - "[{\"method\":\"eth_blockNumber\",\"id\":\"request-1\"}]"); + withEnvelope("[{\"method\":\"eth_blockNumber\",\"id\":\"request-1\"}]")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsByteArray()); @@ -460,7 +539,7 @@ public void fatalError_commitsBare500AndRethrowsOriginal() throws Exception { MockHttpServletResponse response = new MockHttpServletResponse(); StackOverflowError thrown = assertThrows(StackOverflowError.class, - () -> doPost("{\"method\":\"eth_blockNumber\",\"id\":1}", response)); + () -> doPost(withEnvelope("{\"method\":\"eth_blockNumber\",\"id\":1}"), response)); assertSame(fatal, thrown); assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, response.getStatus()); @@ -555,7 +634,7 @@ public void batchMalformedRpcServerResponse_preservesRequestId() throws Exceptio }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); MockHttpServletResponse resp = doPost( - "[{\"method\":\"eth_blockNumber\",\"id\":42}]"); + withEnvelope("[{\"method\":\"eth_blockNumber\",\"id\":42}]")); JsonNode body = MAPPER.readTree(resp.getContentAsByteArray()); assertTrue(body.isArray()); @@ -568,10 +647,10 @@ public void batchMalformedRpcServerResponse_preservesRequestId() throws Exceptio public void batchRuntimeException_preservesSiblingsAndContinues() throws Exception { List dispatched = stubBatchWithMiddleFailure(new RuntimeException("failure-marker")); - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertRecoveredBatch(response, "2"); - assertEquals(MAPPER.readTree("[{\"id\":1},{\"id\":2},{\"id\":3}]"), + assertEquals(MAPPER.readTree(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")), MAPPER.valueToTree(dispatched)); } @@ -579,10 +658,10 @@ public void batchRuntimeException_preservesSiblingsAndContinues() throws Excepti public void batchIOException_preservesSiblingsAndContinues() throws Exception { List dispatched = stubBatchWithMiddleFailure(new IOException("failure-marker")); - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertRecoveredBatch(response, "2"); - assertEquals(MAPPER.readTree("[{\"id\":1},{\"id\":2},{\"id\":3}]"), + assertEquals(MAPPER.readTree(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")), MAPPER.valueToTree(dispatched)); } @@ -590,7 +669,7 @@ public void batchIOException_preservesSiblingsAndContinues() throws Exception { public void batchAssertionError_discardsPartialOutputAndPreservesSiblings() throws Exception { List dispatched = stubBatchWithMiddleFailure( new AssertionError("assertion-sensitive-marker"), true); - String request = "[{\"id\":1},{\"id\":2},{\"id\":3}]"; + String request = withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]"); MockHttpServletResponse response = doPost(request); @@ -607,7 +686,7 @@ public void batchAssertionError_discardsPartialOutputAndPreservesSiblings() thro public void batchAssertionErrorWithoutId_keepsErrorNodeAndContinues() throws Exception { List dispatched = stubBatchWithMiddleFailure( new AssertionError("assertion-sensitive-marker")); - String request = "[{\"id\":1},{\"method\":\"eth_blockNumber\"},{\"id\":3}]"; + String request = withEnvelope("[{\"id\":1},{\"method\":\"eth_blockNumber\"},{\"id\":3}]"); MockHttpServletResponse response = doPost(request); @@ -624,7 +703,7 @@ public void batchAssertionErrors_logOnlyFirstStackPerBatch() throws Exception { try (BatchLogCapture logs = new BatchLogCapture()) { for (int i = 0; i < 2; i++) { assertBatchWithTwoRecoveredFailures( - doPost("[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4}]")); + doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4}]"))); } assertEquals(Arrays.asList(1, 2, 3, 4, 1, 2, 3, 4), dispatched); @@ -642,7 +721,8 @@ public void batchMultipleFailures_logsOnlyFirstStackAndPreservesResponses() thro new IllegalStateException("repeat-sensitive-marker")); try (BatchLogCapture logs = new BatchLogCapture()) { - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4}]"); + MockHttpServletResponse response = doPost( + withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4}]")); assertBatchWithTwoRecoveredFailures(response); assertEquals(Arrays.asList(1, 2, 3, 4), dispatched); @@ -659,7 +739,7 @@ public void consecutiveBatches_eachLogTheirFirstFailure() throws Exception { try (BatchLogCapture logs = new BatchLogCapture()) { for (int i = 0; i < 2; i++) { assertBatchWithTwoRecoveredFailures( - doPost("[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4}]")); + doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4}]"))); } assertEquals(Arrays.asList(1, 2, 3, 4, 1, 2, 3, 4), dispatched); @@ -679,7 +759,7 @@ public void batchFatalAfterOrdinaryFailure_doesNotLogFatalOrContinue() throws Ex try (BatchLogCapture logs = new BatchLogCapture()) { assertSame(fatal, assertThrows(StackOverflowError.class, - () -> doPost("[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4}]", response))); + () -> doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3},{\"id\":4}]"), response))); assertEquals(Arrays.asList(1, 2, 3), dispatched); assertEquals(500, response.getStatus()); @@ -696,7 +776,7 @@ public void batchMalformedResponse_preservesSiblingsAndContinues() throws Except List dispatched = stubBatchWithMalformedMiddleResponse(); try (BatchLogCapture logs = new BatchLogCapture()) { - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertRecoveredBatch(response, "2"); assertEquals(Arrays.asList(1, 2, 3), dispatched); @@ -715,11 +795,11 @@ public void serialize(JsonGenerator generator, SerializerProvider provider) throw new JsonProcessingException("serialization-marker") {}; } }; - failingRequest.put("id", 2); + failingRequest.put("jsonrpc", "2.0").put("method", "eth_blockNumber").put("id", 2); ArrayNode requests = MAPPER.createArrayNode(); - requests.addObject().put("id", 1); + requests.addObject().put("jsonrpc", "2.0").put("method", "eth_blockNumber").put("id", 1); requests.add(failingRequest); - requests.addObject().put("id", 3); + requests.addObject().put("jsonrpc", "2.0").put("method", "eth_blockNumber").put("id", 3); List dispatched = stubBatchWithMalformedMiddleResponse(); MockHttpServletResponse response = new MockHttpServletResponse(); Method handleBatch = JsonRpcServlet.class.getDeclaredMethod("handleBatch", @@ -752,7 +832,7 @@ private static ILoggingEvent assertSingleRecoveryDebug(BatchLogCapture logs, @Test public void batchFailureWithoutId_keepsErrorNodeAndContinues() throws Exception { List dispatched = stubBatchWithMiddleFailure(new IOException("failure-marker")); - String request = "[{\"id\":1},{\"method\":\"eth_blockNumber\"},{\"id\":3}]"; + String request = withEnvelope("[{\"id\":1},{\"method\":\"eth_blockNumber\"},{\"id\":3}]"); MockHttpServletResponse response = doPost(request); @@ -766,7 +846,7 @@ public void batchRecoveredError_atExactLimitDoesNotOverflow() throws Exception { int limit = MAPPER.writeValueAsBytes(recoveredBatch("2")).length; CommonParameter.getInstance().jsonRpcMaxResponseSize = limit; - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertRecoveredBatch(response, "2"); assertEquals(limit, response.getContentAsByteArray().length); @@ -779,7 +859,7 @@ public void batchMalformedResponse_countsOnlyReplacementBytes() throws Exception int limit = MAPPER.writeValueAsBytes(recoveredBatch("2")).length; CommonParameter.getInstance().jsonRpcMaxResponseSize = limit; - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertRecoveredBatch(response, "2"); assertEquals(limit, response.getContentAsByteArray().length); @@ -792,10 +872,10 @@ public void batchRecoveredError_consumesBudgetForLaterResponse() throws Exceptio CommonParameter.getInstance().jsonRpcMaxResponseSize = MAPPER.writeValueAsBytes(recoveredBatch("2")).length - 1; - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertRecoveredErrorConsumesBudget(response); - assertEquals(MAPPER.readTree("[{\"id\":1},{\"id\":2},{\"id\":3}]"), + assertEquals(MAPPER.readTree(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")), MAPPER.valueToTree(dispatched)); } @@ -805,7 +885,7 @@ public void batchMalformedResponse_replacementConsumesBudgetForLaterResponse() t CommonParameter.getInstance().jsonRpcMaxResponseSize = MAPPER.writeValueAsBytes(recoveredBatch("2")).length - 1; - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertRecoveredErrorConsumesBudget(response); assertEquals(Arrays.asList(1, 2, 3), dispatched); @@ -816,7 +896,7 @@ public void batchRecoveredError_overflowStopsLaterDispatch() throws Exception { List dispatched = stubBatchWithMiddleFailure(new IOException("failure-marker")); CommonParameter.getInstance().jsonRpcMaxResponseSize = limitBeforeSecondErrorFits(); - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertBatchErrorOverflow(response); assertEquals(2, dispatched.size()); @@ -827,7 +907,7 @@ public void batchMalformedResponse_replacementCanTriggerOverflow() throws Except List dispatched = stubBatchWithMalformedMiddleResponse(); CommonParameter.getInstance().jsonRpcMaxResponseSize = limitBeforeSecondErrorFits(); - MockHttpServletResponse response = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse response = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertBatchErrorOverflow(response); assertEquals(Arrays.asList(1, 2), dispatched); @@ -845,7 +925,7 @@ public void responseTooLarge_returnsSingleErrorObject() throws Exception { return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("{\"method\":\"eth_getLogs\",\"id\":1}"); + MockHttpServletResponse resp = doPost(withEnvelope("{\"method\":\"eth_getLogs\",\"id\":1}")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsString()); assertFalse(body.isArray()); @@ -862,7 +942,7 @@ public void batchResponseTooLarge_returnsErrorArray() throws Exception { return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("[{\"method\":\"eth_getLogs\"}]"); + MockHttpServletResponse resp = doPost(withEnvelope("[{\"method\":\"eth_getLogs\"}]")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsString()); assertTrue("batch response-too-large must be an array", body.isArray()); @@ -885,7 +965,7 @@ public void batchShortCircuitsOnOverflow() throws Exception { return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("[{\"id\":1},{\"id\":2},{\"id\":3}]"); + MockHttpServletResponse resp = doPost(withEnvelope("[{\"id\":1},{\"id\":2},{\"id\":3}]")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsString()); assertTrue("overflow response must be an array", body.isArray()); @@ -926,6 +1006,35 @@ public void batchInvalidRequestId_afterOverflowStillReturnsInvalidRequest() thro assertEquals("invalid requests must not be dispatched after overflow", 1, callCount[0]); } + @Test + public void batchInvalidEnvelope_afterOverflowStillReturnsInvalidRequest() throws Exception { + int limit = 50; + CommonParameter.getInstance().jsonRpcMaxResponseSize = limit; + int[] callCount = {0}; + doAnswer(inv -> { + OutputStream out = inv.getArgument(1); + out.write(new byte[limit + 1]); + callCount[0]++; + return 0; + }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); + + MockHttpServletResponse resp = doPost("[" + + "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getLogs\",\"id\":1}," + + "{\"jsonrpc\":\"1.0\",\"method\":\"eth_getLogs\",\"id\":2}," + + "{\"jsonrpc\":\"2.0\",\"method\":5,\"id\":3}," + + "{\"jsonrpc\":\"2.0\",\"method\":\"eth_getLogs\",\"id\":null}" + + "]"); + + JsonNode body = MAPPER.readTree(resp.getContentAsByteArray()); + assertEquals(4, body.size()); + assertEquals(-32003, body.get(0).get("error").get("code").asInt()); + assertEquals(1, body.get(0).get("id").asInt()); + assertInvalidRequest(body.get(1), "Invalid Request: jsonrpc must be \"2.0\"", "2"); + assertInvalidRequest(body.get(2), "Invalid Request", "3"); + assertInvalidRequest(body.get(3), "Invalid Request", "null"); + assertEquals("invalid requests must not be dispatched after overflow", 1, callCount[0]); + } + // --- normal path --- @Test @@ -937,7 +1046,8 @@ public void normalRequest_commitsRpcServerResponse() throws Exception { return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("{\"method\":\"eth_blockNumber\",\"id\":1}"); + MockHttpServletResponse resp = doPost( + withEnvelope("{\"method\":\"eth_blockNumber\",\"id\":1}")); assertEquals(200, resp.getStatus()); assertArrayEquals(rpcResp, resp.getContentAsByteArray()); } @@ -960,7 +1070,7 @@ public void batchResponse_contentTypeIsApplicationJsonRpc() throws Exception { return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("[{\"id\":1}]"); + MockHttpServletResponse resp = doPost(withEnvelope("[{\"id\":1}]")); assertEquals("application/json-rpc", resp.getContentType()); } @@ -970,7 +1080,7 @@ public void allNotificationBatch_contentTypeIsApplicationJsonRpc() throws Except doAnswer(inv -> 0).when(mockRpcServer) .handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("[{\"method\":\"eth_blockNumber\"}]"); + MockHttpServletResponse resp = doPost(withEnvelope("[{\"method\":\"eth_blockNumber\"}]")); assertEquals(200, resp.getStatus()); assertEquals(0, resp.getContentLength()); assertEquals("application/json-rpc", resp.getContentType()); @@ -1037,13 +1147,13 @@ public void batchWithMixedObjectAndArray_objectProcessedArrayRejected() throws E return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("[{\"id\":1}, []]"); + MockHttpServletResponse resp = doPost(withEnvelope("[{\"id\":1}, []]")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsString()); assertTrue("response must be a JSON array", body.isArray()); assertEquals(2, body.size()); assertEquals("ok", body.get(0).get("result").asText()); - assertEquals(-32600, body.get(1).get("error").get("code").asInt()); + assertInvalidRequestWithNullId(body.get(1)); } @Test @@ -1054,7 +1164,7 @@ public void batchWithNumericAndStringElements_allGetInvalidRequest() throws Exce assertTrue("response must be a JSON array", body.isArray()); assertEquals(3, body.size()); for (int i = 0; i < 3; i++) { - assertEquals(-32600, body.get(i).get("error").get("code").asInt()); + assertInvalidRequestWithNullId(body.get(i)); } } @@ -1133,7 +1243,7 @@ public void batchResponse_preservesResultsWithinByteLimit() throws Exception { return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); - MockHttpServletResponse resp = doPost("[{\"id\":41},{\"id\":42}]"); + MockHttpServletResponse resp = doPost(withEnvelope("[{\"id\":41},{\"id\":42}]")); assertEquals(200, resp.getStatus()); JsonNode body = MAPPER.readTree(resp.getContentAsByteArray()); assertTrue(body.isArray()); @@ -1347,6 +1457,30 @@ private static void assertInvalidRequestWithNullId(JsonNode response) { assertTrue(response.get("id").isNull()); } + private static void assertInvalidRequest(JsonNode response, String message, String id) + throws IOException { + assertEquals(MAPPER.readTree("{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32600," + + "\"message\":" + MAPPER.writeValueAsString(message) + "},\"id\":" + id + "}"), + response); + } + + /** Fills in the "jsonrpc" and "method" members that dispatch-path tests do not care about. */ + private static String withEnvelope(String json) throws IOException { + JsonNode root = MAPPER.readTree(json); + for (JsonNode request : root.isArray() ? root : MAPPER.createArrayNode().add(root)) { + if (request.isObject()) { + ObjectNode object = (ObjectNode) request; + if (!object.has("jsonrpc")) { + object.put("jsonrpc", "2.0"); + } + if (!object.has("method")) { + object.put("method", "eth_blockNumber"); + } + } + } + return MAPPER.writeValueAsString(root); + } + private MockHttpServletResponse doPost(String body) throws Exception { MockHttpServletResponse resp = new MockHttpServletResponse(); doPost(body, resp); @@ -1366,7 +1500,7 @@ private void assertCleanupFailureDoesNotReplaceFatal(HttpServletResponse respons .handleRequest(any(InputStream.class), any(OutputStream.class)); StackOverflowError thrown = assertThrows(StackOverflowError.class, - () -> doPost("{\"method\":\"eth_blockNumber\",\"id\":1}", response)); + () -> doPost(withEnvelope("{\"method\":\"eth_blockNumber\",\"id\":1}"), response)); assertSame(fatal, thrown); } @@ -1387,7 +1521,7 @@ private void assertWrappedFatalPropagates(Throwable failure, Error fatal, boolea return 0; }).when(mockRpcServer).handleRequest(any(InputStream.class), any(OutputStream.class)); MockHttpServletResponse response = new MockHttpServletResponse(); - String request = batch ? "[{\"id\":1},{\"id\":2},{\"id\":3}]" : "{\"id\":1}"; + String request = withEnvelope(batch ? "[{\"id\":1},{\"id\":2},{\"id\":3}]" : "{\"id\":1}"); Error thrown = assertThrows(Error.class, () -> doPost(request, response));