mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
rpc: handle malformed jsonrpc 2.0 requests correctly #36758
No reviewers
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36758
Loading…
Reference in a new issue
No description provided.
Delete branch "jsonrpc-assume-2.0"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
While reviewing #36642 I found something else we missed in JSON-RPC 2.0:
If we receive a malformed request we would assume that we couldn't parse it's jsonrpc version and send an HTTP error. This is how the legacy jsonrpc server worked (despite that behavior not ever being part of any ratified jsonrpc spec) and we maintain it as Bitcoin "legacy" jsonrpc protocol. However it's possible to form a request that does properly indicate jsonrpc 2.0 but is still malformed. In that case, we should not send an HTTP error: the correct protocol is to respond with
HTTP 200 OKand include the jsonrpc error message in the response.The solution is to check if we know the request's jsonrpc version before responding with an error.
We already correctly handle such malformed requests in batches and this is already tested in
test_batch_requests()ininterface_rpc.pyOn master, the functional test in this PR actually crashes the node because the assumption is codified. Note that this crash requires:
So this is not an urgent security fix, but a bug that might disrupt testing.
In release builds the node doesn't crash, but it returns HTTP 400 with a JSON-RPC 2.0 error body instead of HTTP 200.
Earlier concerns remain unresolved; see the Run archive linked from the Review report.
🔵 Suggestion · The HTTP-status row omits the
-rpcwhitelistbatch exceptionThe narrowed HTTP-error exception omits pre-existing behavior: an authenticated user with an
-rpcwhitelistentry can still receive one legacy HTTP 400/500 error for a valid-JSON batch containing a malformed element.Location:
doc/JSON-RPC-interface.md:92(head).🔵 Suggestion · All-notification batches lose HTTP 204 coverage
The revised no-ID batch expects an error reply for its malformed element, leaving
interface_rpc.pywithout coverage of the batch branch that returns HTTP 204 with no body.Location:
test/functional/interface_rpc.py:158(head).🔵 Suggestion · JSON-RPC 2.0 response changes lack a release note
Authenticated clients sending malformed JSON-RPC 2.0 requests see changed release-build responses, but the documentation update describes current behavior without announcing the compatibility change in a release note.
Location:
doc/JSON-RPC-interface.md:93(head).Review coverage was incomplete.
Reviewed:
7611c965535c· Review report · Previous reportspermalink
Code review ACK
02380237dd. Thanks for finding and fixing this!It makes sense to merge this before #36753, which moves the
-rpcwhitelistdefaultcheck after parsing, so more users can reach this code. I'll rebase that PR on this one.The suggestions below are all optional. The main one is to fix this in
JSONErrorReply()instead of adding another try/catch, so it covers every error thrown after the version is known, and #36753 could use it as well.In commit "rpc: handle malformed jsonrpc 2.0 requests correctly" (
02380237dd)Instead of adding a third place that converts a caught error into a reply (with the batch loop and the outer catch), it could be simpler to make
JSONErrorReply()do the right thing for 2.0 requests, replacing theAssumewith the behavior it asserts. Then thisparse()call can stay as it was, and any error thrown after the version is known gets the 2.0 treatment, not just parse errors. Suggested diff from master:This would also help #36753, which currently builds the 2.0 reply for a whitelist denial itself and could just throw the error for both versions.
I tested this diff together with the PR's test changes:
interface_rpc.py, including the new tests, andrpc_whitelist.pypass in a debug build.In commit "rpc: handle malformed jsonrpc 2.0 requests correctly" (
02380237dd)nit: The JSON-RPC 1.1 vs 2.0 table says 2.0 requests get HTTP 200 "unless there is an actual HTTP server error (request parsing error, endpoint not found, etc)", which could be read as covering the malformed requests tested here. Probably makes sense to update that documentation to say "request body is not valid JSON" instead, to match the behavior after this PR.
In commit "rpc: handle malformed jsonrpc 2.0 requests correctly" (
02380237dd)Since this commit only adds test cases, it's hard to tell from the diff what behavior it changes. Could the commit message say what these requests did before? The PR description explains it, but the commit only has a subject line. Something like:
The test comments could explain more too. The notification case confused me most: it wasn't clear why
{"jsonrpc": "2.0"}fails to parse (it has nomethod), or how this differs from the invalid-notification case just above it, which parses fine and fails when the method runs. Also, since this case doesn't follow the JSON-RPC 2.0 spec (see the separate comment about it), the test should say so, so the behavior isn't mistaken for what the spec requires. Maybe:In commit "rpc: handle malformed jsonrpc 2.0 requests correctly" (
02380237dd)Not a blocker, but if we want to comply with the spec it seems like this case should get an error reply instead of 204. The JSON-RPC 2.0 spec's examples answer an invalid Request object with no id (
{"jsonrpc": "2.0", "method": 1, "params": "bar"}) with an error and"id": null, treating it as an invalid request rather than a notification. If we don't want to comply with the spec, the test comment should be updated to say this is intentional. The test comment suggestion includes that.Note that compatibility with previous bitcoin core releases shouldn't be a concern in this case since before this PR this request made debug builds abort on the
AssumeinJSONErrorReply(), and release builds returned HTTP 400 with a "Missing method" error and no id.ralph referenced this pull request2026-11-05 13:25:43 +00:00
The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.
External sites
Reviews
See the guideline and AI policy for information on the review process.
If your review is incorrectly listed, please copy-paste
<!--meta-tag:bot-skip-->into the comment that the bot should ignore.Conflicts
No conflicts as of last run.
push to
9b21a79587Address feedback from @ryanofsky
Much better approach thanks, taking.
good catch! adding that change to the table in the doc
I'll break out the tests into a test commit that asserts the current behavior, then update the test with the patch. Will clean up the comments too as you suggest.
Great catch and essentially another jsonrpc 2.0 bug from the spec. the second commit now ensures there is always an
idin 2.0 responses. This makes the test simpler too since all the malformed body cases have the same outcome.Ralph review mentions -rpcwhitelist which is handled in #36753
Thanks for the update! Moving the fix into
JSONErrorReply()and the new test commit both look good, and thanks for fixing the missing"id"too.I'm not re-ACKing yet because single requests and batches now disagree about what a notification is. I'd be happy with either of the options there: fixing batches too, or going back to the previous behavior for single requests and changing the notification rule separately. The other new comments are optional.
In commit "rpc: handle malformed jsonrpc 2.0 requests correctly" (
9b21a79587)nit: The Notifications row says any request without an
"id"field is a notification, but after this PR an invalid one gets an error reply, because the spec only counts valid Request objects as notifications. Maybe:In commit "rpc: handle malformed jsonrpc 2.0 requests correctly" (
9b21a79587)After this push, single requests and batches use different definitions of a notification.
{"jsonrpc": "2.0"}gets an error reply with"id": null, as the spec requires, but[{"jsonrpc": "2.0"}]still gets HTTP 204 and no reply, because the batch loop treats any 2.0 entry without an id as a notification. The spec's batch example answers invalid entries with an error too.I think it would be better not to leave it half-done: either fix batches too, or go back to the previous behavior for single requests (the previous push, or my earlier suggestion, which kept the 204) and change the notification rule in a separate PR. Fixing it everywhere seems simplest. If
parse()decides whether a request is a notification,IsNotification()is only true for valid requests, the batch loop needs no changes, andJSONErrorReply()can return 204 for notifications, so #36753 can throw the same error for both versions. Diff from master:The
HTTP_NO_CONTENTbranch inJSONErrorReply()isn't reachable yet, since valid 2.0 notifications never get there on this branch, but it makes the function correct for every 2.0 request. TheJSONRPCReplyObj()comment is the one from the separate comment about it.Resetting the fields at the start of
parse()also fixes a bug that is already on master: a batch entry that isn't an object gets an error reply with the id and version of the entry before it.[{"jsonrpc": "2.0", "method": "getblockcount", "id": 5}, 1]gets"id": 5for the1, and[{"jsonrpc": "2.0", "method": "getblockcount"}, 1]gets no reply at all.I tested this with the PR's tests plus the test changes below, which expect an error for the invalid notification in the batch tests and cover the reset.
interface_rpc.py,rpc_whitelist.py,interface_http.pyandrpc_users.pypass in a debug build.Test changes
In commit "rpc: handle malformed jsonrpc 2.0 requests correctly" (
9b21a79587)This comment was hard for me to follow. It doesn't say the branch is for requests that had no
"id"member, and it doesn't mention notifications, which also get here. Maybe:re: https://github.com/bitcoin/bitcoin/pull/36758#discussion_r4483889331
Thanks, this is better than what I suggested. I didn't think a test commit could show the old behavior since debug builds abort, but catching the disconnect and checking stderr for the failed
Assumeworks well, and the test diff in the second commit now shows exactly what changed.re: https://github.com/bitcoin/bitcoin/pull/36758#discussion_r4484432359
Thanks, this looks right for single requests. Batches still drop these requests, though, see the comment about batches.
In commit "test: assert current RPC behavior when handling malformed request body" (
bb036a9150)nit:
{**request}makes a copy that isn't needed, since the dict isn't modified, and-32600could beRPC_INVALID_REQUESTlike in the 2.0 loop below:push to
f27a0bc523:Clean up a test and some comments to address review by @ryanofsky however the biggest suggestion I did not take yet because we should review #36642 as prerequisitie.
I'm just gonna throw in the qualifier "valid" (requests) here but if you wanna push for the whole sentence I'll add it.
Heh ok this side bug is addressed in https://github.com/bitcoin/bitcoin/pull/36642 so I will focus on reviewing that, then rebase this on top to address the rest of your comment here.
Very clear thanks
Cleaning this up as suggested, thanks
Concept ACK
You found this while reviewing my #36642, so with that merged today I ran this branch on master as a user with and without a whitelist (https://gist.github.com/fametrano/c15db81fbefd2f12a6d0ba9d829bda45/9a333a7c8ca8174577c5413d78f268543b670b4a). Merged onto master, the six malformed 2.0 requests of the new test get HTTP 200 with the error for both users, where master answers 400, and
interface_rpc.pypasses.For the batch fix you plan: #36753's refused-batch reply drops an invalid element without an id through its own
IsNotification()check. A "parsed" flag in the execution loop leaves that drop in place; deciding notifications inparse(), as ryanofsky suggested, fixes both.push to
f5ed688fa1tACK
f5ed688fa1ryanofsky asked that batches follow the same notification rule as single requests, and the new commit decides it in
parse(), as he suggested. I reran the probe from my last review on regtest (https://gist.github.com/fametrano/e5ebd604b25ed609b7144e53c1a23a5e/bf392bb18cdd5312a1607e09f466b75ccaab7852), with the previous head on the same master as the baseline.The six malformed 2.0 requests of the test still get HTTP 200 with the error. For a user without a whitelist, a batch element without an id that fails to parse, such as
{"jsonrpc":"2.0"}, had no reply before and now gets its error with"id":null. Valid notifications, alone or in a batch, still get 204 with no body.interface_rpc.py,rpc_whitelist.py,interface_http.pyandrpc_users.pypass.Code review ACK
f5ed688fa1. On master, a malformed JSON-RPC 2.0 request makes debug builds abort and gets an HTTP 400 in release builds. With this PR it gets an HTTP 200 reply with the error, as the spec requires, and invalid requests without an id now get an error reply instead of being treated as notifications, both alone and in batches.Thanks for the updates and for rebasing on #36642. The main remaining suggestion is to add commit messages to the second and third commits saying what behavior they change. The other comments are small test nits and can be ignored.
re: https://github.com/bitcoin/bitcoin/pull/36758#discussion_r4517122971
Thanks, "valid" is enough. No need for the rest of the sentence.
re: https://github.com/bitcoin/bitcoin/pull/36758#discussion_r4517275774
Thanks, agreed. Since #36642 every batch element gets its own copy of the unparsed request, so the reset at the start of
parse()isn't needed, and the new commit fixes the rest. Singletons and batches now agree on what a notification is.In commit "rpc: handle malformed jsonrpc 2.0 requests correctly" (
5004f241c5)Could this commit and the next one have messages saying what behavior they change? It would be nice to be able to read the log and know how the server behaved before and after each change, without having to read the PR or the spec. Maybe something like:
And for the next commit, see the separate comment.
In commit "rpc: requests that fail to parse can not be jsonrpc2.0 notifications" (
f5ed688fa1)Suggested message for this commit (see the comment about the previous one):
In commit "rpc: requests that fail to parse can not be jsonrpc2.0 notifications" (
f5ed688fa1)nit: Since
response_fieldsnow also decides whether a request without an id expects a reply,is Noneseems more accurate thannot. That way only an unset value means "no reply", andresponse_fields={}means "expect a reply with no extra fields" instead of being treated likeNone:In commit "rpc: requests that fail to parse can not be jsonrpc2.0 notifications" (
f5ed688fa1)The log message says this batch is all notifications, which is inaccurate after this commit: the batch has always included the invalid
{"pizza": "sausage"}request, which used to be dropped as a notification and now gets an error reply. Maybe the message could just say the requests have no ids.Also,
format_response()already adds thejsonrpcanderrorfields from the call's expected result, so only the id is needed inresponse_fieldsand this could be simplified to:Push to
7f7428b457:Address nits and expand commit messages per @ryanofsky feedback
👍
👍
Sure using
is NonehereTaking this, more correct comment and cleaner code thanks.
Code review ACK
7f7428b457. On master, a malformed JSON-RPC 2.0 request makes debug builds abort and gets an HTTP 400 in release builds. With this PR it gets an HTTP 200 reply with the error, as the spec requires, and invalid requests without an id now get an error reply instead of being treated as notifications, both alone and in batches.Since the last review, the only changes are the new commit messages and the two test cleanups. Thanks for taking these! One more suggestion, not a blocker: the
HTTP_NO_CONTENTbranch inJSONErrorReply()that I suggested earlier turns out to be dead code, and could be dropped from the last commit.In commit "rpc: requests that fail to parse can not be jsonrpc2.0 notifications" (
7f7428b457)I suggested adding this block in https://github.com/bitcoin/bitcoin/pull/36758#discussion_r4498229560, but I think it should be dropped, because it's dead code in this PR.
IsNotification()is only true afterparse()succeeds, and nothing that throws after a successful parse reachesJSONErrorReply(): a single 2.0 request runs withcatch_errors=true, the whitelist check returns 403 without throwing, and batch elements catch their own errors. Adding this dead code also makes it harder to understand how the real change in this commit actually works.(I included this in my earlier suggestion because I was mixing this PR up with #36753, which needs something similar when it refuses a valid notification after parsing. But it can just be added there, so
JSONErrorReplydoes not need to change at all in this commit.)ACK
7f7428b457Does indeed bring the behavior for invalid requests closer to the JSON-RPC 2.0 spec.
nit: We know there is no pre-existing
idfield, so could use the quicker method here and on other such lines that are touched:nit: The reason for making
IsNotification()use a "cached" value is not blatantly obvious. Could make it clearer if you touch again. Something like:push to
7611c96553Address nits from @ryanofsky and @hodlinator thank you!
Good catch, checked with an
assert(false)here. A request can only be a notification now ifparse()succeeds. Ifparse()succeeds there is no otherJSONErrorReply()path beforeIsNotification()returns early.nice little optimization here, skipping
UniValue::findKey()thanks.sure, this is much more clear.
Code review ACK
7611c96553. Nice, targeted fixes for JSON-RPC server handing malformed JSON-RPC 2.0 requests incorrectly. The first commit just adds test coverage. The second commit makes malformed single requests return JSON errors instead of HTTP errors and avoid crashing debug builds. The third commit makes malformed batch subrequests without ids return errors instead of being treated like notifications and returning nothing.Since the last review, the unreachable
HTTP_NO_CONTENTbranch was dropped, so the last commit no longer touchesJSONErrorReply(), and hodlinator's two suggestions were applied. Thanks for the updates!re-ACK
7611c96553Changes since first review:
UniValuefieldsJSONRPCRequest::m_notificationcommentACK
7611c96553Makes the behavior for invalid requests more JSON-RPC 2.0 compliant.
Only one optional hardening remark, don't think it's big enough to invalidate the ACKs for it.
Hardening option:
Consider resetting
m_notificationat the top of parse() so it doesn't depend on callers passing a fresh object."re: https://github.com/bitcoin/bitcoin/pull/36758#discussion_r4773174350
Agree this would be nice hardening, and that it isn't worth a push here: both callers parse a fresh object since #36642. If we do add it, it should probably reset
idandm_json_versiontoo, becauseparse()throws before setting them when the request isn't an object, so a reused object would still reply with the previous id. I can add that to #36753, which touchesparse()anyway.In commit "rpc: requests that fail to parse can not be jsonrpc2.0 notifications" (
7611c96553)Not a blocker, could be a follow-up: now that entry 4 here gets an error reply, no batch test reaches the HTTP 204 "all notifications" branch any more, since every remaining batch expects at least one response. The Ralph review noticed this. Adding back a batch of only the valid notifications would cover it, e.g.:
post-merge crACK
7611c96553