mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 16:02:38 +00:00
rpc: Report -rpcwhitelist denials as JSON-RPC errors #36753
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!36753
Loading…
Reference in a new issue
No description provided.
Delete branch "pr/rpcdeny"
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?
This PR adds two JSON-RPC error codes for requests refused by
-rpcwhitelist, which until now got an HTTP 403 status with an empty body:RPC_METHOD_NOT_PERMITTED(-38) is returned for a refused request, with HTTP 200 for JSON-RPC 2.0 requests and 403 for legacy 1.x requests.RPC_REQUEST_NOT_EXECUTED(-39) is returned for the other requests in a refused batch. A refused batch now gets HTTP 200 and an array with an error for each request, and still runs none of them.Problem:
-rpcwhitelisterrors are currently handled differently from other JSON-RPC errors, so clients report them with vague or misleading messages, and for JSON-RPC 2.0 requests the handling does not follow documented behavior. Specifically, requests refused by-rpcwhitelistget HTTP 403 with an empty body, so the refusal shows up as a generic transport error rather than a specific JSON-RPC error. This is especially a problem for JSON-RPC 2.0 requests, which are supposed to report failed method calls only as JSON-RPC errors, not HTTP errors. The empty reply causes a concrete problem when JSON-RPC requests are sent over IPC instead of HTTP:bitcoin-cli -ipcconnectreceives only the response body, so a refused call prints a JSON type error instead of a permission error, as described in a private security review. Over HTTP,bitcoin-clicurrently stops at the 403 status and prints only "server returned HTTP error 403" instead of the actual error.Solution: Report whitelist denials like any other failed call: a JSON-RPC error in the body, with the HTTP status the request's version calls for. This brings the behavior in line with the documentation.
bitcoin-clithen prints the permission error over both HTTP and IPC, with no change to the IPC interface. The first commit documents how batch requests work, since the documentation didn't mention them. The second adds tests for the current replies, so the later commits' test changes show how each reply changes. Two refactoring commits follow: one suggested in #36642 moves connection fields out ofJSONRPCRequestinto a newJSONRPCClientstruct, and one moves the batch handling out ofExecuteHTTPRPC()into anExecuteBatch()function. Between them, a small commit makesJSONRPCRequest::parse()reset the fields it sets, so a reused request object can't answer with an earlier request's id. A smallbitcoin-clifix makes-generatereport errors fromgeneratetoaddress, which it ignored. The last two commits make the change, insrc/httprpc.cppandsrc/rpc/protocol.h. Details in the commit messages.Compatibility: HTTP clients that send
"jsonrpc": "2.0"or batches and check for a 403 status need to read the error code instead. Single 1.x requests keep the 403 status, now with an error body.Open question for review:
RPC_METHOD_NOT_PERMITTEDcould be namedRPC_ACCESS_DENIED, andRPC_REQUEST_NOT_EXECUTEDis documented as batch-specific but would fit any request refused before it runs.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
Reviewers, this pull request conflicts with the following ones:
If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.
🔵 Suggestion · Default-denied users have no batch authorization coverage
Batches from users denied by
-rpcwhitelistdefault=1now depend on per-element authorization, but every default-deny assertion sends a single request.Location:
test/functional/rpc_whitelist.py:297(head).🔵 Suggestion · The IPC denial test never exercises a batch reply
The new IPC test covers only single requests, leaving the advertised
bitcoin-cli -getinfo -ipcconnectrefusal behavior without end-to-end regression coverage.Location:
test/functional/interface_ipc_cli.py:87(head).🔵 Suggestion · Refused-batch documentation omits parse-error precedence
The batch documentation promises
-38or-39for every request, but malformed elements retain their parse errors and notifications receive no reply.Location:
doc/JSON-RPC-interface.md:107(head).🔵 Suggestion · The batch-reply commit also changes malformed-batch execution
Commit
7c1c2320combines a change to which requests execute in malformed batches with the new error format for refused batches.Location: src/httprpc.cpp:199 (commit).
Review coverage was incomplete.
Reviewed:
7c1c2320ecc5· Review report · Previous reportspermalink
🚧 At least one of the CI tasks failed.
Task
tidy: https://github.com/bitcoin/bitcoin/actions/runs/41833576128/job/126586635980LLM reason (✨ experimental): CI failed because clang-tidy flagged
std::move(*denial)inhttprpc.cpp:193as ineffective on a const reference, and warnings are treated as errors.Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
An intermittent issue.
Leave a comment here, if you need help tracking down a confusing failure.
Updated
8cfdc340b7->21526b182f(pr/rpcdeny.1->pr/rpcdeny.2, compare) to fix CI: drop a no-op std::move flagged by clang-tidy https://github.com/bitcoin/bitcoin/actions/runs/41833576128/job/126586635980; and pass the IPC socket path explicitly in the new interface_ipc_cli.py whitelist test, since -ipcconnect=auto can't find it when the datadir path is too long https://github.com/bitcoin/bitcoin/actions/runs/41833576128/job/126586636207concept ACK
Narrowly avoiding a merge conflict with https://github.com/bitcoin/bitcoin/pull/36758 but I think 36758 should be merged first, since this PR (36753) exposes that bug to a slightly wider use case.
Updated
21526b182f->3667e19fe9(pr/rpcdeny.2->pr/rpcdeny.3, compare) to address findings from the Ralph LLM review (https://review.fish.foo/traces/36753-8cfdc340b779dc9c31f360900d98b8d807192e9b-2121-1.html): name the denied methods in RPC_REQUEST_NOT_EXECUTED errors sobitcoin-cli -getinfoshows them, report parse errors for malformed requests in refused batches, test that a refused batch has no effect, and add a release noteMy #36642 gives a non-object batch element a null id, so if it lands, the batch loop here can stay as it is.
janb84 asked on #36642 for the same batch replies with or without -rpcwhitelist, and pinheadmz pointed him here. On master, a user without a whitelist gets the previous element's id on that element's error, and this PR extends that reply to whitelisted users. I ran janb84's batches against each PR and their merge (https://gist.github.com/fametrano/2fc9fb4e35b060c3870aaf198668c271/dd9a540a099199d4293f6854f543915a838b0fbb): with both, each user gets the null id. The two merge cleanly (tree 1042df97fa), and either can land first.
Concept ACK
3667e19fe9Think this code still has the DOS vector as highlighted by Ralph
Thanks for the reviews!
Rebased
3667e19fe9->711222b96f(pr/rpcdeny.3->pr/rpcdeny.4, compare) after #36642 was merged:JSONRPCClientstruct, so each batch element gets a fresh request without copying anything, and aProcessBatch()helper shared by executed and refused batches.bitcoin-cli -generate, which ignored errors fromgeneratetoaddressand reported success when it was denied (Ralph).The other two findings in that Ralph review are fixed elsewhere: non-object batch elements reusing the previous id by #36642, and malformed 2.0 requests reaching the
Assume()inJSONErrorReply()by #36758.re: https://github.com/bitcoin/bitcoin/pull/36753#issuecomment-6761562101
In commit "refactor: rpc: move batch loop into ProcessBatch()" (
8036a77077)Thanks for checking. This PR is now based on #36642, and the reply to a refused batch goes through the same
ProcessBatch()loop, so both paths give a non-object element a null id.re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4526778129
In commit "rpc: Add RPC_REQUEST_NOT_EXECUTED error for refused -rpcwhitelist batches" (
711222b96f)Thanks, you're right. The -39 message listed every denied method and was repeated in each held-back request's error, so the reply could grow with the product of the two. It now names at most three short methods and says how many more there are, so the reply grows linearly with the batch. There's a new test for it.
tACK
711222b96fTested on macOS 27.2.1 arm64 against master
9183edd25e. Bothrpc_whitelist.pyandinterface_ipc_cli.pyfrom this PR fail on master and pass with this PR.Retested the cases from my November 10 review:
3667e19fe9)711222b96f)-generate, user allowed onlygetnewaddress"blocks": null, exit 0generatetoaddress, exit 38-generate, unrestricted user with an out-of-range block count"blocks": null, exit 0Response size now scales linearly across the tested batch sizes.
For batches containing a non-object element, master returns HTTP 400 for the entire batch for the restricted user, while the unrestricted user receives per-element responses. With this PR, both users receive the same per-element responses with HTTP 200. The basic whitelist checks from my previous review still behave as expected.
ACK
711222b96fThis change primarily fixes the error handling bug for RPC over IPC where we get an unexpected JSON value when a user is blocked from executing an RPC due to the whitelist. It also implements much finer grained error reporting when it comes to batched requests and corrects HTTP status codes returned upon permission failure to match the JSON-RPC-interface.md docs. (interface_rpc.py is unchanged by this PR and already demonstrates fine-grained batch errors with expected HTTP status codes).
Happy you implemented a variant of my suggestion to split the client's fields from the requests (with more correct handling of
context)!No reason for these to live outside the scope of
WhitelistErrorBatch()?nit: This if condition is essentially
if (named.empty())(andunnamed > 0).Seems clearer:
nanonit: Would sort
structs last:nanonit: Coding style and .clang-format (
13f36c020f) suggests:nit: Long line, made me almost miss where
callwas used:nit: Could extract the rest of
run_test()intotest_errors()to keep things clean?Diff (looks like moving test_whitelist(), but it's actually extracting test_errors())
🐙 This pull request conflicts with the target branch and needs rebase.
code review at
711222b96fStill waiting for #36758 merge and rebase on top of that but I wanted to get this PR into my brain today. I left several questions and a few nits. I also agree with @Zippo76 about perhaps logging too much.
Built and tested on macos/arm64, manually tested the behavior change with eccentric RPC requests and batches. I still need to test the IPC behavior locally and try some mutations against the tests.
0afef9d734Remark: this logic already exists for the other "macros" -getinfo -netinfo -getaddrinfo
e49c9aced7I was confused by this comment at first but I think its indicative of this whole function trying to do too much with the batch processing and its own try/catch nested inside the singleton request logic. Maybe you clean that up in another commit in this PR... But it'd be nice if it were simpler
8036a77077I don't understand passing a handler-lambda here instead of just calling
JSONRPCExec()directly inProcessBatch()Also, and maybe this is coming up in another commit, it seems like we could just go directly to
ProcessBatch()early ifvalRequest.isArray()and handle the whitelist auth inProcessBatch()711222b96fThis is all pretty amusing actually and feels over-engineered but the kind of over-engineering I'm getting used to expecting from LLMs ;-) I played around with different combinations of requests in batches and it's honestly impressive how generously verbose the response is.
One thing I noticed is
{"method":""}will get"User is not permitted to call method "orthe user is not permitted to call: and 2 more"which I think can be cleaned up with single quotes around the rejected method names.Unless we should be rejecting empty method names for some lower level syntax reason...
e49c9aced7bikeshedding nit: These data describe an HTTP request I think, not to be confused with a jsonrpc request which there might be more than one of in a batch contained in the total payload from the client. Just something about
URI,authUser, andcontextfields which don't really describe a client.However we are already using
HTTPClientandHTTPRequestin the codebase and the rest of this PR usesclientso I dunno. Even calling itHTTPContextwith fieldnodeContextmight be more clear.3ecef70658as long as you're here you can swap in the new
HTTPConnectionhelper fromnetutil.pysee #369163ecef70658looks like you only use this along with
assert_equal, could just call the functionassert_replyand do the check here? Not a huge change but a function called "reply" I expect to some data back to someone.Thanks for the reviews!
Rebased
711222b96f->dfcdc8b80a(pr/rpcdeny.4->pr/rpcdeny.5, compare) after #36758 was merged, with changes from review:ExecuteHTTPRPC()as pinheadmz suggested. The third commit now moves the whole batch branch, including the-rpcwhitelistcheck, into anExecuteBatch()function that callsJSONRPCExec()directly, replacingProcessBatch()and its callback. A refused single request now throws its error for both JSON-RPC versions and letsJSONErrorReply()answer it, which works now that #36758 madeJSONErrorReply()handle 2.0 requests.JSONRPCRequest::parse(), suggested by janb84 on #36758.doc/JSON-RPC-interface.md, which didn't mention them: requests in a batch are handled independently, except that a batch with a refused method is refused as a whole. The-rpcwhitelisttext there now names the -38 error.reply()test helper toparse_response().re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4774344375
Right, this just makes
-generatecheck for an error reply the way the other handlers already do. It was the odd one out, so it turned errors from its second call into"blocks": nulland exit code 0.re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4772820544
Thanks, the latest push gives
ExecuteHTTPRPC()that shape. It declares the request, then inside thetryhands an array toExecuteBatch()(see the other thread), and parses and runs a single request. The denial is now just athrowfor both JSON-RPC versions, so thecatchblocks build every error reply from the request throughJSONErrorReply(). I also rewrote the comment abovejreqto say what it is used for.In commit "rpc: Add RPC_REQUEST_NOT_EXECUTED error for refused -rpcwhitelist batches" (
dfcdc8b80a)re: https://github.com/bitcoin/bitcoin/pull/36753#pullrequestreview-6154256166
Agreed, and thanks @Zippo76 for measuring it. The latest push logs only the first denial in a batch, as master did when it stopped at the first one, so a refused batch writes one warning however many denied requests it has. The test checks that the second denial isn't logged.
re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4774215330
Agreed, this is better, and it's what the latest push does. The lambda was only there so the refused-batch reply in the last commit could reuse the loop, but that's simpler as a branch inside the loop. The third commit now moves the whole batch branch, including the whitelist check, into an
ExecuteBatch()function that callsJSONRPCExec()directly, andExecuteHTTPRPC()returns it as soon as it sees an array. The last commit changesExecuteBatch()in place.re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4597846978
Thanks, took this and your other five suggestions in the latest push: the wrapped
test_cli()line,test_errors(), the forward declaration order, the struct brace, and the constants, which now live inside the function that builds this message (NotExecutedMessage(), which replacedWhitelistErrorBatch()when the batch code was restructured).re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4775400797
Thanks, the latest push quotes the method names in both messages (
... call method '') and adds a test for an empty name.This is one of the areas where I find myself agreeing more with LLMs than with other developers. I think we often don't distinguish between different kinds of complexity and push back on all of it, when only one kind is really a problem. Complexity that's spread out, through shared state or logic split across many places, makes a codebase hard to understand and work with. Complexity that's encapsulated behind a single function or class interface can make software easier to use, not harder, in the context of the larger system. This function is an example of the second kind: it's internally fiddly, but it's a local helper that changes no state, takes the batch and returns an error string, and its only job is to give users clear feedback.
Without this feedback, clients like
bitcoin-cli -getinfoonly show the first error in a batch reply, and that's usually a held-back request's -39 error rather than the -38 error for the method that was actually denied. So the -39 message names the denied methods, so the user can tell which call to drop (wallet calls, in the-getinfocase). The cap on how many names it lists, and how long they can be, is there because the message is repeated in every held-back request's error, which made the reply size quadratic before janb84 pointed it out in https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4526778129.Note: while writing the test I noticed that a trailing comma in
-rpcwhitelist(asuser1in this test has) permits the empty method name, since the empty field after the comma ends up in the whitelist. That's harmless (the call then fails with "Method not found") and is unchanged by this PR.re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4776008806
They describe the HTTP request for HTTP callers, but not every caller is HTTP:
bitcoin-cli -ipcconnectrequests come in throughRpcImpl::executeRpcover IPC, andChainImpl::executeRpcfills it in for internal calls, so I'd avoid anHTTPname. The idea of "client" is the thing that sent the request, which every element of a batch shares. I don't feel strongly about the name, though, so happy to change it if you have a better one.re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4772269816
Done. #36916 already switched this file to the
netutil.pyhelper on master, and the rebase keeps it inrpcpost().re: https://github.com/bitcoin/bitcoin/pull/36753#discussion_r4772418387
Good point, renamed it to
parse_response(). I kept it returning the value instead of making itassert_reply(), because a few checks look at one element of the result (parse_response(resp)[1][0]["error"]) instead of comparing the whole reply.🚧 At least one of the CI tasks failed.
Task
tidy: https://github.com/bitcoin/bitcoin/actions/runs/47139517821/job/144370827671LLM reason (✨ experimental): tidy_fail: clang-tidy reports
bugprone-use-after-moveinhttprpc.cpp(treated as an error).Hints
Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:
Possibly due to a silent merge conflict (the changes in this pull request being
incompatible with the current code in the target branch). If so, make sure to rebase on the latest
commit of the target branch.
A sanitizer issue, which can only be found by compiling with the sanitizer and running the
affected test.
Intermittent network issues can occur; re-run CI for now, and report the issue if they keep happening.
A functional or integration test failure may be intermittent or unrelated to this pull request.
If no dedicated issue thread exists, create a new one to track it.
Leave a comment here, if you need help tracking down a confusing failure.
ACK
7c1c2320ecBuilt and tested on macos/arm64. Played with the new errors via http and bitcoin-cli -ipcconnect, comparing to master. It's a big improvement in the UX for RPC over IPC.
I noticed a few things that are redundant with the rebase on master (I think...?)
Also noticed some slight differences in UX between HTTP and IPC simply because
rpcpasswordis ignored over IPC, so for example over IPC an unauthorized request getsbut over HTTP that same request gets
... I don't see this as a blocker at all.
Show Signature
pinheadmz's public key is on openpgp.org
82dff38977Didn't we already determine this was dead code?
https://github.com/bitcoin/bitcoin/pull/36758#discussion_r4589017331
ec6a99140dnit Might be worth mentioning that at this point if the user is not in the whitelist, it means they can execute anything, checked by the caller
ExecuteHTTPRPC()ed0bcf6c9aHm, the changes in this commit were proposed almost exactly the same in #36642 but that PR discussion it was decided to make the caller responsible. I think this commit is a no-op since that was merged.
https://github.com/bitcoin/bitcoin/pull/36642#discussion_r4494106574
concept ACK