Skip to content

fix: force connection: close on chunked upstream requests - #158

Merged
pi0 merged 3 commits into
mainfrom
fix/req-smuggle
Jul 9, 2026
Merged

pi0 merged 3 commits into
mainfrom
fix/req-smuggle

Conversation

@pi0x

@pi0x pi0x commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds the connection-reuse half of the HTTP request-smuggling fix for GHSA-ggv3-7p47-pfv8 (CVE-2026-29057). This complements the deleteLength desync fix already on main (#153).

The upstream Next.js/http-proxy patch had two hunks:

  1. Hunk 1 — deleteLength (already fixed in fix: preserve transfer-encoding on chunked DELETE/OPTIONS #153): no longer rewrites a chunked DELETE/OPTIONS into content-length: 0 while streaming the body — the proxy no longer manufactures a desync.
  2. Hunk 2 — setupOutgoing (this PR): force Connection: close on the upstream request for any chunked (transfer-encoding) request, so the upstream socket is never reused.

Why Hunk 2 matters for httpxy specifically

A framing desync is only exploitable for cross-user response poisoning if the upstream keep-alive socket is reused afterward. httpxy defaults to keep-alive agents, so — unlike stock http-proxy (which defaults to no agent → close) — chunked-request sockets were reused by default. That is the exact amplifier Hunk 2 removes. Even though httpxy no longer creates a desync itself, a lenient/legacy upstream (e.g. one that honors Connection: transfer-encoding as hop-by-hop, or mishandles chunked framing) could, and the reused socket would let leftover bytes be served as another user's response.

Change

The hardening now lives in a shared helper, forceConnectionCloseForTransferEncoding() (src/_utils.ts), which forces Connection: close — regardless of agent — when the outgoing request carries a transfer-encoding header, or its Connection header lists transfer-encoding as hop-by-hop. This also closes the Connection: upgrade + chunked-body bypass vector. Genuine WebSocket upgrades (no transfer-encoding) keep their Connection header intact.

Crucially, the helper is applied on every outgoing-request path, not just setupOutgoing — httpxy has three parallel paths that build upstream requests, and all three defaulted to keep-alive socket reuse:

Path Location Coverage
setupOutgoing src/_utils.ts ProxyServer web/ws initial requests
proxyFetch → _sendRequest src/fetch.ts Initial request and every followRedirects 307/308 replay hop (the helper re-runs on each recursion)
followRedirects replay src/middleware/web-incoming.ts ProxyServer 307/308 chunked replay, which builds its request options by hand and bypasses setupOutgoing

Without the last two, a chunked request over proxyFetch's default keep-alive agent, or a chunked ProxyServer request that gets 307/308-redirected with a caller-supplied keep-alive agent, would still return a reusable socket to the pool — leaving the exact smuggling amplifier this PR aims to remove.

Tests

Mechanism tests (assert Connection: close is emitted):

  • test/_utils.test.ts — 4 unit tests: TE forces close even with the default keep-alive agent; Connection: keep-alive, transfer-encoding forces close; Connection: upgrade + chunked forces close; real WS upgrades are untouched.
  • test/middleware/web-incoming.test.ts — #chunked-connection-teardown: end-to-end raw-socket test asserting the backend actually receives connection: close for a chunked request through a default keep-alive proxy. Plus a #followRedirects regression asserting the 307 replay of a chunked request is sent with connection: close.
  • test/fetch.test.ts — proxyFetch regressions: chunked request over a keep-alive agent forces close; Connection hop-by-hop marker forces close; 307 replay forces close and preserves the body; a non-chunked request keeps connection intact.

End-to-end outcome test (test/request-smuggling.test.ts, ported from the upstream vercel/next.js rewrite-request-smuggling suite):

Sends a raw crafted chunked request that hides a second GET /secret request inside its body, through an httpxy proxy fronting a deliberately lenient, desync-prone upstream (pipelines on keep-alive, honors Connection: close), and asserts the smuggled request never reaches the upstream — across the same Connection-header permutations and methods as upstream:

Scenario Connection header Method
keep-alive only keep-alive DELETE
keep-alive + upgrade keep-alive, upgrade DELETE
transfer-encoding + upgrade Transfer-Encoding, upgrade DELETE
OPTIONS + transfer-encoding + upgrade Transfer-Encoding, upgrade OPTIONS
lenient upstream (non-rfc TE strip) keep-alive, upgrade OPTIONS

The upstream suite's 6th scenario (absolute-URL upgrade → SSRF) is N/A for httpxy: it targets Next.js's rewrite engine, which can route by the request URL's host. httpxy's ws/upgrade path always resolves to the configured options.target via setupOutgoing — an absolute URL only affects the outgoing path (toProxy), never the destination host — so there is no URL-driven routing to exploit.

All new tests were verified to fail without this change (the smuggled GET /secret reaches the upstream) and pass with it. Full suite (lint + typecheck + 314 tests) is green.

Docs

Updated AGENTS.md: corrected the stale deleteLength description, documented the keep-alive default and the TE → Connection: close rule, documented the shared helper with the three outgoing paths it now covers, and listed the new request-smuggling.test.ts end-to-end suite.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of chunked requests so upstream connections now use Connection: close when needed, helping prevent request-smuggling issues.
    • Preserved legitimate upgrade/WebSocket behavior while keeping the original connection header intact when no transfer encoding is present.
    • Clarified HTTP behavior for DELETE and OPTIONS requests: content-length: 0 is only added when no body-related headers are already set.

Hardens against HTTP request smuggling (GHSA-ggv3-7p47-pfv8), the
connection-reuse half of the advisory that complements the existing
`deleteLength` desync fix (#153).

`setupOutgoing` now forces `Connection: close` on the upstream request —
regardless of agent — whenever the request carries `transfer-encoding`,
or its `Connection` header lists `transfer-encoding` as hop-by-hop. Since
httpxy defaults to keep-alive agents, a chunked request would otherwise
reuse the upstream socket; if a lenient upstream ever desynced, leftover
bytes could be read as a pipelined next request and poison another user's
response. Tearing the socket down after any chunked request removes that
amplifier and also closes the `Connection: upgrade` + chunked-body bypass.
Genuine WebSocket upgrades (no `transfer-encoding`) keep their header.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@codecov

codecov Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.23%. Comparing base (f7a2713) to head (91f664b).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #158      +/-   ##
==========================================
+ Coverage   94.95%   95.23%   +0.28%     
==========================================
  Files           8        8              
  Lines         793      840      +47     
  Branches      328      352      +24     
==========================================
+ Hits          753      800      +47     
  Misses         35       35              
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pi0 pi0 changed the title fix: force connection: close on chunked upstream requests (GHSA-ggv3-7p47-pfv8) fix: force connection: close on chunked upstream requests Jul 9, 2026
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds request-smuggling hardening to setupOutgoing in src/_utils.ts by detecting transfer-encoding headers (directly or via hop-by-hop Connection header markers) and forcing outgoing.headers.connection to "close", independent of agent settings. Documentation in AGENTS.md is updated accordingly, and unit and integration tests are added.

Changes

Connection Close Hardening for Request Smuggling

Layer / File(s) Summary
Transfer-encoding detection and forced connection close
src/_utils.ts
Adds transferEncodingConnectionToken regex and hardening logic in setupOutgoing that forces outgoing.headers.connection = "close" when transfer-encoding is present or marked hop-by-hop via Connection.
Unit tests for hardening scenarios
test/_utils.test.ts
Adds tests covering chunked transfer-encoding, hop-by-hop Connection markers, upgrade+chunked bypass, and genuine WebSocket upgrade preservation.
Integration regression test
test/middleware/web-incoming.test.ts
Adds a test sending a raw chunked OPTIONS request and asserting the upstream connection header is forced to "close".
Documentation updates
AGENTS.md
Revises deleteLength behavior description and documents the new connection-close hardening rule and WebSocket exception.

Estimated code review effort: 2 (Simple) | ~15 minutes

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ProxyMiddleware
    participant setupOutgoing
    participant UpstreamServer

    Client->>ProxyMiddleware: OPTIONS request (transfer-encoding: chunked)
    ProxyMiddleware->>setupOutgoing: build outgoing request options
    setupOutgoing->>setupOutgoing: detect transfer-encoding header or hop-by-hop Connection token
    setupOutgoing->>setupOutgoing: force outgoing.headers.connection = "close"
    setupOutgoing->>ProxyMiddleware: return hardened outgoing options
    ProxyMiddleware->>UpstreamServer: forward request with connection: close
    UpstreamServer->>ProxyMiddleware: response
    ProxyMiddleware->>Client: response
Loading

Possibly related PRs

  • unjs/httpxy#129: Both PRs modify src/_utils.ts's setupOutgoing logic around WebSocket/Connection header handling.

Suggested reviewers: pi0, sapphi-red

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: forcing Connection: close on chunked upstream requests.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/req-smuggle

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.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
src/_utils.ts (1)

155-176: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Hardening logic is correct and well-documented.

The two-pronged detection (direct transfer-encoding header + hop-by-hop Connection marker) correctly covers both vectors, and the Object.entries + .toLowerCase() scan properly handles non-lowercased keys injected via options.headers. The upgrade + chunked bypass is closed: the existing upgrade-preservation block at lines 145–153 no longer shields requests that carry transfer-encoding.

One minor redundancy: outgoing.headers is always an object by this point (set at line 95 as { ...req.headers }), so the guard at line 166 is unnecessary. Not a defect—just a copy of the pre-existing pattern at line 146.

🧹 Remove redundant guard
- outgoing.headers = outgoing.headers || {};
  const carriesTransferEncoding = Object.entries(outgoing.headers).some(
🤖 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 `@src/_utils.ts` around lines 155 - 176, The hardening logic in the outgoing
request header handling is correct, but the `outgoing.headers = outgoing.headers
|| {}` guard is redundant because `outgoing.headers` is already initialized
earlier in the same flow. Remove that unnecessary fallback in the `_utils`
request-header normalization logic and keep the existing
`carriesTransferEncoding` / `connectionMarksTransferEncoding` checks and
`connection = "close"` behavior unchanged.
🤖 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.

Nitpick comments:
In `@src/_utils.ts`:
- Around line 155-176: The hardening logic in the outgoing request header
handling is correct, but the `outgoing.headers = outgoing.headers || {}` guard
is redundant because `outgoing.headers` is already initialized earlier in the
same flow. Remove that unnecessary fallback in the `_utils` request-header
normalization logic and keep the existing `carriesTransferEncoding` /
`connectionMarksTransferEncoding` checks and `connection = "close"` behavior
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3467e184-f463-4b1d-b971-c9d9b84af7e0

📥 Commits

Reviewing files that changed from the base of the PR and between f7a2713 and 9eac4c3.

📒 Files selected for processing (4)
  • AGENTS.md
  • src/_utils.ts
  • test/_utils.test.ts
  • test/middleware/web-incoming.test.ts

@unjs unjs deleted a comment from pi0x Jul 9, 2026
pi0 and others added 2 commits July 9, 2026 10:53
The request-smuggling hardening (GHSA-ggv3-7p47-pfv8) previously lived
only in `setupOutgoing`, leaving two parallel outgoing-request paths that
could still reuse an upstream keep-alive socket after a chunked request:

- `proxyFetch` defaults to a shared keep-alive agent and forwards a
  client-supplied `transfer-encoding` header verbatim.
- The `web-incoming` `followRedirects` 307/308 replay builds its request
  options by hand, bypassing `setupOutgoing`.

Extract the logic into a shared `forceConnectionCloseForTransferEncoding()`
helper and apply it on every outgoing path: `setupOutgoing`,
`proxyFetch`'s `_sendRequest` (covering the initial request and each
redirect hop), and the ProxyServer redirect replay. Add regression tests
for each; all fail without the fix.

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

Port the upstream vercel/next.js rewrite-request-smuggling suite to httpxy.
Previously coverage only asserted the mechanism (`connection: close` is
emitted); this adds an outcome test: a crafted chunked request hiding a
smuggled `GET /secret` in its body is sent to an httpxy proxy fronting a
deliberately lenient, desync-prone upstream, and the suite asserts the
smuggled request never reaches the upstream across the same Connection-header
permutations and methods (keep-alive; keep-alive,upgrade; transfer-encoding,
upgrade; OPTIONS; non-rfc strip). All 5 scenarios fail without the hardening.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@pi0
pi0 merged commit 299d5e1 into main Jul 9, 2026
4 checks passed
@pi0
pi0 deleted the fix/req-smuggle branch July 9, 2026 11:04
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.

2 participants