"use strict"; // adpanel:upstream-error-listeners — behavior pins for createProxyMiddleware's // response handling (utils/db-proxy.js is directly requirable). // // The middleware's response callback used to pipe the upstream // IncomingMessage (proxyRes) into the client response with NO 'error' and NO // 'aborted' listener on the non-text branch: a backend connection reset // mid-stream emitted 'error' on proxyRes where no outer try/catch can catch // it — an unhandled 'error' event on an EventEmitter throws, so the panel // WORKER CRASHED (the exact class AGENTS.md mandates error listeners for; // see the services/node-http.js posture: response error AND aborted // listeners, single-settle finish). // // The fix attaches ONE idempotent failure finisher before either response // branch; every response path settles through it exactly once: // - proxyRes 'error' / 'aborted' (both branches) → unpipe + destroy the // backend request/response, then: before headers → 502; after headers → // the client socket is destroyed (a truncated exchange must never be // ended "cleanly" against its content-length); // - proxyReq 'error' before any response → 502 (existing contract); // - proxyReq 'timeout' → settles FIRST (its 504 must win the race against // the aborted/error its own destroy() provokes), destroys the client // socket after headers instead of hanging it forever; // - the text branch's old per-branch error listener is folded into the // shared finisher; the rewrite logic itself is untouched. // - res 'close' (the CLIENT half of the exchange) settles through the same // finisher when the client disappears before the exchange completed — // mid-stream, or with the dial still in flight (real Node fires res // 'close' with writableEnded false BEFORE the response callback runs). // 'close' ALSO fires after a normal completion (proxyRes 'end' → // pipe's/res.end → res 'finish' → res 'close', with res.writableEnded // already true), so the handler guards on the exchange's completion state // and the success path is provably untouched. // // Crash detection needs NO process-level uncaughtException handler: with no // 'error' listener registered, proxyRes.emit("error", ...) THROWS // synchronously — so a regression back to the listener-less pipe fails these // tests directly, and the listener-count assertions below prove the wiring // even before any event fires. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const http = require("node:http"); const { EventEmitter } = require("node:events"); const zlib = require("node:zlib"); const ROOT = path.join(__dirname, ".."); const MODULE_PATH = path.join(ROOT, "utils", "db-proxy.js"); // Isolated module instance (same mechanism as tests/db-proxy-cluster-token-store.test.js). function loadWorker() { delete require.cache[MODULE_PATH]; return require(MODULE_PATH); } function tmpDir(prefix) { return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); } // ─── Fakes ────────────────────────────────────────────────────── // Mock express-style client response. destroy/end/status calls are counted so // the exactly-once settle guarantee is assertable. An EventEmitter so tests // can drive the CLIENT side the way real Node reports it: res 'close' fires // BOTH on a premature disconnect and after normal completion; writableEnded // mirrors the stream state the middleware's client-close guard reads. class MockResponse extends EventEmitter { constructor({ headersSentStaysFalse = false } = {}) { super(); this.statusCode = 0; this.statusCalls = []; this.headers = {}; this.writes = []; this.endCalls = 0; this.destroyCalls = 0; this.ended = false; this.destroyed = false; this.writableEnded = false; this._headersSentStaysFalse = headersSentStaysFalse; this.headersSent = false; } setHeader(name, value) { this.headers[String(name).toLowerCase()] = value; } getHeader(name) { return this.headers[String(name).toLowerCase()]; } getHeaderNames() { return Object.keys(this.headers); } removeHeader(name) { delete this.headers[String(name).toLowerCase()]; } status(code) { this.statusCode = code; this.statusCalls.push(code); return this; } writeHead(code, headers) { this.statusCode = code; if (!this._headersSentStaysFalse) this.headersSent = true; if (headers) { for (const [k, v] of Object.entries(headers)) this.headers[String(k).toLowerCase()] = v; } return this; } write(chunk) { this.writes.push(chunk); return true; } end(chunk) { if (chunk !== undefined && chunk !== null) this.writes.push(chunk); this.endCalls += 1; this.ended = true; this.writableEnded = true; // Real Node commits the headers synchronously on end() — the // late-double-response guards below depend on that semantics. if (!this._headersSentStaysFalse) this.headersSent = true; return this; } destroy() { this.destroyCalls += 1; this.destroyed = true; return this; } } // Fake upstream request (EventEmitter with the ClientRequest surface the // middleware uses). Records destroy() so backend-socket teardown is provable. function fakeProxyReq() { const EventEmitter = require("node:events").EventEmitter; const proxyReq = new EventEmitter(); proxyReq.destroyCalls = 0; proxyReq.end = () => { }; proxyReq.write = () => { }; proxyReq.destroy = () => { proxyReq.destroyCalls += 1; }; proxyReq.setTimeout = () => { }; return proxyReq; } // Fake upstream response (IncomingMessage shape: EventEmitter + statusCode + // headers + pipe/unpipe/destroy). respond() may override pipe for streaming. function fakeProxyRes({ statusCode = 200, headers = {}, pipe } = {}) { const EventEmitter = require("node:events").EventEmitter; const proxyRes = new EventEmitter(); proxyRes.statusCode = statusCode; proxyRes.headers = { ...headers }; proxyRes.unpiped = []; proxyRes.destroyCalls = 0; proxyRes.unpipe = (dest) => { proxyRes.unpiped.push(dest); }; proxyRes.destroy = () => { proxyRes.destroyCalls += 1; }; if (pipe) proxyRes.pipe = pipe; else proxyRes.pipe = (dest) => { proxyRes.pipedTo = dest; }; return proxyRes; } // Patch http.request with a canned upstream exchange; returns { restore, // captured, lastReq }. respond() returns the fake proxyRes. With // invokeCallback true (default) the middleware's response callback runs // synchronously, like the real http module delivering headers. With false, // no response object is delivered at all — the pre-response dial-failure // scenario, where the client response cannot have headers sent yet. function stubHttp(respond, { invokeCallback = true } = {}) { const realRequest = http.request; const captured = []; const reqs = []; http.request = function (options, callback) { captured.push(options); const proxyReq = fakeProxyReq(); reqs.push(proxyReq); if (invokeCallback) { const proxyRes = respond(options); if (callback) callback(proxyRes); } return proxyReq; }; return { captured, get lastReq() { return reqs[reqs.length - 1]; }, restore() { http.request = realRequest; }, }; } // ─── Harness ──────────────────────────────────────────────────── const dbProxy = loadWorker(); dbProxy.configureTokenStore({ dataDir: tmpDir("dbproxy-stream-error-") }); const SERVICE = "phpmyadmin"; const SESSION_ID = "sess-stream-error"; async function mintedToken() { const minted = await dbProxy.generateToken(SERVICE, "203.0.113.10", "admin@panel.test", SESSION_ID); assert.ok(minted && typeof minted.token === "string", "token minted for the harness session"); return minted.token; } function cookieHeader(token) { return dbProxy.proxyCookieName(SERVICE) + "=" + token; } function mockReq(token) { return { url: "/db-access/phpmyadmin/index.php", method: "GET", headers: { cookie: [ "adpanel.sid=panel-session-secret", cookieHeader(token), "pma_lang=en", ].join("; "), }, sessionID: SESSION_ID, session: { user: "admin@panel.test" }, resume() { }, pipe() { }, }; } const middleware = dbProxy.createProxyMiddleware({ cookieSecure: () => false }); const nextThrows = () => { throw new Error("must not fall through to next()"); }; test("mid-pipe upstream 'error' after headers (instrumented): single settle, no crash", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "application/octet-stream" } }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); // Listener wiring proof BEFORE any event fires: the pre-fix code had // zero 'error' listeners here — emit() would have thrown // "Unhandled 'error' event" and crashed the worker. assert.ok(upstream.listenerCount("error") >= 1, "proxyRes must carry an 'error' listener"); assert.ok(upstream.listenerCount("aborted") >= 1, "proxyRes must carry an 'aborted' listener"); assert.ok(res.headersSent, "precondition: headers already sent"); assert.strictEqual(res.destroyCalls, 0, "precondition: nothing settled yet"); // No try/catch around the emit on purpose: with the listeners missing // this line throws synchronously (the worker-crash mechanism itself). upstream.emit("error", new Error("ECONNRESET mid-pipe")); assert.strictEqual(res.destroyCalls, 1, "the client socket must be destroyed exactly once"); assert.strictEqual(res.endCalls, 0, "a truncated exchange must not be ended 'cleanly' after headers"); assert.strictEqual(res.statusCalls.filter((c) => c === 502).length, 0, "no 502 may be attempted once headers are already sent"); assert.strictEqual(stub.lastReq.destroyCalls, 1, "the backend request must be destroyed (no socket leak)"); assert.strictEqual(upstream.destroyCalls, 1, "the upstream response must be destroyed"); assert.deepStrictEqual(upstream.unpiped, [res], "the direct pipe must be unpiped from the client response"); } finally { stub.restore(); } }); test("single-settle: 'error' then 'aborted' (and repeats) after headers change nothing", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "application/octet-stream" } }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("error", new Error("first failure wins")); const snapshot = { destroyCalls: res.destroyCalls, endCalls: res.endCalls, statusCalls: res.statusCalls.length, reqDestroys: stub.lastReq.destroyCalls, resDestroys: upstream.destroyCalls, }; upstream.emit("aborted"); upstream.emit("error", new Error("late duplicate")); upstream.emit("aborted"); assert.strictEqual(res.destroyCalls, snapshot.destroyCalls, "exactly one settle — no double destroy"); assert.strictEqual(res.endCalls, snapshot.endCalls, "no late end after the settle"); assert.strictEqual(res.statusCalls.length, snapshot.statusCalls, "no late status write"); assert.strictEqual(stub.lastReq.destroyCalls, snapshot.reqDestroys, "backend teardown stays single-shot"); assert.strictEqual(upstream.destroyCalls, snapshot.resDestroys, "upstream teardown stays single-shot"); } finally { stub.restore(); } }); test("'aborted' mid-pipe after headers: clean single teardown, no uncaught", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "application/octet-stream" } }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("aborted"); // no argument — the legacy Node abort signal assert.strictEqual(res.destroyCalls, 1, "the truncated response is torn down exactly once"); assert.strictEqual(res.endCalls, 0); assert.strictEqual(stub.lastReq.destroyCalls, 1); } finally { stub.restore(); } }); test("proxyReq 'error' before any upstream response: 502 once (pre-headers contract preserved)", async () => { const token = await mintedToken(); // invokeCallback: false — the backend dies before delivering any response, // so no proxyRes (and no response-branch listeners) ever exist and the // client response cannot have headers sent. const stub = stubHttp(() => { throw new Error("no response object in this scenario"); }, { invokeCallback: false }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); stub.lastReq.emit("error", new Error("ECONNREFUSED")); assert.strictEqual(res.statusCalls.filter((c) => c === 502).length, 1, "exactly one 502"); assert.strictEqual(res.endCalls, 1, "the 502 is ended once"); assert.strictEqual(res.destroyCalls, 0, "no destroy on the pre-headers failure path"); // A late duplicate error must not double-respond (headers are on the // wire after the 502), and a late timeout must not add a 504. stub.lastReq.emit("error", new Error("duplicate")); stub.lastReq.emit("timeout"); assert.strictEqual(res.statusCalls.filter((c) => c === 502).length, 1, "still exactly one 502"); assert.strictEqual(res.statusCalls.filter((c) => c === 504).length, 0, "no 504 after the settled 502"); assert.strictEqual(res.endCalls, 1, "still exactly one response termination"); } finally { stub.restore(); } }); test("proxyReq 'timeout' before headers: 504 once, and late failure events cannot double-respond", async () => { const token = await mintedToken(); const stub = stubHttp(() => { throw new Error("no response object in this scenario"); }, { invokeCallback: false }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); stub.lastReq.emit("timeout"); assert.strictEqual(res.statusCalls.filter((c) => c === 504).length, 1, "exactly one 504"); assert.strictEqual(res.endCalls, 1, "the 504 is ended once"); assert.strictEqual(res.destroyCalls, 0, "pre-headers timeout: no client destroy needed"); // The handler's own destroy() makes the request dead; any late error / // repeat timeout must not add a second response on top of the 504. stub.lastReq.emit("error", new Error("teardown error")); stub.lastReq.emit("timeout"); assert.strictEqual(res.statusCalls.filter((c) => c === 502).length, 0, "no 502 after the settled 504"); assert.strictEqual(res.statusCalls.filter((c) => c === 504).length, 1, "still exactly one 504"); assert.strictEqual(res.endCalls, 1, "still exactly one response termination"); } finally { stub.restore(); } }); test("proxyReq 'timeout' after headers: the stalled stream is destroyed instead of hanging forever, and the aborted stays single-settle", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "application/octet-stream" } }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); assert.ok(res.headersSent, "precondition: headers already sent"); stub.lastReq.emit("timeout"); assert.strictEqual(res.destroyCalls, 1, "the stalled client socket is destroyed exactly once"); assert.strictEqual(res.statusCalls.filter((c) => c === 504).length, 0, "no header rewrite after headers sent"); upstream.emit("aborted"); // provoked by the request teardown assert.strictEqual(res.destroyCalls, 1, "the aborted must not settle a second time"); assert.strictEqual(res.endCalls, 0); } finally { stub.restore(); } }); test("text branch regression: buffering succeeds byte-identically (rewrite + heartbeat + security headers)", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "text/html; charset=utf-8", "content-length": "999" }, }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("data", Buffer.from('x')); upstream.emit("end"); assert.strictEqual(res.endCalls, 1, "the buffered body is ended exactly once"); assert.strictEqual(res.destroyCalls, 0, "no failure teardown on the success path"); const body = res.writes.map(String).join(""); assert.ok(body.includes("/db-access/phpmyadmin/index.php"), "the phpMyAdmin path rewrite is unchanged"); assert.ok(body.includes("__heartbeat"), "the heartbeat script injection is unchanged"); assert.ok(body.includes(""), "the body closes normally"); assert.strictEqual(res.headers["x-frame-options"], "DENY", "the security baseline is applied before writeHead"); assert.ok(String(res.headers["content-security-policy"]).includes("frame-ancestors 'none'"), "the supplemental frame CSP is applied before writeHead"); assert.strictEqual(res.headers["content-length"], undefined, "content-length is dropped for rewritten text"); } finally { stub.restore(); } }); // adpanel:db-proxy-rewrite-budget - compressed input limits must also bound // expanded text; invalid or truncated bodies must never become clean pages. test("text rewrite rejects compressed expansion and oversized plaintext before forwarding", async () => { const limit = 5 * 1024 * 1024; const oversized = Buffer.alloc(limit + 1, 0x61); for (const [encoding, payload] of [["gzip", zlib.gzipSync(oversized)], ["deflate", zlib.deflateSync(oversized)], ["identity", oversized]]) { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "text/html", "content-encoding": encoding } }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("data", payload); upstream.emit("end"); assert.strictEqual(res.destroyCalls, 1, `${encoding} expansion beyond the rewrite budget must fail the exchange`); assert.strictEqual(res.endCalls, 0, "no oversized or truncated response may end cleanly"); assert.strictEqual(res.writes.length, 0, "rejected text must never reach the client"); assert.strictEqual(stub.lastReq.destroyCalls, 1, "the failed exchange releases its upstream request"); } finally { stub.restore(); } } }); test("text rewrite refuses malformed compressed bodies instead of forwarding them as text", async () => { for (const encoding of ["gzip", "deflate"]) { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "text/html", "content-encoding": encoding } }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("data", Buffer.from("not-a-compressed-response")); upstream.emit("end"); assert.strictEqual(res.destroyCalls, 1, "decode failure must use the shared failure finisher"); assert.strictEqual(res.endCalls, 0, "malformed compressed data is never rendered as HTML"); } finally { stub.restore(); } } }); test("text rewrite preserves valid compressed HTML and its heartbeat", async () => { const html = 'x'; for (const [encoding, payload] of [["gzip", zlib.gzipSync(html)], ["deflate", zlib.deflateSync(html)]]) { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "text/html", "content-encoding": encoding } }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("data", payload); upstream.emit("end"); assert.strictEqual(res.destroyCalls, 0); assert.strictEqual(res.endCalls, 1); assert.ok(res.writes.map(String).join("").includes("/db-access/phpmyadmin/index.php")); assert.ok(res.writes.map(String).join("").includes("__heartbeat")); } finally { stub.restore(); } } }); test("text rewrite keeps HEAD responses bodyless even with a content encoding", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "text/html", "content-encoding": "gzip" } }); return upstream; }); const res = new MockResponse(); try { await middleware({ ...mockReq(token), method: "HEAD" }, res, nextThrows); upstream.emit("end"); assert.strictEqual(res.destroyCalls, 0); assert.strictEqual(res.endCalls, 1); assert.strictEqual(res.writes.length, 0, "HEAD must neither decompress an absent body nor add heartbeat HTML"); } finally { stub.restore(); } }); test("text branch: upstream 'error' mid-buffering settles exactly once (no truncated clean end)", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "text/html", "content-length": "4096" }, }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("data", Buffer.from("half a page")); upstream.emit("error", new Error("reset mid-buffering")); upstream.emit("end"); // a destroyed stream must not deliver 'end' semantics — the settle guard makes this a no-op assert.strictEqual(res.destroyCalls, 1, "the truncated exchange is destroyed exactly once"); assert.strictEqual(res.endCalls, 0, "no res.end(partialText) may fire after the failure settle"); assert.strictEqual(res.statusCalls.length, 0, "no status rewrite after headers sent"); } finally { stub.restore(); } }); test("normal non-text pipe still streams: payload passes through and ends once", async () => { const token = await mintedToken(); const payload = Buffer.from("BINARY-OK"); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "application/octet-stream" }, pipe: (dest) => { dest.write(payload); dest.end(); }, }); return upstream; }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); assert.strictEqual(res.writes.length, 1, "the payload is written through (still streaming, no buffering)"); assert.ok(Buffer.from(res.writes[0]).equals(payload), "the payload passes through byte-identically"); assert.strictEqual(res.endCalls, 1, "pipe end:true still ends the client response once"); assert.strictEqual(res.destroyCalls, 0, "no failure teardown on the success path"); assert.strictEqual(res.statusCode, 200, "the upstream status passes through"); } finally { stub.restore(); } }); test("the finisher's before-headers 502 guard settles exactly once (defensive branch)", async () => { // In the wired middleware proxyRes events can only fire after the response // callback ran synchronously (writeHead included), so the finisher's // pre-headers 502 branch is defensive. This drives it directly: a response // whose headersSent stays false (headers not yet committed) still settles // exactly once and never re-responds. const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "application/octet-stream" } }); return upstream; }); const res = new MockResponse({ headersSentStaysFalse: true }); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("error", new Error("failure before headers committed")); assert.strictEqual(res.statusCalls.filter((c) => c === 502).length, 1, "one 502 from the pre-headers branch"); assert.strictEqual(res.endCalls, 1); upstream.emit("aborted"); upstream.emit("error", new Error("duplicate")); assert.strictEqual(res.statusCalls.filter((c) => c === 502).length, 1, "still exactly one settle"); assert.strictEqual(res.endCalls, 1); assert.strictEqual(res.destroyCalls, 0, "the pre-headers branch ends, it does not destroy"); } finally { stub.restore(); } }); // ─── Client-disconnect pins (adpanel:db-proxy-client-close) ───── // Spies console.error (the module's logger default) so "nothing logged" is // assertable; every caller must restore() it. function captureConsoleError() { const calls = []; const real = console.error; console.error = (...args) => calls.push(args.map(String).join(" ")); return { calls, restore() { console.error = real; } }; } test("client 'close' mid-stream after headers: the upstream exchange is torn down exactly once, no uncaught, no log", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "application/octet-stream" } }); return upstream; }); const errs = captureConsoleError(); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); assert.ok(res.headersSent, "precondition: headers already sent"); assert.strictEqual(stub.lastReq.destroyCalls, 0, "precondition: the dial is live"); // The client dies mid-stream: real Node fires res 'close' with // writableEnded still false, so the guard lets the settle through — the // abandoned export must stop draining the backend socket. res.destroyed = true; res.emit("close"); assert.strictEqual(stub.lastReq.destroyCalls, 1, "the backend request is destroyed promptly"); assert.strictEqual(upstream.destroyCalls, 1, "the upstream response is destroyed"); assert.deepStrictEqual(upstream.unpiped, [res], "the pipe is unpiped from the client response"); assert.strictEqual(res.destroyCalls, 1, "the (already dead) client response is settled exactly once"); assert.strictEqual(res.endCalls, 0, "a dead exchange is never ended cleanly"); // Late duplicates — a second close plus the aborted/error the upstream // teardown provokes — must change nothing (single settle). res.emit("close"); upstream.emit("aborted"); upstream.emit("error", new Error("teardown echo")); assert.strictEqual(stub.lastReq.destroyCalls, 1, "backend teardown stays single-shot"); assert.strictEqual(upstream.destroyCalls, 1, "upstream teardown stays single-shot"); assert.strictEqual(res.destroyCalls, 1, "client settle stays single-shot"); assert.deepStrictEqual(errs.calls, [], "nothing is logged on the client-close settle"); } finally { errs.restore(); stub.restore(); } }); test("client 'close' mid-buffering (text branch): the truncated exchange is destroyed, never ended with partial text", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "text/html", "content-length": "4096" }, }); return upstream; }); const errs = captureConsoleError(); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("data", Buffer.from("half a page")); res.destroyed = true; res.emit("close"); // the client gives up while the body is still buffering assert.strictEqual(stub.lastReq.destroyCalls, 1, "the backend request is destroyed"); assert.strictEqual(upstream.destroyCalls, 1, "the upstream response is destroyed"); assert.strictEqual(res.destroyCalls, 1, "the client response is settled exactly once"); assert.strictEqual(res.endCalls, 0, "no res.end may fire"); // The destroyed upstream must not deliver its buffered half as a clean end // on top of the settle (the same guard the error-settle path relies on). upstream.emit("end"); assert.strictEqual(res.endCalls, 0, "no partial-text end after the client-close settle"); assert.deepStrictEqual(errs.calls, [], "nothing is logged"); } finally { errs.restore(); stub.restore(); } }); test("client 'close' with the dial still in flight (pre-response): the dial is aborted once, single settle", async () => { const token = await mintedToken(); // invokeCallback: false — no proxyRes is ever delivered; real Node fires // res 'close' with writableEnded false BEFORE the response callback would // run, so the settle happens with the upstream reference still null. const stub = stubHttp(() => { throw new Error("no response object in this scenario"); }, { invokeCallback: false }); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); assert.strictEqual(res.headersSent, false, "precondition: no headers committed"); res.destroyed = true; res.emit("close"); assert.strictEqual(stub.lastReq.destroyCalls, 1, "the pending dial is aborted exactly once"); assert.strictEqual(res.statusCalls.filter((c) => c === 502).length, 1, "the finisher's pre-headers branch answers its 502 (swallowed by the dead socket on a real one)"); assert.strictEqual(res.endCalls, 1); // A late close and the destroy-provoked request error must not re-settle // (the 502 commit makes headersSent true, so the error handler skips too). res.emit("close"); stub.lastReq.emit("error", new Error("dial aborted")); assert.strictEqual(stub.lastReq.destroyCalls, 1, "single settle"); assert.strictEqual(res.endCalls, 1, "still exactly one response termination"); } finally { stub.restore(); } }); test("client 'close' after NORMAL completion (pipe branch): a no-op — nothing destroyed, nothing logged", async () => { const token = await mintedToken(); const payload = Buffer.from("DONE-OK"); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "application/octet-stream" }, pipe: (dest) => { dest.write(payload); dest.end(); }, }); return upstream; }); const errs = captureConsoleError(); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); assert.ok(res.writableEnded, "precondition: pipe end:true completed the exchange (res.end ran)"); // Success order: proxyRes 'end' → pipe's res.end() → res 'finish' → // res 'close' — the close that follows a completed exchange MUST be a // no-op, or every keep-alive response teardown would nuke the exchange. res.emit("close"); assert.strictEqual(stub.lastReq.destroyCalls, 0, "nothing destroyed after completion"); assert.strictEqual(upstream.destroyCalls, 0, "the upstream response is untouched"); assert.strictEqual(res.destroyCalls, 0, "the client response is untouched"); assert.strictEqual(res.endCalls, 1, "the successful end is the only termination"); assert.deepStrictEqual(errs.calls, [], "no error is logged for the success-path close"); } finally { errs.restore(); stub.restore(); } }); test("client 'close' after NORMAL completion (text branch): a no-op as well", async () => { const token = await mintedToken(); let upstream; const stub = stubHttp(() => { upstream = fakeProxyRes({ headers: { "content-type": "text/html; charset=utf-8", "content-length": "999" }, }); return upstream; }); const errs = captureConsoleError(); const res = new MockResponse(); try { await middleware(mockReq(token), res, nextThrows); upstream.emit("data", Buffer.from("ok")); upstream.emit("end"); // the text branch's res.end(text) runs here assert.ok(res.writableEnded, "precondition: res.end(text) completed the exchange"); res.emit("close"); assert.strictEqual(stub.lastReq.destroyCalls, 0, "nothing destroyed after completion"); assert.strictEqual(upstream.destroyCalls, 0, "the upstream response is untouched"); assert.strictEqual(res.destroyCalls, 0, "the client response is untouched"); assert.strictEqual(res.endCalls, 1, "the buffered body was ended exactly once"); assert.deepStrictEqual(errs.calls, [], "no error is logged for the success-path close"); } finally { errs.restore(); stub.restore(); } });