Merge bitcoin/bitcoin#36758: rpc: handle malformed jsonrpc 2.0 requests correctly
What changed, and why it matters
This update fixes a bug in Bitcoin Core's JSON-RPC server. When a malformed request claimed to use JSON-RPC 2.0, the server could crash in debug builds or return the wrong HTTP status code in release builds. The fix makes the server return a proper JSON-RPC error inside a normal HTTP 200 response, as the JSON-RPC 2.0 spec expects. It also stops malformed batch subrequests from being silently treated as notifications. The crash only happens with RPC authentication enabled and only in debug builds, so it is mainly a testing/reliability issue rather than a live-network threat.
Apply the patch. It is a low-urgency correctness fix. Operators running debug builds with RPC exposed and authentication enabled should update to avoid a potential crash from malformed RPC traffic. No immediate mainnet consensus or wallet risk is indicated.
Security signals we found
Debug-build assertion failure (crash) reachable via authenticated RPC
Protocol non-compliance: malformed JSON-RPC 2.0 requests returned HTTP 400 instead of HTTP 200 with JSON-RPC error body
Malformed batch subrequests without id were incorrectly treated as notifications and produced no reply
Fix adds explicit version check before choosing HTTP error vs JSON-RPC error response
Evidence from the diff
The commit changes httprpc.cpp so that JSONErrorReply no longer assumes a V2 request cannot reach it. If the request is known to be JSON-RPC 2.0, the function now returns HTTP 200 and a JSON-RPC error object. rpc/request.cpp is updated so replies always include an “id” field (null when unknown), and parse() only marks a V2 request without an id as a notification if parsing succeeds. rpc/request.h adds an m_notification flag. Tests and documentation are updated accordingly. The PR description notes that on master a debug build with RPC authentication enabled would hit an Assume() failure at httprpc.cpp:46.
Changed components
src/httprpc.cppsrc/rpc/request.cppsrc/rpc/request.htest/functional/interface_rpc.pydoc/JSON-RPC-interface.mdInspect captured patch +58 / −11
### doc/JSON-RPC-interface.md
@@ -89,8 +89,8 @@ protocol in v27.0 and prior releases.
| Request marker | `"version": "1.1"` (or none) | `"jsonrpc": "2.0"` |
| Response marker | (none) | `"jsonrpc": "2.0"` |
| `"error"` and `"result"` fields in response | both present | only one is present |
-| HTTP codes in response | `200` unless there is any kind of RPC error (invalid parameters, method not found, etc) | Always `200` unless there is an actual HTTP server error (request parsing error, endpoint not found, etc) |
-| Notifications: requests that get no reply | (not supported) | Supported for requests that exclude the "id" field. Returns HTTP status `204` "No Content" |
+| HTTP codes in response | `200` unless there is any kind of RPC error (invalid parameters, method not found, etc) | Always `200` unless there is an actual HTTP server error (request body is not valid JSON, endpoint not found, etc) |
+| Notifications: requests that get no reply | (not supported) | Supported for valid requests that exclude the "id" field. Returns HTTP status `204` "No Content" |
## Security
### src/httprpc.cpp
@@ -40,10 +40,12 @@ static bool g_rpc_whitelist_default = false;
static UniValue JSONErrorReply(UniValue objError, const JSONRPCRequest& jreq, HTTPStatusCode& nStatus)
{
- // HTTP errors should never be returned if JSON-RPC v2 was requested. This
- // function should only be called when a v1 request fails or when a request
- // cannot be parsed, so the version is unknown.
- Assume(jreq.m_json_version != JSONRPCVersion::V2);
+ // A request known to be JSON-RPC 2.0 gets the error in the reply with HTTP OK
+ // HTTP error statuses are only returned for 1.x requests and requests whose version is unknown.
+ if (jreq.m_json_version == JSONRPCVersion::V2) {
+ nStatus = HTTP_OK;
+ return JSONRPCReplyObj(NullUniValue, std::move(objError), jreq.id, jreq.m_json_version);
+ }
// Send error reply from json-rpc error object
nStatus = HTTP_INTERNAL_SERVER_ERROR;
### src/rpc/request.cpp
@@ -68,7 +68,17 @@ UniValue JSONRPCReplyObj(UniValue result, UniValue error, std::optional<UniValue
if (jsonrpc_version == JSONRPCVersion::V1_LEGACY) reply.pushKV("result", NullUniValue);
reply.pushKV("error", std::move(error));
}
- if (id.has_value()) reply.pushKV("id", std::move(id.value()));
+ if (id.has_value()) {
+ reply.pushKVEnd("id", std::move(id.value()));
+ } else if (jsonrpc_version == JSONRPCVersion::V2) {
+ // The request had no "id" member. This happens for notifications, and
+ // for invalid requests that left out the id (for example with a missing
+ // or non-string method name). The JSON-RPC 2.0 spec requires every
+ // response to have an "id", set to null when the request's id could not
+ // be determined, so add "id": null. For notifications this is harmless,
+ // because their replies are never sent.
+ reply.pushKVEnd("id", NullUniValue);
+ }
return reply;
}
@@ -254,4 +264,9 @@ void JSONRPCRequest::parse(const UniValue& valRequest)
params = UniValue(UniValue::VARR);
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array or object");
+
+ // A notification is a valid JSON-RPC 2.0 request without an "id" member.
+ // Invalid requests are not notifications, and get an error reply even
+ // without an id.
+ m_notification = m_json_version == JSONRPCVersion::V2 && !id.has_value();
}
### src/rpc/request.h
@@ -63,9 +63,11 @@ class JSONRPCRequest
std::string peerAddr;
std::any context;
JSONRPCVersion m_json_version = JSONRPCVersion::V1_LEGACY;
+ //! Set at the end of a successful parse() of a JSON-RPC 2.0 request without an "id" member.
+ bool m_notification{false};
void parse(const UniValue& valRequest);
- [[nodiscard]] bool IsNotification() const { return !id.has_value() && m_json_version == JSONRPCVersion::V2; };
+ [[nodiscard]] bool IsNotification() const { return m_notification; };
};
#endif // BITCOIN_RPC_REQUEST_H
### test/functional/interface_rpc.py
@@ -44,7 +44,7 @@ def format_request(options, idx, fields):
def format_response(options, idx, fields):
- if options.version == 2 and options.notification:
+ if options.version == 2 and options.notification and options.response_fields is None:
return None
response = {}
if not options.notification:
@@ -152,8 +152,10 @@ def test_batch_requests(self):
self.log.info("Testing JSON-RPC 2.0 batch with notifications...")
self.test_batch_request(lambda idx: BatchOptions(version=2, notification=idx < 2))
- self.log.info("Testing JSON-RPC 2.0 batch of ALL notifications...")
- self.test_batch_request(lambda idx: BatchOptions(version=2, notification=True))
+ self.log.info("Testing JSON-RPC 2.0 batch of requests without ids...")
+ # The request with no method (index 4) is invalid, so it is not a
+ # notification, and gets an error reply with "id": null.
+ self.test_batch_request(lambda idx: BatchOptions(version=2, notification=True, response_fields={"id": None} if idx == 4 else None))
# JSONRPC 1.1 does not support batch requests, but test them for backwards compatibility.
self.log.info("Testing nonstandard JSON-RPC 1.1 batch request...")
@@ -242,6 +244,32 @@ def test_http_status_codes(self):
# Sanity check: command was not executed
assert_equal(block_count + 1, self.nodes[0].getblockcount())
+ self.log.info("Testing error handling of requests with malformed body")
+ cases = [
+ ({}, "Missing method"),
+ ({"method": 1}, "Method must be a string"),
+ ({"method": "getblockcount", "params": 1}, "Params must be an array or object"),
+ ]
+ self.log.info("... JSONRPC 1.1 expects HTTP error codes")
+ for request, message in cases:
+ response, status = send_json_rpc(self.nodes[0], request)
+ assert_equal(response, {"result": None, "error": {"code": RPC_INVALID_REQUEST, "message": message}})
+ assert_equal(status, 400)
+ self.log.info("... JSONRPC 2.0 expects HTTP 200 with error message in response")
+ for request, message in cases:
+ for notification in [True, False]:
+ body = {"jsonrpc": "2.0", **request}
+ if not notification:
+ body["id"] = "1"
+ response, status = send_json_rpc(self.nodes[0], body)
+ expected = {"jsonrpc": "2.0", "error": {"code": RPC_INVALID_REQUEST, "message": message}}
+ if notification:
+ expected["id"] = None
+ else:
+ expected["id"] = "1"
+ assert_equal(response, expected)
+ assert_equal(status, 200)
+
def test_work_queue_exceeded(self):
self.log.info("Testing work queue exceeded...")
self.restart_node(0, ['-rpcworkqueue=1', '-rpcthreads=1'])Why this scored 41/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.