Repository navigation
fix(rpc): add input validation and request bounds - #1343
Conversation
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>
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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.Hijackertransports (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. |
- 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>
|
✅ Review complete (commit 4c2c20a) |
thepastaclaw
left a comment
There was a problem hiding this comment.
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.
| 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 | ||
| } |
There was a problem hiding this comment.
🟡 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']
There was a problem hiding this comment.
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.
…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]>
thepastaclaw
left a comment
There was a problem hiding this comment.
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.
…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
left a comment
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
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.
Why this PR exists
http.Hijackertype assertion, unbounded JSON-RPC batch sizes, no length bound onBlockSearchqueries, a missing negative-index check inGenesisChunked, and unclampedUnconfirmedTxspagination. Malformed or out-of-range inputs on the externally reachable RPC layer could panic a handler or do far more work than intended.http.Hijackercan crash the handler goroutine or process more than necessary. These are robustness/correctness gaps, not behaviour any well-formed client depends on.v1.6-dev.What was done
Originheader against the configured allow-list before completing the connection upgrade.http.Hijackertype assertion with a checked one that returns an error when hijacking is unavailable.BlockSearchquery-string length.GenesisChunked.UnconfirmedTxspagination parameters to valid ranges.internal/rpc/core/rpc_validation_test.go,rpc/jsonrpc/server/rpc_validation_test.go.How Has This Been Tested?
go buildandgo testoninternal/inspect/rpc,internal/rpc/core,rpc/jsonrpc/server— all pass (BLS cgo build).golangci-lintwith the CI configuration (--new-from-rev=origin/v1.6-dev) — 0 new issues.Breaking Changes
None.
Checklist
Attribution
🤖 Co-authored by Claudius the Magnificent AI Agent