Skip to content

fix(rpc): add input validation and request bounds - #1343

Merged
lklimek merged 7 commits into
v1.6-devfrom
fix/rpc-request-handling
Jun 18, 2026
Merged

lklimek merged 7 commits into
v1.6-devfrom
fix/rpc-request-handling

Conversation

@lklimek

@lklimek lklimek commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

Why this PR exists

  • Problem: Several RPC entry points accepted inputs without validating ranges or bounds — an unchecked http.Hijacker type assertion, unbounded JSON-RPC batch sizes, no length bound on BlockSearch queries, a missing negative-index check in GenesisChunked, and unclamped UnconfirmedTxs pagination. Malformed or out-of-range inputs on the externally reachable RPC layer could panic a handler or do far more work than intended.
  • What breaks without it: A request carrying an oversized batch, an out-of-range pagination/index value, or hitting an environment where the response writer does not implement http.Hijacker can crash the handler goroutine or process more than necessary. These are robustness/correctness gaps, not behaviour any well-formed client depends on.
  • Blocking relationship: none. Independent change; targets v1.6-dev.

What was done

  • Validate the WebSocket Origin header against the configured allow-list before completing the connection upgrade.
  • Replace the unchecked http.Hijacker type assertion with a checked one that returns an error when hijacking is unavailable.
  • Cap JSON-RPC batch requests at 100 entries per batch.
  • Bound the BlockSearch query-string length.
  • Reject negative indices in GenesisChunked.
  • Clamp UnconfirmedTxs pagination parameters to valid ranges.
  • Added unit tests: internal/rpc/core/rpc_validation_test.go, rpc/jsonrpc/server/rpc_validation_test.go.

How Has This Been Tested?

  • go build and go test on internal/inspect/rpc, internal/rpc/core, rpc/jsonrpc/server — all pass (BLS cgo build).
  • golangci-lint with the CI configuration (--new-from-rev=origin/v1.6-dev) — 0 new issues.

Breaking Changes

None.

Checklist

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit tests
  • I have made corresponding changes to the documentation (CHANGELOG entry added)

Attribution

🤖 Co-authored by Claudius the Magnificent AI Agent

Add defensive input validation and explicit limits across RPC request
handling:

- Validate the WebSocket Origin header against the configured allow-list
  before completing the connection upgrade.
- Use a checked type assertion for the underlying http.Hijacker and return
  an error when it is unavailable, instead of an unchecked assertion.
- Cap JSON-RPC batch requests at 100 entries per batch.
- Bound the BlockSearch query-string length.
- Reject negative indices in GenesisChunked.
- Clamp UnconfirmedTxs pagination parameters to valid ranges.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f9c719fe-c859-45a3-af8c-39278209e857

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/rpc-request-handling

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@lklimek
lklimek requested a review from Copilot June 16, 2026 11:04
@lklimek
lklimek marked this pull request as ready for review June 16, 2026 11:04
@lklimek
lklimek requested a review from QuantumExplorer as a code owner June 16, 2026 11:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens externally reachable RPC endpoints by adding input validation and bounding request sizes to prevent handler panics and excessive work on malformed requests.

Changes:

  • Add a safer default WebSocket Origin policy (same-host / allow-list), and make the status writer tolerant of non-http.Hijacker transports (e.g. HTTP/2).
  • Enforce request bounds: JSON-RPC batch cap, BlockSearch query length cap, negative-index rejection for GenesisChunked, and safer UnconfirmedTxs pagination under a shrinking mempool.
  • Add targeted unit tests for the new validation/robustness behavior and update the changelog.

Reviewed changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
rpc/jsonrpc/server/ws_handler.go Introduces configurable Origin allow-list checking for WebSocket upgrades.
rpc/jsonrpc/server/rpc_validation_test.go Adds tests for HTTP/2 hijack behavior, Origin checking, and JSON-RPC batch limiting.
rpc/jsonrpc/server/http_server.go Makes the status-capturing writer implement Hijack() safely when unsupported.
rpc/jsonrpc/server/http_json_handler.go Adds a hard cap on JSON-RPC batch size.
internal/rpc/core/rpc_validation_test.go Adds tests for GenesisChunked bounds, BlockSearch query length cap, and UnconfirmedTxs pagination robustness.
internal/rpc/core/net.go Rejects negative chunk indices and fixes GenesisChunked bounds/error reporting.
internal/rpc/core/mempool.go Clamps pagination slice bounds when mempool shrinks between Size() and ReapMaxTxs().
internal/rpc/core/env.go Wires the WebSocket Origin checker to configured CORSAllowedOrigins.
internal/rpc/core/blocks.go Adds BlockSearch query length validation.
internal/inspect/rpc/rpc.go Adds a TODO around websocket disconnect unsubscription logic (but currently still risks a nil panic).
CHANGELOG.md Notes the RPC hardening change in the release changelog.

Comment thread internal/inspect/rpc/rpc.go Resolved
Comment thread internal/rpc/core/blocks.go Resolved
Comment thread rpc/jsonrpc/server/http_json_handler.go Resolved
Comment thread internal/inspect/rpc/rpc.go Resolved
- Wrap the BlockSearch maximum-query-length error with
  coretypes.ErrInvalidRequest so clients receive Invalid request instead
  of Internal error, matching the other request-validation paths.
- Reject an empty JSON-RPC batch ([]) with a single Invalid request
  response, per JSON-RPC 2.0.
- Drop the out-of-scope inspect-server TODO comment.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

<sub>🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent</sub>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 3 comments.

Comment thread rpc/jsonrpc/server/http_server.go Resolved
Comment thread internal/rpc/core/env.go Resolved
Comment thread CHANGELOG.md Resolved
@thepastaclaw

thepastaclaw commented Jun 17, 2026 •

Copy link
Copy Markdown

✅ Review complete (commit 4c2c20a)

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

Two real regressions to flag: (1) the new WebSocket OriginChecker default (same-host only) is not threaded into the light proxy or inspect RPC, so their WS endpoints quietly reject browsers that the operator's CORS allow-list (inspect) or the previous permissive default (light proxy) used to accept; (2) the batch-size cap fires only after json.Unmarshal has fully decoded the request array, so the bound on resource usage is weaker than it appears. Other agent findings were either unrelated to this PR or low-value (32-bit truncation, CORS-equivalent origin normalization).

🔴 2 blocking | 🟡 2 suggestion(s)

2 additional finding(s) omitted (not in diff).

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `internal/inspect/rpc/rpc.go`:
- [BLOCKING] internal/inspect/rpc/rpc.go:69-72: Inspect RPC WebSocket ignores configured CORSAllowedOrigins
  NewWebsocketManager now defaults to OriginChecker(nil), which only accepts same-host or Origin-less requests. The main node RPC overrides this with conf.RPC.CORSAllowedOrigins at internal/rpc/core/env.go:293, but the inspect RPC Handler registers /websocket without that override even though addCORSHandler below uses rpcConfig.CORSAllowedOrigins for HTTP. The result is that HTTP and WS disagree about which browser origins are permitted on the same externally reachable endpoint: an origin that the operator explicitly allow-listed via CORS gets accepted for HTTP and rejected with 403 at WS upgrade. Wire the configured allow-list through here (mirroring env.go:293) or take the allow-list as an argument to NewWebsocketManager so every caller is consistent.

In `light/proxy/proxy.go`:
- [BLOCKING] light/proxy/proxy.go:99-109: Light proxy WebSocket loses permissive origin default with no operator opt-out
  Before this PR the embedded Upgrader returned true for every origin, so browser clients on any host could connect to the light proxy's /websocket. After this PR the default is OriginChecker(nil), which only accepts same-host and Origin-less requests. The proxy uses rpcserver.Config (which has no CORS fields) and never adds a CORS handler, so unlike the node and inspect RPC there is no allow-list to thread in: any browser client that worked before is now silently 403'd at the WS upgrade and the operator has no configuration knob to restore it. This contradicts the PR description's "No breaking changes" claim. Either expose the allow-list (or a permissive-mode flag) to the light proxy's config and wire it into wm.CheckOrigin, or document the new restriction and provide a clear way to override.

In `rpc/jsonrpc/server/http_json_handler.go`:
- [SUGGESTION] rpc/jsonrpc/server/http_json_handler.go:46-64: Batch cap is enforced after the whole array is unmarshaled
  parseRequests calls json.Unmarshal(data, &reqs) on the full body before the len(requests) > maxBatchRequests check runs. Within the default 1MB MaxBodyBytes an attacker can fit hundreds of thousands of empty {} request objects, forcing allocation/decoding of that many RPCRequest structs before the server rejects with maxBatchRequests. The cap still prevents the expensive Call work, so this isn't a worst-case bypass, but it weakens the "request bounds" goal of this PR — the bound on parser-side work is set by MaxBodyBytes alone, not by maxBatchRequests. Consider stream-decoding the array with json.Decoder and bailing once the (maxBatchRequests+1)th element is seen, or rejecting based on a cheap pre-count.

In `rpc/jsonrpc/server/ws_handler.go`:
- [SUGGESTION] rpc/jsonrpc/server/ws_handler.go:39-55: Default WebSocket origin policy change should be called out in CHANGELOG / upgrade notes
  Previously the embedded Upgrader returned true for every origin; the new default rejects cross-origin browser requests unless the operator has the host listed in cors-allowed-origins (and even then only on call sites that wire OriginChecker through — see the two blocking findings above). The current CHANGELOG entry ("Add input validation and request bounds to the RPC layer") doesn't mention this observable behavior change for browser clients. Add a sentence to the CHANGELOG/upgrade notes calling out that browser WebSocket clients on cross-origin hosts now need to be listed in cors-allowed-origins.

Comment on lines 50 to +64
return
}

if len(requests) == 0 {
writeRPCResponse(w, logger, rpctypes.RPCRequest{}.MakeErrorf(
rpctypes.CodeInvalidRequest, "empty batch request"))
return
}

if len(requests) > maxBatchRequests {
writeRPCResponse(w, logger, rpctypes.RPCRequest{}.MakeErrorf(
rpctypes.CodeInvalidRequest,
"batch contains %d requests, but the maximum is %d", len(requests), maxBatchRequests))
return
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Suggestion: Batch cap is enforced after the whole array is unmarshaled

parseRequests calls json.Unmarshal(data, &reqs) on the full body before the len(requests) > maxBatchRequests check runs. Within the default 1MB MaxBodyBytes an attacker can fit hundreds of thousands of empty {} request objects, forcing allocation/decoding of that many RPCRequest structs before the server rejects with maxBatchRequests. The cap still prevents the expensive Call work, so this isn't a worst-case bypass, but it weakens the "request bounds" goal of this PR — the bound on parser-side work is set by MaxBodyBytes alone, not by maxBatchRequests. Consider stream-decoding the array with json.Decoder and bailing once the (maxBatchRequests+1)th element is seen, or rejecting based on a cheap pre-count.

source: ['codex']

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in this update — Batch cap is enforced after the whole array is unmarshaled no longer present.

Auto-resolved by the review system based on the latest commit diff. If you believe this was closed in error, reopen the thread.

Comment thread rpc/jsonrpc/server/ws_handler.go Resolved
lklimek and others added 2 commits June 17, 2026 12:15
…y WS origin default

The shared rpcserver.NewWebsocketManager default Origin policy is now
OriginChecker(nil) (same-host / Origin-less only), which regressed two
websocket entry points relative to their pre-change behavior.

B1 — inspect RPC WS ignored CORSAllowedOrigins. The HTTP path honors the
operator's CORS allow-list but the WS upgrade used the restrictive default,
so an allow-listed browser origin worked over HTTP yet was 403'd at the WS
upgrade. Thread rpcConfig.CORSAllowedOrigins into wm.CheckOrigin, mirroring
the node RPC (internal/rpc/core/env.go) and the HTTP CORS handler.

B2 — light proxy WS lost its historic permissive default with no opt-out.
The proxy is configured via rpcserver.Config, which exposes no CORS knob,
so the restrictive default silently rejected browser clients that worked
before. Restore the prior allow-all origin policy with a documented comment;
origin restrictions are expected to be enforced by AuthN/AuthZ in front of
the proxy.

Add a table-driven regression test for the inspect Handler WS origin policy
(no-origin, same-host, allow-listed, and rejected cross-origin cases).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ange

Add the (#1343) reference to the RPC input-validation entry and document
that browser websocket clients on cross-origin hosts must now be listed in
cors-allowed-origins following the WS Origin default-policy change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@lklimek
lklimek requested a review from thepastaclaw June 17, 2026 10:30

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

The PR is cleanly scoped to RPC input-validation hardening and addresses the prior review round (BlockSearch length error wrapping, empty-batch rejection, inspect-RPC and light-proxy WS origin behavior, CHANGELOG note). Verified the WS origin checker mirrors rs/cors semantics and that the batch cap is enforced but only after the full body is unmarshaled. No blocking issues; one defense-in-depth suggestion plus minor test/wildcard nitpicks.

💬 2 nitpick(s)

1 carried-forward finding(s) already raised on this PR; not re-posting as new inline comments.

Comment thread rpc/jsonrpc/server/ws_handler.go Resolved
lklimek and others added 2 commits June 17, 2026 14:01
…igin patterns

statusWriter.Hijack now returns the stdlib http.ErrNotSupported sentinel
instead of a bespoke error, matching net/http conventions for the
"feature not supported" condition (HTTP/2 transports degrade cleanly).

compileOriginMatchers only honors the first '*' in an allow-list entry
(rs/cors semantics); any later '*' is matched literally and can never
appear in a browser Origin, leaving the entry dead. It now warns at
compile/config-load time so operators get feedback, with the godoc
updated to state the single-wildcard contract. A logger is threaded
through OriginChecker to all call sites.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Pin the rs/cors port quirks inherited by OriginChecker: a wildcard-host
pattern denies an Origin carrying a port suffix, an explicit-port pattern
matches the same explicit port, and the same-host fallback denies on port
mismatch.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

PR #1343 is a focused RPC input-hardening change (batch cap, query length, genesis index, mempool pagination, WebSocket Origin policy, safe Hijacker). It is consensus-neutral and the latest delta resolves all prior reviewer concerns. Verification finds one in-scope consistency suggestion (BlockSearch now wraps ErrInvalidRequest but the structurally identical TxSearch check still returns a bare error) and one minor defensive nitpick on the new compileOriginMatchers logger. Codex execution was degraded (sandbox blocked Go cache / BLS headers), but its source review yielded no in-scope findings, consistent with Claude.

🟡 1 suggestion(s) | 💬 1 nitpick(s)

1 additional finding(s) omitted (not in diff).

🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `internal/rpc/core/tx.go`:
- [SUGGESTION] internal/rpc/core/tx.go:59-60: TxSearch query-length error should wrap ErrInvalidRequest to match BlockSearch
  This PR rewrote the BlockSearch query-length check to wrap `coretypes.ErrInvalidRequest` (`internal/rpc/core/blocks.go:216`) and the new tests assert that property via `errors.Is`. The structurally identical check in `TxSearch` still returns a bare `errors.New("maximum query length exceeded")`, so the same client probe behaves inconsistently between the two endpoints. The divergence is created by this PR's chosen direction for BlockSearch; aligning TxSearch keeps the RPC contract uniform for clients and tooling that classify input errors via `errors.Is(err, coretypes.ErrInvalidRequest)`. One-line change.

Comment thread rpc/jsonrpc/server/ws_handler.go Resolved
Guard against a nil logger at the top of compileOriginMatchers so that
callers passing nil to OriginChecker with a multi-wildcard allow-list
entry no longer nil-deref on the logger.Warn call.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

Verified PR #1343 hardens RPC entry points (WS Origin allow-list, checked Hijacker, JSON-RPC batch cap, BlockSearch length cap, GenesisChunked negative-index, UnconfirmedTxs pagination clamp) and restores prior CORS-honoring/permissive WS behavior. The latest delta correctly normalizes a nil logger in compileOriginMatchers with a regression test. No in-scope defects remain; the prior round's nil-deref is resolved. Codex test execution was degraded (no Go module/BLS access in sandbox); Claude verified findings against the source directly.

@lklimek
lklimek merged commit 4999e1d into v1.6-dev Jun 18, 2026
17 checks passed
@lklimek
lklimek deleted the fix/rpc-request-handling branch June 18, 2026 09:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants