"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("x