Repository navigation
fix(dev): forward chunked request bodies in HA proxy - #1390
Conversation
The dev HA round-robin proxy in dev-scripts/run.py only streamed the request body when a Content-Length header was present. A client using Transfer-Encoding: chunked (e.g. nix copy uploading a NAR whose on-the-fly-compressed .nar.zst size is unknown) had its body silently dropped: Transfer-Encoding is hop-by-hop and was stripped, so the body loop was skipped and the backend received a bodiless PUT. The unconsumed client body then reset the connection, surfacing as curl error 56 (Connection reset by peer) and aborting the whole closure upload. Detect chunked framing before the header is dropped, decode the chunked body from the client and re-encode it chunked to the backend in bounded PROXY_BUFFER units (no whole-body buffering, so proxy memory still does not scale with payload size). Harden the error path so a backend failure drains the unconsumed body and forces the connection closed, yielding a real 502 instead of a reset. Surface backend connect/forward failures via the log so dev upload failures are diagnosable. Add a regression test that drives the real run.py proxy with both a Content-Length and a Transfer-Encoding: chunked PUT, asserting the backend receives the full body in both cases, and wire dev-scripts/run.py into the e2e-harness-unit flake check so it runs in CI. Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
This change is part of the following stack: Change managed by git-spice. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughSummary by CodeRabbit
WalkthroughFixes the dev HA reverse proxy to stream and forward client request bodies framed with Transfer-Encoding: chunked, adds bounded chunk parsing and drain-on-error to avoid client resets, includes regression tests for chunked and Content-Length uploads, and updates specs/docs and CI wiring. ChangesDev HA Proxy Chunked Body Forwarding and Tests
Sequence Diagram(s)sequenceDiagram
participant Client
participant ProxyHandler
participant _stream_chunked_body
participant Backend
Client->>ProxyHandler: PUT /upload ... Transfer-Encoding: chunked
ProxyHandler->>_stream_chunked_body: read chunk-size line
_stream_chunked_body->>_stream_chunked_body: parse hex size, validate CRLF
_stream_chunked_body->>ProxyHandler: emit framed chunk bytes
ProxyHandler->>Backend: forward chunked bytes (with Transfer-Encoding: chunked)
alt backend connect/forward OK
Backend-->>ProxyHandler: response (e.g., 204)
ProxyHandler-->>Client: backend response
else backend error / parse error
ProxyHandler->>ProxyHandler: _fail -> drain remaining body, send 502
ProxyHandler-->>Client: 502 Bad Gateway
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request adds support for forwarding chunked request bodies in the development HA reverse proxy (dev-scripts/run.py) and introduces regression tests to verify full-body delivery and clean error handling. The review feedback suggests extending the _fail error path to also drain chunked request bodies to prevent connection resets, prioritizing chunked encoding over Content-Length when both headers are present to comply with RFC 7230, and parameterizing the unreachable backend test to cover both chunked and non-chunked request paths.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/tasks.md (1)
12-12: 💤 Low valueMinor documentation discrepancy: task 2.2 vs. implementation structure.
Task 2.2 mentions extracting a
_forward_request_body(conn)helper, but the implementation (dev-scripts/run.py lines 395-410) keeps the body-forwarding logic inline within_proxy()as two conditional branches (one for Content-Length, one for chunked). The logic is clear and well-organized, so this is a documentation variance rather than a defect. If future refactoring introduces more body-forwarding modes, extracting a dedicated helper would reduce complexity in_proxy().🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/tasks.md` at line 12, The tasks doc mentions extracting a `_forward_request_body(conn)` helper but the code keeps body-forwarding inline inside `_proxy()` with two branches; reconcile by either (A) updating the task entry to state that `_proxy()` currently handles both `Content-Length` and `Transfer-Encoding: chunked` inline, removing the expectation of a separate helper, or (B) implement the helper `_forward_request_body(conn)` and move the two conditional branches from `_proxy()` into that function (retain the existing behavior for `Content-Length` loop and chunked handling). Reference the existing `_proxy()` function and the intended `_forward_request_body(conn)` symbol when making the change.nix/e2e-tests/tests/test_dev_proxy.py (1)
72-82: ⚡ Quick winChunked decoder doesn't handle optional trailers.
After the zero-length terminator chunk, HTTP/1.1 allows optional trailer headers before the final CRLF. Line 79 reads only one line, assuming no trailers. The upstream proxy decoder (context snippet 1) loops until it finds a blank line. While current tests don't send trailers (
_putline 104 sends0\r\n\r\n), a future test or external client that does will cause the backend to mis-parse the body.♻️ Align with upstream trailer handling
size = int(line.split(b";", 1)[0], 16) if size == 0: - self.rfile.readline() # trailing CRLF after terminator + # Consume optional trailers until blank line. + while True: + trailer = self.rfile.readline() + if trailer in (b"\r\n", b"\n", b""): + break break🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@nix/e2e-tests/tests/test_dev_proxy.py` around lines 72 - 82, The chunked decoder in the block starting with "elif te and 'chunked' in te.lower()" incorrectly reads a single line after the zero-length terminator and thus ignores optional trailer headers; update the handling so that after detecting size == 0 you loop reading lines from self.rfile until you encounter a blank line (i.e., keep calling self.rfile.readline() and break only on an empty line), ensuring any trailers are consumed before breaking and before returning/using body.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@dev-scripts/run.py`:
- Around line 267-281: The chunked-body reader currently discards terminators
without validating them, allowing malformed data to slip through; update the
loop that consumes trailers and the per-chunk CRLF check to validate exact CRLF
sequences and raise ProxyBodyError on framing errors: when handling the
zero-sized chunk, require the following line(s) to be proper trailers terminated
by b"\r\n" (do not treat EOF as a valid blank line) and when consuming the CRLF
after each chunk (the rfile.readline() at the end of the per-chunk loop), verify
it equals b"\r\n" (or raise ProxyBodyError) instead of ignoring it; use the
existing variables rfile, send, PROXY_BUFFER and the ProxyBodyError exception to
implement these checks.
- Around line 326-347: ProxyHandler._fail currently reconstructs remaining from
self.headers["Content-Length"], which can over-drain because ProxyHandler._proxy
already decrements a local remaining while streaming; change the code so _proxy
passes the current unread byte count into _fail (e.g., call self._fail(code,
message, unread) or set self._unread_bytes before calling _fail) and then in
_fail use that unread value (falling back to Content-Length only if unread is
None) to bound the drain loop against self.rfile using PROXY_BUFFER; ensure the
drain loop decrements that unread counter and stops when it reaches zero to
avoid blocking or over-draining.
In `@nix/e2e-tests/tests/test_dev_proxy.py`:
- Line 61: The class-level mutable dict _CaptureHandler.received is causing test
state to leak across runs; convert it to an instance attribute by initializing
self.received in _CaptureHandler.__init__ (and update any references from
_CaptureHandler.received to instance.received), or alternatively add an autouse
pytest fixture that clears _CaptureHandler.received before each test (e.g., a
fixture named clear_capture_state that calls _CaptureHandler.received.clear());
choose one approach and update tests/handlers consistently to avoid shared
mutable state.
---
Nitpick comments:
In `@nix/e2e-tests/tests/test_dev_proxy.py`:
- Around line 72-82: The chunked decoder in the block starting with "elif te and
'chunked' in te.lower()" incorrectly reads a single line after the zero-length
terminator and thus ignores optional trailer headers; update the handling so
that after detecting size == 0 you loop reading lines from self.rfile until you
encounter a blank line (i.e., keep calling self.rfile.readline() and break only
on an empty line), ensuring any trailers are consumed before breaking and before
returning/using body.
In `@openspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/tasks.md`:
- Line 12: The tasks doc mentions extracting a `_forward_request_body(conn)`
helper but the code keeps body-forwarding inline inside `_proxy()` with two
branches; reconcile by either (A) updating the task entry to state that
`_proxy()` currently handles both `Content-Length` and `Transfer-Encoding:
chunked` inline, removing the expectation of a separate helper, or (B) implement
the helper `_forward_request_body(conn)` and move the two conditional branches
from `_proxy()` into that function (retain the existing behavior for
`Content-Length` loop and chunked handling). Reference the existing `_proxy()`
function and the intended `_forward_request_body(conn)` symbol when making the
change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b5ae01d1-2835-4079-8990-e8fc4a9b9b92
📒 Files selected for processing (9)
dev-scripts/run.pynix/e2e-tests/flake-module.nixnix/e2e-tests/tests/test_dev_proxy.pyopenspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/.openspec.yamlopenspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/design.mdopenspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/proposal.mdopenspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/specs/dev-ha-proxy/spec.mdopenspec/changes/archive/2026-06-10-fix-dev-proxy-chunked-body/tasks.mdopenspec/specs/dev-ha-proxy/spec.md
Address review feedback on the HA-proxy chunked-body fix: - RFC 7230 §3.3.3: when both Transfer-Encoding: chunked and Content-Length are present, chunked wins — ignore Content-Length and do not forward it to the backend (closes a request-smuggling vector). - _fail() now drains the *unconsumed* body for both framings: thread the remaining fixed-length count from _proxy() (no over-drain/block when a failure happens mid-forward) and best-effort drain a chunked body so a backend failure on a chunked upload yields a clean 502 instead of a TCP reset (threads Ilh7H, Ilh7L, Ilh7W, Ill89). - _stream_chunked_body() validates chunk terminators: raise ProxyBodyError on a truncated terminator or a missing per-chunk CRLF instead of silently accepting malformed framing (thread Ill8v). - Test: parameterize the unreachable-backend 502 test over both Content-Length and chunked, and fix the capture backend's mutable class-attr state leak with an autouse reset fixture + ClassVar (threads Ilh7f, Ill9E). Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
dev-scripts/run.py (1)
257-275:⚠️ Potential issue | 🟠 Major | ⚡ Quick winBound the chunk-size and trailer lines too.
_stream_chunked_body()is still using unboundedreadline(), so a client can send a multi-megabyte chunk-size or trailer line and make the proxy buffer it in memory before anyPROXY_BUFFERchunking kicks in. That breaks the bounded-streaming guarantee this change is trying to add. Please cap these line reads and reject overlong framing; the same guard should be mirrored in the chunked branch of_drain_request_body()too.Suggested direction
+MAX_CHUNK_LINE = 8 * 1024 + def _stream_chunked_body(rfile, send): while True: - size_line = rfile.readline() + size_line = rfile.readline(MAX_CHUNK_LINE + 1) if not size_line: raise ProxyBodyError("client closed before chunked terminator") + if len(size_line) > MAX_CHUNK_LINE and not size_line.endswith(b"\n"): + raise ProxyBodyError("chunk header too long") token = size_line.split(b";", 1)[0].strip() ... if size == 0: while True: - trailer = rfile.readline() + trailer = rfile.readline(MAX_CHUNK_LINE + 1) if trailer == b"": raise ProxyBodyError("truncated chunked terminator") + if len(trailer) > MAX_CHUNK_LINE and not trailer.endswith(b"\n"): + raise ProxyBodyError("chunk trailer too long") if trailer in (b"\r\n", b"\n"): break🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@dev-scripts/run.py` around lines 257 - 275, _stream_chunked_body() (and the chunked branch in _drain_request_body()) currently calls rfile.readline() without a limit, allowing a client to send arbitrarily long chunk-size or trailer lines and break the bounded-streaming guarantee; fix by calling rfile.readline(max_line_len) with a defined max (e.g. PROXY_MAX_LINE or PROXY_MAX_CHUNK_HEADER) for the chunk-size and trailer reads, detect when the returned line does not end with a newline or exceeds the limit and raise ProxyBodyError (with an appropriate message like "chunk size line too long" or "truncated chunked terminator") to reject overlong framing, and apply the same limited-read logic to the chunked branch inside _drain_request_body() so both places enforce the same bounds.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@dev-scripts/run.py`:
- Around line 341-380: The current drain logic (drain_fixed, drain_cap, and the
chunked-loop using self.rfile.read()/readline()) can block indefinitely; wrap
the whole draining phase in a short temporary timeout so _fail() can proceed to
send_error() on timeout—e.g. set a small socket timeout on the underlying socket
(or use select/poll) before running drain_fixed/loop and restore the original
timeout afterwards, and break out of all draining loops when a timeout occurs;
ensure the timeout handling catches the timeout exception and stops further
reads so send_error() is invoked.
- Around line 451-457: The read loop that forwards a known Content-Length can
silently break on an empty read, causing the backend to hang; modify the loop in
the request handler where content_length/cl_remaining are used so that if
self.rfile.read(...) returns b"" you raise ProxyBodyError (or the existing
ProxyBodyError exception type) instead of break; ensure this happens inside the
loop before decrementing cl_remaining and that the exception propagates to the
existing 502 error path used by conn.getresponse().
---
Outside diff comments:
In `@dev-scripts/run.py`:
- Around line 257-275: _stream_chunked_body() (and the chunked branch in
_drain_request_body()) currently calls rfile.readline() without a limit,
allowing a client to send arbitrarily long chunk-size or trailer lines and break
the bounded-streaming guarantee; fix by calling rfile.readline(max_line_len)
with a defined max (e.g. PROXY_MAX_LINE or PROXY_MAX_CHUNK_HEADER) for the
chunk-size and trailer reads, detect when the returned line does not end with a
newline or exceeds the limit and raise ProxyBodyError (with an appropriate
message like "chunk size line too long" or "truncated chunked terminator") to
reject overlong framing, and apply the same limited-read logic to the chunked
branch inside _drain_request_body() so both places enforce the same bounds.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9df03199-8e0a-4a4c-888d-e6e60c5e1ff6
📒 Files selected for processing (2)
dev-scripts/run.pynix/e2e-tests/tests/test_dev_proxy.py
🚧 Files skipped from review as they are similar to previous changes (1)
- nix/e2e-tests/tests/test_dev_proxy.py
Address CodeRabbit incremental-review findings: - _fail() now wraps the body drain in a short (0.25s) socket timeout and restores the prior timeout afterward, so a client that stalls mid-upload cannot block in rfile.read()/readline() and starve the 502 (thread IlzlS). - The fixed-length forward loop raises ProxyBodyError on a short read instead of breaking: the backend was already told to expect the full Content-Length, so breaking would hang conn.getresponse(); routing to the 502 path avoids the hang (thread IlzlY). - Add a regression test: a client that declares a Content-Length but closes early gets a 502 (asserted via raw socket, with a client-side timeout so a regression fails fast instead of hanging). Co-Authored-By: Claude Opus 4.8 <[email protected]>
## Summary A **second, distinct** dev-harness bug from the chunked-body fix in #1390 (which is necessary and stays). After #1390, `nix copy` of a large closure (e.g. a ~9.35 GB `nixos-system`) to the `:8500` HA proxy **still** intermittently fails with `curl error 56: Connection reset by peer`, aborting the whole copy on the first reset. **Root cause:** the proxy's `ProxyHandler` left `protocol_version` at the stdlib `BaseHTTPRequestHandler` default of **HTTP/1.0**, so it force-closed every client connection after one request. `nix copy` pushes hundreds of objects over a small pool of HTTP/1.1 keep-alive connections; because the proxy refused keep-alive, nix was forced to open a brand-new TCP connection per object — thousands for a multi-GB closure. Under that churn (amplified by the default listen backlog of 5 and a ~1 s-per-PUT stall from unanswered `Expect: 100-continue`), the accept loop stalls and intermittently nix's upload connection is reset **before the proxy ever handles it** (`curl error 56`). **Reproduced & fix-validated** on a clean isolated ncps behind the real proxy: the unpatched proxy dies at PUT #2; the patched proxy completes **3,488 PUTs with 0 resets**. `curl -v` confirms `HTTP/1.1 200` + "Connection left intact" (reuse). ## What changed (`dev-scripts/run.py` proxy only; ncps unchanged) - `ProxyHandler.protocol_version = "HTTP/1.1"` — persistent, reused client connections; also makes `BaseHTTPRequestHandler` auto-answer `Expect: 100-continue`, removing the per-PUT stall. - Response framing for safe reuse: preserve `Content-Length`; treat `204`/`304`/`HEAD`/`1xx` as bodiless; send `Connection: close` when the body length is unknown (e.g. backend chunked, stripped as hop-by-hop) so the client reads to EOF instead of mis-framing the next response. - Raise the listener backlog (`request_queue_size`) above the stdlib default of 5, set before the socket is activated. - All #1390 hardening preserved (chunked request-body forwarding, RFC 7230 §3.3.3, bounded `_fail` drain, error logging). ## Test plan - [x] `task fmt` (0 changed), `task lint` (0 issues), `task test` (all Go packages ok) - [x] New keep-alive / framing / `Expect: 100-continue` regression tests drive the real `run.py` proxy via `NCPS_RUN_PY`; confirmed RED on HTTP/1.0, GREEN after the fix - [x] `e2e-harness-unit` nix check green (52 passed; +4 new tests) - [x] End-to-end: full `nix copy` of the 9.35 GB closure through the patched proxy — 3,488 PUTs, 0 resets --------- Co-authored-by: Claude Opus 4.8 <[email protected]>
Summary
The dev HA round-robin reverse proxy in
dev-scripts/run.py(PR #1389) silently dropped the body of any request sent withTransfer-Encoding: chunked. It only streamed the request body when aContent-Lengthheader was present; chunked uploads (noContent-Length, andTransfer-Encodingstripped as hop-by-hop) skipped the body loop entirely, so the backend received a bodiless PUT and the unconsumed client body reset the connection — surfacing ascurl error 56: Connection reset by peerand aborting the wholenix copyclosure upload.nix copyuploads NARs with chunked encoding because the on-the-fly-compressed.nar.zstsize is unknown ahead of time, so large closures (e.g. anixos-system) failed while smallContent-LengthNARs succeeded.Diagnosis (proven)
Driving the real
run.pyproxy against a capture backend:Content-LengthTransfer-Encoding: chunkedFix (
dev-scripts/run.pyonly — ncps server untouched)PROXY_BUFFERunits (no whole-body buffering — proxy memory still does not scale with payload size).502instead of a TCP reset.log_messagewas a no-op), so dev upload failures are diagnosable.dev-ha-proxyspec (chunked + Content-Length forwarding, 502-not-reset, error visibility) and archive the OpenSpec change.Test plan
run.pyproxy with bothContent-LengthandTransfer-Encoding: chunkedPUTs; asserts full body reaches the backend in both, and unreachable backend →502(not reset).dev-scripts/run.pyinto thee2e-harness-unitflake check so the test runs in CI (nix build .#checks.x86_64-linux.e2e-harness-unit→ 43 passed).task fmtclean ·task lint0 issues ·task testall Go packages pass.