rpc: Report -rpcwhitelist denials as JSON-RPC errors #36753

pull ryanofsky wants to merge 6 commits into bitcoin:master from ryanofsky:pr/rpcdeny changing 12 files +387 −103
  1. ryanofsky commented at 12:56 PM on November 4, 2026: contributor

    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: -rpcwhitelist errors 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 -rpcwhitelist get 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 -ipcconnect receives 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-cli currently 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-cli then prints the permission error over both HTTP and IPC, with no change to the IPC interface. The fix is a small change to src/httprpc.cpp and src/rpc/protocol.h, with tests in rpc_whitelist.py and interface_ipc_cli.py. It comes after two refactoring commits suggested in #36642, which move connection fields out of JSONRPCRequest into a new JSONRPCClient struct and move the batch loop into a ProcessBatch() helper that the refused-batch reply shares. 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_PERMITTED could be named RPC_ACCESS_DENIED, and RPC_REQUEST_NOT_EXECUTED is documented as batch-specific but would fit any request refused before it runs.

  2. DrahtBot added the label RPC/REST/ZMQ on Nov 4, 2026
  3. DrahtBot commented at 12:56 PM on November 4, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

    The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

    See the guideline and AI policy for information on the review process.

    Type Reviewers
    ACK Zippo76, hodlinator
    Concept ACK pinheadmz, janb84

    If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore.

    <!--174a7506f384e20aa4161008e828411d-->

    Conflicts

    Reviewers, this pull request conflicts with the following ones:

    • #36916 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36916.svg"></sub> (test: avoid BSD ephemeral-port collisions in HTTP clients by willcl-ark)
    • #36826 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36826.svg"></sub> (rpc: Return the right RPCErrorCode more consistently by maflcko)
    • #36200 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36200.svg"></sub> (rpc: invalid credentials can occupy every HTTP worker by hodlinator)
    • #36147 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36147.svg"></sub> (ci: add native freeBSD ci job by willcl-ark)

    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.

    <!--5faf32d7da4f0f540f40219e4f7537a3-->

    LLM Linter (✨ experimental)

    Possible typos and grammar issues:

    • test/functional/rpc_whitelist.py: “May call the node methods bitcoin-cli -getinfo uses but not the wallet ones, one method that changes state, and the first of the two methods bitcoin-cli -generate calls.” → “May call the node methods used by bitcoin-cli -getinfo, one state-changing method, and the first of the two methods called by bitcoin-cli -generate, but not the wallet methods used by -getinfo.” [The original sentence makes the scope of “but not” unclear.]

    <sup>2026-11-12 17:59:43</sup>

  4. DrahtBot added the label CI failed on Nov 4, 2026
  5. DrahtBot commented at 2:13 PM on November 4, 2026: contributor

    <!--85328a0da195eb286784d51f73fa0af9-->

    🚧 At least one of the CI tasks failed. <sub>Task tidy: https://github.com/bitcoin/bitcoin/actions/runs/41833576128/job/126586635980</sub> <sub>LLM reason (✨ experimental): CI failed because clang-tidy flagged std::move(*denial) in httprpc.cpp:193 as ineffective on a const reference, and warnings are treated as errors.</sub>

    <details><summary>Hints</summary>

    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.

    </details>

  6. ryanofsky force-pushed on Nov 4, 2026
  7. ryanofsky commented at 7:08 PM on November 4, 2026: contributor

    <!-- begin push-2 -->

    Updated 8cfdc340b779dc9c31f360900d98b8d807192e9b -> 21526b182fa04f557ca3a55650ff643742b8e94d (pr/rpcdeny.1 -> pr/rpcdeny.2, compare)<!-- end --> 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/126586636207

  8. pinheadmz commented at 7:20 PM on November 4, 2026: member

    concept ACK Narrowly avoiding a merge conflict with #36758 but I think 36758 should be merged first, since this PR (36753) exposes that bug to a slightly wider use case.

  9. DrahtBot removed the label CI failed on Nov 5, 2026
  10. ryanofsky force-pushed on Nov 5, 2026
  11. ryanofsky commented at 1:01 PM on November 5, 2026: contributor

    <!-- begin push-3 -->

    Updated 21526b182fa04f557ca3a55650ff643742b8e94d -> 3667e19fe9b189662e9ca4c7931c40d348eb34e3 (pr/rpcdeny.2 -> pr/rpcdeny.3, compare)<!-- end --> 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 so bitcoin-cli -getinfo shows them, report parse errors for malformed requests in refused batches, test that a refused batch has no effect, and add a release note

  12. fametrano commented at 7:23 AM on November 10, 2026: none

    My #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.

  13. in src/httprpc.cpp:146 in 3667e19fe9
     141 | +    for (size_t i{0}; i < valRequest.size(); ++i) {
     142 | +        if (denied[i].empty()) continue;
     143 | +        const std::string& method{valRequest[i].find_value("method").get_str()};
     144 | +        if (std::ranges::find(denied_methods, method) == denied_methods.end()) denied_methods.push_back(method);
     145 | +    }
     146 | +    const std::string not_executed{strprintf("Not executed because the batch includes methods the user is not permitted to call: %s", util::Join(denied_methods, ", "))};
    


    janb84 commented at 3:26 PM on November 10, 2026:

    Think this code still has the DOS vector as highlighted by Ralph


    ryanofsky commented at 6:01 PM on November 12, 2026:

    re: #36753 (review)

    In commit "rpc: Add RPC_REQUEST_NOT_EXECUTED error for refused -rpcwhitelist batches" (711222b96fddcf0f5d86e7f4ee3a45942666bbf2)

    Think this code still has the DOS vector as highlighted by Ralph

    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.

  14. janb84 commented at 3:26 PM on November 10, 2026: contributor

    Concept ACK 3667e19fe9b189662e9ca4c7931c40d348eb34e3

  15. test: characterize -rpcwhitelist denial replies
    Add tests for what clients currently get when -rpcwhitelist refuses a
    request, so that the following commits, which change these replies, only
    need to update the expected values:
    
    - A denied request, JSON-RPC 2.0 request or notification gets HTTP 403
      with an empty body, and bitcoin-cli prints "server returned HTTP error
      403", including for -getinfo and -generate.
    - A batch including a denied request gets HTTP 403 with an empty body,
      and none of its requests run.
    - With a whitelist, a batch request missing its method fails the whole
      batch with HTTP 500, and a request that is not an object fails it with
      HTTP 400.
    - Over IPC, where bitcoin-cli gets the reply body without the HTTP
      status, the empty body is reported as a JSON type error.
    
    This change was written with Claude Opus 5.5.
    3ecef70658
  16. refactor: rpc: split client fields out of JSONRPCRequest
    Move the fields that describe the connection a request came in on (URI,
    authUser, peerAddr and the default context) into a new JSONRPCClient
    struct, and have JSONRPCRequest refer to it instead of holding copies.
    ExecuteHTTPRPC() now takes the client and creates a new request for each
    batch element instead of copying a template request, so nothing parsed
    from one element can end up in the reply to the next.
    
    JSONRPCRequest keeps its own context, which starts as the client's,
    because the wallet's RPC dispatcher replaces it with the wallet context
    before calling wallet handlers.
    
    This was suggested as a follow-up in #36642, and lets the next commit
    share the batch loop.
    
    This change was written with Claude Opus 5.5.
    e49c9aced7
  17. refactor: rpc: move batch loop into ProcessBatch()
    Move the loop that parses and executes each element of a JSON-RPC batch
    out of ExecuteHTTPRPC() into a ProcessBatch() helper, which takes the work
    to do for each parsed request as a callback. ExecuteHTTPRPC() passes
    JSONRPCExec(), so batches are handled as before.
    
    The next commits use the same helper to reply to a batch refused by
    -rpcwhitelist, so that parse errors, notifications and empty replies are
    handled in one place for both.
    
    This change was written with Claude Opus 5.5.
    8036a77077
  18. cli: report generatetoaddress errors in -generate
    bitcoin-cli -generate calls getnewaddress, then generatetoaddress, and
    builds its output from the second reply's result without checking its
    error. When generatetoaddress returns a JSON-RPC error, -generate prints
    the address with "blocks": null and exits successfully. Return the reply
    as it is when it has an error, so bitcoin-cli prints the error and exits
    with its code, as the other request handlers do.
    
    The next commit makes this reachable for users refused by -rpcwhitelist:
    a denied generatetoaddress call now gets a JSON-RPC error instead of an
    HTTP 403 status. This was found by the Ralph LLM review.
    
    This change was written with Claude Opus 5.5.
    0afef9d734
  19. rpc: Add RPC_METHOD_NOT_PERMITTED error for -rpcwhitelist denials
    Return a JSON-RPC error with a new RPC_METHOD_NOT_PERMITTED (-38) code when
    -rpcwhitelist refuses a request, with HTTP status 200 for JSON-RPC 2.0 requests
    and 403 for legacy 1.x requests. Previously every refused request got an empty
    body and HTTP 403, so the status was the only sign of the refusal.
    
    This makes a whitelist denial follow the rule every other failed method call
    has followed since bf1a1f16624 (#27101): the error goes in the response body,
    and a 2.0 request gets HTTP 200 unless the HTTP request itself is invalid. A
    refused 2.0 notification gets HTTP 204 and no body, like other notifications.
    JSONErrorReply() asserts this rule, and doc/JSON-RPC-interface.md documents it
    for 2.0 requests, so the 403 that refused 2.0 requests got contradicted the
    documentation. This change brings the behavior in line with it, and the
    documentation needs no change.
    
    The empty 403 reply broke bitcoin-cli in two ways. Over -ipcconnect it gets the
    reply through interfaces::Rpc::executeRpc, which carries no HTTP status, so it
    printed a JSON type error. Over HTTP it sends 2.0 for every request and stops
    at a 403 status without reading the body, so it printed only "server returned
    HTTP error 403". Both now print the permission error.
    
    The denial is reported at the point where a failing method reports its error,
    so the existing code handles the version differences and notifications, and the
    only new whitelist logic is a WhitelistDenial() check. The same requests are
    refused and their methods do not run. One difference: a request has to be parsed
    before it can be answered in its own version, so a user refused outright by
    -rpcwhitelistdefault is no longer turned away before parsing. A malformed request
    from that user now gets the usual parse error, and an empty batch gets an empty
    reply.
    
    For review:
    
    - HTTP clients that send "jsonrpc": "2.0" and check for a 403 status need to
      read the error code instead. Legacy 1.x clients see the same status as
      before, now with an error body.
    - Code name: RPC_METHOD_NOT_PERMITTED could instead be a more general
      RPC_ACCESS_DENIED. Reusing RPC_INVALID_REQUEST or RPC_METHOD_NOT_FOUND would
      conflict with JSONErrorReply(), which maps them to 400 and 404 for 1.x
      requests.
    - A batch is still refused as a whole when any of its methods is denied, so the
      permitted requests in it do not run. Running them would change which requests
      execute, not just what is reported. The next commit keeps this and reports
      the refusal per request.
    
    This issue was reported privately as part of a security audit.
    
    This change was written with Claude Opus 5.
    2badf99744
  20. rpc: Add RPC_REQUEST_NOT_EXECUTED error for refused -rpcwhitelist batches
    When -rpcwhitelist refuses a batch, return HTTP 200 with an array holding one
    error per request: RPC_METHOD_NOT_PERMITTED for each denied method and a new
    RPC_REQUEST_NOT_EXECUTED (-39) code for the other requests, which did not run.
    The -39 message names up to three of the denied methods too, because batch
    clients like bitcoin-cli -getinfo show only the first error. It names no more,
    and skips long names, because it is repeated in every held-back request's error
    and would otherwise let one batch ask for a reply quadratic in its size.
    Previously the whole batch got HTTP 403 and a single error object (an empty
    body before the previous commit). The batch is still refused as a whole before
    any request runs, so a refused batch has no partial effect.
    
    Batches report every other error per request in an HTTP 200 response, whatever
    the JSON-RPC version, and batch clients cannot read a single error object.
    bitcoin-cli -getinfo sends a batch, so a refused one reported "Batch must be an
    array" from JSONRPCProcessBatchReply over -ipcconnect, and "server returned
    HTTP error 403" over HTTP. It now prints the permission error. Every denial in
    the batch is reported, not only the first, so one reply names every method the
    caller needs to drop.
    
    The authorization pass also no longer fails the whole batch on a malformed
    request. It threw for a request that was not an object, and let an absent or
    non-string method field throw out of get_str(), which failed the whole batch
    with HTTP 400 or 500. Without a whitelist those requests are reported
    individually and the rest of the batch still runs. The pass now leaves them to
    the loop that executes the batch, and a refused batch reports their parse
    errors the same way, so both paths agree. Nothing slips past the check: parsing
    such a request fails there before its method would run.
    
    Requests without an id are left out of the reply, because JSON-RPC 2.0 gives
    notifications no response, so a refused batch of only notifications gets HTTP
    204 and no body, like an executed one.
    
    For review:
    
    - The status of a refused 1.x batch changes from 403 to 200 too, matching how
      1.x batches report every other error.
    - RPC_REQUEST_NOT_EXECUTED is documented as batch-specific, but the name would
      also fit any request refused before it runs.
    
    This issue was reported privately as part of a security audit.
    
    This change was written with Claude Opus 5.
    711222b96f
  21. Zippo76 commented at 9:18 PM on November 10, 2026: none

    Concept ACK

    Tested 3667e19fe9 on macOS 27.2 arm64 against master 117c54d4c5.

    rpc_whitelist.py fails on master and passes with this PR. Manual checks with curl confirmed errors -38 and -39, HTTP 403 for JSON-RPC 1.0 requests, and HTTP 200 for JSON-RPC 2.0 requests and batches. bitcoin-cli reports the RPC errors. A user denied access to all methods receives -38 (“User is not permitted to call any methods”), including for each element of a batch.

    I also measured the response-size and memory amplification noted in the Ralph review. For batches containing N allowed calls and N distinct forbidden method names:

    N Request size Response size Peak observed RSS
    800 92 KB 8.5 MB 69 MB
    1600 184 KB 33.7 MB 200 MB
    3200 370 KB 134 MB 706 MB

    RSS was sampled every 20 ms. On the PR, RSS was approximately 22 MB before the full series, which started at N=100; it was not measured immediately before the N=3200 batch. On master, these requests returned HTTP 403 with an empty body, and RSS remained roughly stable, increasing from 62 MB to 67 MB over the full series.

    Across the run, the PR produced 6,300 “not allowed to call” warnings in debug.log, versus 6 on master. A separate batch containing 1,000 allowed calls and one forbidden method with a 10,000-character name produced a 10 MB response from a 68 KB request.

    For bitcoin-cli -generate, I observed:

    Case Master PR
    User allowed only getnewaddress HTTP error 403, exit 1 "blocks": null, exit 0
    Unrestricted user, out-of-range block count "blocks": null, exit 0 "blocks": null, exit 0

    The second case confirms that the bitcoin-cli -generate handler already masks errors from generatetoaddress on master. This PR also exposes that existing behavior for whitelist rejections.

    I did not test the IPC path or the reported abort in Debug builds.

  22. ryanofsky force-pushed on Nov 12, 2026
  23. in src/httprpc.cpp:145 in 711222b96f
     147 | +    UniValue reply{UniValue::VARR};
     148 | +    for (size_t i{0}; i < batch.size(); ++i) {
     149 | +        UniValue response;
     150 | +        // Each element gets its own request, so that nothing parsed from one
     151 | +        // element ends up in the reply to the next
     152 | +        JSONRPCRequest req{client};
    


    ryanofsky commented at 6:01 PM on November 12, 2026:

    re: #36753 (comment)

    In commit "refactor: rpc: move batch loop into ProcessBatch()" (8036a77077723194f36b3089e66df9d1c6b25dbb)

    I ran janb84's batches against each PR and their merge ... with both, each user gets the null id.

    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.

  24. ryanofsky commented at 6:21 PM on November 12, 2026: contributor

    Thanks for the reviews!

    <!-- begin push-4 -->

    Rebased 3667e19fe9b189662e9ca4c7931c40d348eb34e3 -> 711222b96fddcf0f5d86e7f4ee3a45942666bbf2 (pr/rpcdeny.3 -> pr/rpcdeny.4, compare)<!-- end --> after #36642 was merged:

    • Added a first commit with characterization tests of the current replies, so the later commits' test changes only update expected values.
    • Added two refactoring commits suggested in #36642: a JSONRPCClient struct, so each batch element gets a fresh request without copying anything, and a ProcessBatch() helper shared by executed and refused batches.
    • Bounded the -39 error to at most three short denied method names. Listing all of them in every held-back request's error made the reply size quadratic (reported by janb84 and Ralph).
    • Added a commit fixing bitcoin-cli -generate, which ignored errors from generatetoaddress and 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() in JSONErrorReply() by #36758.

  25. Zippo76 commented at 9:47 AM on November 14, 2026: none

    tACK 711222b96f

    Tested on macOS 27.2.1 arm64 against master 9183edd25e. Both rpc_whitelist.py and interface_ipc_cli.py from this PR fail on master and pass with this PR.

    Retested the cases from my November 10 review:

    Case Previous results (3667e19fe9) Current results (711222b96f)
    Response size, N = 800 / 1600 / 3200 8.5 / 33.7 / 134 MB 243 / 488 / 978 KB
    Peak observed RSS at N = 3200 706 MB 36 MB; 23 MB before the full series
    1,000 allowed calls plus one forbidden method with a 10,000-character name 10 MB response 179 KB response
    -generate, user allowed only getnewaddress "blocks": null, exit 0 Error -38 for generatetoaddress, exit 38
    -generate, unrestricted user with an out-of-range block count "blocks": null, exit 0 Error -1, "JSON integer out of range", exit 1

    Response 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.

  26. DrahtBot requested review from pinheadmz on Nov 14, 2026
  27. DrahtBot requested review from janb84 on Nov 14, 2026
  28. in test/functional/interface_ipc_cli.py:29 in 711222b96f
      23 | @@ -24,16 +24,39 @@ def setup_nodes(self):
      24 |          self.extra_init = [{"ipcbind": True}]
      25 |          super().setup_nodes()
      26 |  
      27 | -    def test_cli(self, args, error=None):
      28 | +    def test_cli(self, args, error=None, call=None, expected=None, returncode=None):
      29 |          # Intentionally set wrong RPC password so only IPC not HTTP connections work
      30 | -        args = [self.binary_paths.bitcoincli, f"-datadir={self.nodes[0].datadir_path}", "-rpcpassword=wrong"] + args + ["echo", "foo"]
      31 | +        args = [self.binary_paths.bitcoincli, f"-datadir={self.nodes[0].datadir_path}", "-rpcpassword=wrong"] + args + (call or ["echo", "foo"])
    


    hodlinator commented at 6:13 PM on November 16, 2026:

    nit: Long line, made me almost miss where call was used:

            args = [self.binary_paths.bitcoincli, f"-datadir={self.nodes[0].datadir_path}", "-rpcpassword=wrong"] + \
                   args + (call or ["echo", "foo"])
    
  29. in test/functional/interface_ipc_cli.py:90 in 711222b96f
      85 | @@ -63,6 +86,9 @@ def run_test(self):
      86 |  
      87 |              self.stop_node(0)
      88 |  
      89 | +        self.start_node(0)
      90 | +        self.test_whitelist()
    


    hodlinator commented at 6:21 PM on November 16, 2026:

    nit: Could extract the rest of run_test() into test_errors() to keep things clean?

    <details><summary>Diff (looks like moving test_whitelist(), but it's actually extracting test_errors())</summary>

    --- a/test/functional/interface_ipc_cli.py
    +++ b/test/functional/interface_ipc_cli.py
    @@ -35,28 +35,7 @@ class TestBitcoinIpcCli(BitcoinTestFramework):
             assert_equal(result.stderr, None)
             assert_equal(result.returncode, returncode if returncode is not None else (0 if error is None else 1))
     
    -    def test_whitelist(self):
    -        """A method the caller may not use, called over IPC.
    -
    -        The username bitcoin-cli sends over IPC is the -rpcuser value; it selects
    -        which -rpcwhitelist applies and is not authenticated.
    -        """
    -        self.log.info("Testing -rpcwhitelist denials over IPC")
    -        # -rpcwhitelistdefault=0 so the whitelist applies only to ipcuser and the
    -        # test framework's own cookie connection keeps working.
    -        self.restart_node(0, extra_args=["-rpcwhitelistdefault=0", "-rpcwhitelist=ipcuser:getblockcount"])
    -        # Name the socket explicitly, because -ipcconnect=auto does not find it
    -        # when the datadir path is too long and the socket is in a temporary
    -        # directory instead.
    -        args = [f"-ipcconnect=unix:{self.nodes[0].ipc_socket_path}", "-rpcuser=ipcuser"]
    -        # A permitted method still works, so the whitelist is in force.
    -        self.test_cli(args, call=["getblockcount"], expected="0\n")
    -        # The reply to a denied method has an empty body, which bitcoin-cli
    -        # reports as a JSON type error.
    -        self.test_cli(args, error="error: JSON value of type null is not of expected type object")
    -        self.restart_node(0)
    -
    -    def run_test(self):
    +    def test_errors(self):
             node = self.nodes[0]
             if node.ipc_tmp_dir:
                 self.log.info("Skipping a few checks because temporary directory path is too long")
    @@ -84,6 +63,29 @@ class TestBitcoinIpcCli(BitcoinTestFramework):
     
                 self.stop_node(0)
     
    +    def test_whitelist(self):
    +        """A method the caller may not use, called over IPC.
    +
    +        The username bitcoin-cli sends over IPC is the -rpcuser value; it selects
    +        which -rpcwhitelist applies and is not authenticated.
    +        """
    +        self.log.info("Testing -rpcwhitelist denials over IPC")
    +        # -rpcwhitelistdefault=0 so the whitelist applies only to ipcuser and the
    +        # test framework's own cookie connection keeps working.
    +        self.restart_node(0, extra_args=["-rpcwhitelistdefault=0", "-rpcwhitelist=ipcuser:getblockcount"])
    +        # Name the socket explicitly, because -ipcconnect=auto does not find it
    +        # when the datadir path is too long and the socket is in a temporary
    +        # directory instead.
    +        args = [f"-ipcconnect=unix:{self.nodes[0].ipc_socket_path}", "-rpcuser=ipcuser"]
    +        # A permitted method still works, so the whitelist is in force.
    +        self.test_cli(args, call=["getblockcount"], expected="0\n")
    +        # The reply to a denied method has an empty body, which bitcoin-cli
    +        # reports as a JSON type error.
    +        self.test_cli(args, error="error: JSON value of type null is not of expected type object")
    +        self.restart_node(0)
    +
    +    def run_test(self):
    +        self.test_errors()
             self.start_node(0)
             self.test_whitelist()
    

    </details>

  30. in src/httprpc.h:12 in 711222b96f
       6 | @@ -7,7 +7,7 @@
       7 |  
       8 |  #include <any>
       9 |  
      10 | -class JSONRPCRequest;
      11 | +struct JSONRPCClient;
      12 |  class UniValue;
      13 |  enum HTTPStatusCode : int;
    


    hodlinator commented at 6:43 PM on November 16, 2026:

    nanonit: Would sort structs last:

    class UniValue;
    enum HTTPStatusCode : int;
    struct JSONRPCClient;
    
  31. in src/rpc/request.h:61 in 711222b96f
      56 | + * Client that sent a JSON-RPC request: the connection-level fields shared by
      57 | + * every request in an HTTP body or IPC call, including every element of a
      58 | + * batch.
      59 | + */
      60 | +struct JSONRPCClient
      61 | +{
    


    hodlinator commented at 6:45 PM on November 16, 2026:

    nanonit: Coding style and .clang-format (13f36c020f0329b5e975282b45292fdf2a495e31) suggests:

    struct JSONRPCClient {
    
  32. in src/httprpc.cpp:178 in 711222b96f
     180 | +
     181 | +//! Maximum number of denied methods named in the error for a request held back
     182 | +//! by a refused batch.
     183 | +static constexpr size_t MAX_NAMED_DENIED_METHODS{3};
     184 | +//! Longest method name quoted in that error. RPC method names are much shorter.
     185 | +static constexpr size_t MAX_NAMED_METHOD_LENGTH{64};
    


    hodlinator commented at 9:31 AM on November 17, 2026:

    No reason for these to live outside the scope of WhitelistErrorBatch()?

  33. in src/httprpc.cpp:211 in 711222b96f
     213 | +    }
     214 | +    std::string methods{util::Join(named, ", ")};
     215 | +    const size_t unnamed{seen.size() - named.size()};
     216 | +    if (unnamed > 0 && !named.empty()) {
     217 | +        methods += strprintf(" and %d more", unnamed);
     218 | +    } else if (unnamed > 0) {
    


    hodlinator commented at 9:48 AM on November 17, 2026:

    nit: This if condition is essentially if (named.empty()) (and unnamed > 0).

    Seems clearer:

    --- a/src/httprpc.cpp
    +++ b/src/httprpc.cpp
    @@ -206,10 +206,12 @@ static UniValue WhitelistErrorBatch(const UniValue& valRequest, const std::vecto
         }
         std::string methods{util::Join(named, ", ")};
         const size_t unnamed{seen.size() - named.size()};
    -    if (unnamed > 0 && !named.empty()) {
    -        methods += strprintf(" and %d more", unnamed);
    -    } else if (unnamed > 0) {
    -        methods = unnamed == 1 ? "1 method with a long name" : strprintf("%d methods with long names", unnamed);
    +    if (unnamed > 0) {
    +        if (!named.empty()) {
    +            methods += strprintf(" and %d more", unnamed);
    +        } else {
    +            methods = unnamed == 1 ? "1 method with a long name" : strprintf("%d methods with long names", unnamed);
    +        }
         }
         const std::string not_executed{strprintf("Not executed because the batch includes methods the user is not permitted to call: %s", methods)};
     
    
  34. hodlinator approved
  35. hodlinator commented at 10:38 AM on November 17, 2026: contributor

    ACK 711222b96fddcf0f5d86e7f4ee3a45942666bbf2

    This 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)!

  36. DrahtBot added the label Needs rebase on Nov 27, 2026
  37. DrahtBot commented at 1:09 PM on November 27, 2026: contributor

    <!--cf906140f33d8803c4a75a2196329ecb-->

    🐙 This pull request conflicts with the target branch and needs rebase.


github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-12-01 02:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me