Skip to content

Commit 10a916b

Browse files
committed
fix(web-incoming): defer body piping until socket is assigned
Piping immediately (3e68d30) could end a bodyless request queued behind a saturated agent, flushing headers before `proxyReq` fires and making `setHeader` throw ERR_HTTP_HEADERS_SENT (chimurai/http-proxy-middleware#472). Wire the body on the "socket" event instead, still without waiting for "connect" (#166).
1 parent 0260a5b commit 10a916b

3 files changed

Lines changed: 81 additions & 22 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ Returns Promise<Socket> (the upstream proxy socket)
8181
- `proxyRes` event fires only for the final (non-redirect) response; `proxyReq` fires for each request including redirects.
8282
- Sensitive headers (`authorization`, `cookie`) are stripped on cross-origin redirects.
8383
- When `followRedirects` is enabled, the request body is tee'd (written to proxy request and buffered simultaneously) rather than piped.
84-
- Without `followRedirects`, the incoming request is piped into the outgoing request **immediately**, without waiting for the upstream socket to emit `connect`. `ClientRequest` buffers writes issued before the socket connects, so the deferral is unnecessary — and it deadlocks with mocked sockets from request interceptors (msw/`@mswjs/interceptors`, nock), which only emit `connect` _after_ the outgoing request has been fully written (unjs/httpxy#166). Regression coverage: `#stream with mocked sockets` in `test/middleware/web-incoming.test.ts`.
84+
- The request body is wired into the outgoing request on the `ClientRequest` `"socket"` event (after `proxyReq` listeners run), **not** immediately and **not** on the socket's `"connect"`. Wiring immediately lets a bodyless request call `proxyReq.end()` while queued behind a saturated agent (`maxSockets`), flushing headers before `proxyReq` fires so `setHeader` throws `ERR_HTTP_HEADERS_SENT` (chimurai/http-proxy-middleware#472; caught by `pnpm test:ecosystem`). Waiting for `"connect"` deadlocks with mocked sockets from request interceptors (msw/`@mswjs/interceptors`, nock), which only emit `connect` _after_ the outgoing request has been fully written (unjs/httpxy#166). `ClientRequest` buffers writes until the socket connects, so no further deferral is needed. Regression coverage: `#stream with mocked sockets` and `#stream proxyReq header mutation under socket contention` in `test/middleware/web-incoming.test.ts`.
8585

8686
### WebSocket middleware semantics
8787

‎src/middleware/web-incoming.ts‎

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -156,28 +156,33 @@ export const stream = defineProxyMiddleware((req, res, options, server, head, ca
156156

157157
// Buffer request body when following redirects (needed for 307/308 replay)
158158
let bodyBuffer: Buffer | undefined;
159-
if (maxRedirects > 0) {
160-
const chunks: Buffer[] = [];
159+
160+
// Start sending the body once a socket is assigned (right after "proxyReq"
161+
// listeners had a chance to mutate headers) but without waiting for it to
162+
// connect. Ending the request earlier (e.g. bodyless GET queued behind a busy
163+
// agent) flushes headers before "proxyReq" fires (chimurai/http-proxy-middleware#472).
164+
// Waiting for "connect" deadlocks with mocked sockets from request interceptors
165+
// (msw / @mswjs/interceptors, nock), which only emit "connect" *after* the
166+
// outgoing request has been fully written (unjs/httpxy#166).
167+
proxyReq.once("socket", () => {
161168
const source = options.buffer || req;
162-
source.on("data", (chunk: Buffer) => {
163-
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
164-
proxyReq.write(chunk);
165-
});
166-
source.on("end", () => {
167-
bodyBuffer = Buffer.concat(chunks);
168-
proxyReq.end();
169-
});
170-
source.on("error", (err: Error) => {
171-
proxyReq.destroy(err);
172-
});
173-
} else {
174-
// Pipe immediately, without waiting for the upstream socket to connect.
175-
// `ClientRequest` buffers writes issued before the socket is connected, and
176-
// deferring deadlocks with mocked sockets (msw / @mswjs/interceptors, nock),
177-
// which only emit "connect" *after* the outgoing request has been fully
178-
// written (unjs/httpxy#166).
179-
(options.buffer || req).pipe(proxyReq);
180-
}
169+
if (maxRedirects > 0) {
170+
const chunks: Buffer[] = [];
171+
source.on("data", (chunk: Buffer) => {
172+
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
173+
proxyReq.write(chunk);
174+
});
175+
source.on("end", () => {
176+
bodyBuffer = Buffer.concat(chunks);
177+
proxyReq.end();
178+
});
179+
source.on("error", (err: Error) => {
180+
proxyReq.destroy(err);
181+
});
182+
} else {
183+
source.pipe(proxyReq);
184+
}
185+
});
181186

182187
function handleResponse(proxyRes: IncomingMessage, redirectCount: number, currentUrl: URL) {
183188
const statusCode = proxyRes.statusCode!;

‎test/middleware/web-incoming.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1337,3 +1337,57 @@ describe("#stream with mocked sockets", () => {
13371337
expect(await proxyThroughMockSocket("POST", "x".repeat(8192))).to.eql("x".repeat(8192));
13381338
});
13391339
});
1340+
1341+
// https://github.com/chimurai/http-proxy-middleware/issues/472
1342+
describe("#stream proxyReq header mutation under socket contention", () => {
1343+
async function run(followRedirects?: boolean) {
1344+
const received: (string | string[] | undefined)[] = [];
1345+
const source = http.createServer((req, res) => {
1346+
received.push(req.headers["x-added"]);
1347+
setTimeout(() => res.end("OK"), 10);
1348+
});
1349+
const sourcePort = await listenOn(source);
1350+
1351+
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
1352+
const proxy = httpProxy.createProxyServer({
1353+
target: `http://127.0.0.1:${sourcePort}`,
1354+
agent,
1355+
followRedirects,
1356+
});
1357+
const errors: Error[] = [];
1358+
proxy.on("error", (err, _req, res) => {
1359+
errors.push(err);
1360+
(res as http.ServerResponse).destroy();
1361+
});
1362+
proxy.on("proxyReq", (proxyReq) => {
1363+
proxyReq.setHeader("x-added", "yes");
1364+
});
1365+
const proxyServer = http.createServer((req, res) => {
1366+
proxy.web(req, res);
1367+
});
1368+
const proxyPort = await listenOn(proxyServer);
1369+
1370+
try {
1371+
const bodies = await Promise.all(
1372+
Array.from({ length: 10 }, () =>
1373+
fetch(`http://127.0.0.1:${proxyPort}/`).then((r) => r.text()),
1374+
),
1375+
);
1376+
expect(errors).to.eql([]);
1377+
expect(bodies).to.eql(Array.from({ length: 10 }, () => "OK"));
1378+
expect(received).to.eql(Array.from({ length: 10 }, () => "yes"));
1379+
} finally {
1380+
agent.destroy();
1381+
source.close();
1382+
proxyServer.close();
1383+
}
1384+
}
1385+
1386+
it("should allow setHeader in proxyReq when requests queue for a socket", async () => {
1387+
await run();
1388+
});
1389+
1390+
it("should allow setHeader in proxyReq when requests queue for a socket (followRedirects)", async () => {
1391+
await run(true);
1392+
});
1393+
});

0 commit comments

Comments
 (0)