"use strict"; // Regression tests for the node-response size cap (finding 12). // // nodes.js buffered every node response with no size limit: httpJson(), // callNodeApiOnce() (via callNodeApi), httpRequestJson() and // httpRequestJsonWithBody() accumulated res "data" chunks until "end" before // parsing, so a misbehaving or compromised daemon could exhaust the panel // worker's memory through the fs list/read relays alone. index.js's // counterpart (httpGetRaw/nodeFsPost) already caps buffered bodies at 16 MiB // — a size chosen to fit every daemon-legal response with headroom (max // editor read 10 MiB → ~13.7 MiB base64-encoded → more with JSON escaping) — // and answers node_response_too_large for over-cap list/read. // // nodes.js now mirrors that, and (adpanel:relay-helper-consolidation, Wave 3) // the cap itself is enforced in ONE place: the hardened core in // services/node-http.js. httpJson() and the GET-probe httpRequestJson() are // thin wrappers over that core (pinned below to stay wrappers); the inline // callNodeApiOnce() keeps the file's local MAX_NODE_RESPONSE_BYTES cap; and // httpRequestJsonWithBody() — which had ZERO callers (verified by grep across // nodes.js, index.js, utils/ and services/; only this file's old pin knew its // name) — was deleted, with its slice of the structural pin consciously // dropped rather than silently: the invariant it guarded is re-asserted over // the helpers that exist (the wrappers are pinned to delegate to the capped // core, so a private buffered reimplementation cannot quietly reappear). // The /api/nodes/server/:name/entries and /file relays still map a too-large // dial to 502 node_response_too_large (with index.js's user-facing wording) // instead of the misleading node_list_failed / node_read_failed. // // adpanel:relay-helper-consolidation (Wave 2 Step B3): the two relays' dial // + outcome mapping moved onto the shared services/node-fs-relay.js core // (relayFsJson + renderFsListOutcome/renderFsReadOutcome, relay variant), so // the route pins below assert the delegation AND the shared renderer's // branch order/wording (byte-pinned behaviorally in // node-fs-relay-routes.test.js); the classification itself // (status 0 + tooLarge ⇒ too_large, never offline) is pinned on // classifyNodeJsonResult. // // nodes.js cannot be exercised through index.js (it boots servers on // require), so — same Module._load technique as node-api-bind-host.test.js — // nodes.js is loaded in-process against a stubbed db module and pointed at // real local HTTP servers (ADPANEL_ALLOW_PRIVATE_NODES=1 lets the SSRF guard // accept loopback). httpJson is exported and behaviorally tested here end to // end (wrapper + core); the GET-probe httpRequestJson wrapper is not // exported, so its delegation is pinned at source level below. const test = require("node:test"); const assert = require("node:assert"); const http = require("node:http"); const https = require("node:https"); const { EventEmitter } = require("node:events"); const fs = require("node:fs"); const path = require("node:path"); const Module = require("node:module"); process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1"; const ROOT = path.join(__dirname, ".."); const NODES_JS = path.join(ROOT, "nodes.js"); const INDEX_JS = path.join(ROOT, "index.js"); const CAP = 16 * 1024 * 1024; const dbStub = { async query() { return []; }, pool: { async execute() { return [[]]; }, async query() { return [[]]; }, }, }; const nodes = (() => { const originalLoad = Module._load; Module._load = function (request, parent, isMain) { if (request === "./db" && parent && parent.filename === NODES_JS) return dbStub; return originalLoad.apply(this, arguments); }; try { return require(NODES_JS); } finally { Module._load = originalLoad; } })(); function startNodeHttpServer(handler) { return new Promise((resolve, reject) => { const server = http.createServer(handler); server.on("error", reject); server.listen(0, "127.0.0.1", () => resolve({ server, port: server.address().port })); }); } // close() alone leaves an active socket holding the event loop open when a // test fails before the client hangs up. function stopServer(server) { if (!server) return; if (typeof server.closeAllConnections === "function") server.closeAllConnections(); server.close(); } function withDeadline(promise, ms, message) { // Clear the losing timer on settle: a pending setTimeout would keep the // event loop alive for the whole deadline after the tests have passed. let timer; const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); }); return Promise.race([promise, deadline]).finally(() => clearTimeout(timer)); } const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // The client's destroy and the server's 'close' event are on opposite sides // of a socket, so the flag can lag the settled promise by a few ticks: poll // with a deadline instead of asserting inline. async function waitFor(predicate, ms, message) { const start = Date.now(); while (!predicate()) { if (Date.now() - start > ms) throw new Error(message); await sleep(10); } } // Streams 1 MiB chunks forever until the client disconnects. Bytes are // counted at write() call time, which always precedes client receipt — a // safe lower bound for what the client has pulled. A long client timeoutMs // guarantees the promise cannot settle via the timeout path: if the cap did // not trigger, the test fails on its own deadline instead of passing // vacuously. function endlessOverCapServer() { const state = { bytesWritten: 0, clientAborted: false }; const promise = startNodeHttpServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); const chunk = Buffer.alloc(1024 * 1024, 0x61); const pump = setInterval(() => { if (state.clientAborted || res.destroyed) return; state.bytesWritten += chunk.length; try { res.write(chunk); } catch { } }, 1); const stop = () => { state.clientAborted = true; clearInterval(pump); try { res.destroy(); } catch { } }; res.on("close", stop); res.on("error", stop); req.on("error", stop); }).then(({ server, port }) => ({ server, port })); return { promise, state }; } test("httpJson aborts an unbounded chunked node response once it crosses the 16 MiB cap", async () => { const { promise, state } = endlessOverCapServer(); let server; try { ({ server } = await promise); const port = server.address().port; const result = await withDeadline( nodes.httpJson(`http://127.0.0.1:${port}/`, { timeoutMs: 30000 }), 15000, "httpJson never settled — the response cap did not trigger and the helper buffered indefinitely" ); assert.equal(result.status, 0, "over-cap response must be reported as a transport-level failure"); assert.equal(result.tooLarge, true, "over-cap response must carry the tooLarge marker"); assert.equal(result.error, "response too large"); assert.equal(result.json, null); await waitFor( () => state.clientAborted, 2000, "the client never destroyed the response mid-stream — it drained the unbounded body" ); assert.ok( state.bytesWritten >= CAP, `cap must trigger only after crossing ${CAP} bytes, server observed ${state.bytesWritten}` ); } finally { stopServer(server); } }); test("httpJson rejects a Content-Length over-cap response from the headers alone", async () => { let server; const state = { bytesWritten: 0, clientAborted: false, responseFinished: false }; try { ({ server } = await startNodeHttpServer((req, res) => { // 256 KiB every 5ms: draining the whole 64 MiB body would take ~1.3s, // so "aborted within 200ms of settle" cannot be confused with "read to // the end". res.writeHead(200, { "Content-Type": "application/json", "Content-Length": String(4 * CAP), }); const chunk = Buffer.alloc(256 * 1024, 0x61); const pump = setInterval(() => { if (state.clientAborted || res.destroyed || res.writableEnded) return; state.bytesWritten += chunk.length; try { res.write(chunk); } catch { } if (state.bytesWritten >= 4 * CAP) { state.responseFinished = true; res.end(); clearInterval(pump); } }, 5); const stop = () => { state.clientAborted = true; clearInterval(pump); }; res.on("close", stop); req.on("error", stop); })); const port = server.address().port; const result = await withDeadline( nodes.httpJson(`http://127.0.0.1:${port}/`, { timeoutMs: 30000 }), 15000, "httpJson never settled — the Content-Length pre-check did not trigger" ); assert.equal(result.status, 0); assert.equal(result.tooLarge, true); assert.equal(result.json, null); await waitFor( () => state.clientAborted, 2000, "the client never destroyed the socket — it ignored the over-cap Content-Length" ); assert.equal(state.responseFinished, false, "the client must abort long before the server finishes writing"); } finally { stopServer(server); } }); test("httpJson still parses responses under the cap unchanged", async () => { let server; try { ({ server } = await startNodeHttpServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ ok: true, entries: [1, 2, 3], pad: "a".repeat(1024 * 1024) })); })); const port = server.address().port; const result = await nodes.httpJson(`http://127.0.0.1:${port}/`, { timeoutMs: 10000 }); assert.equal(result.status, 200); assert.equal(result.tooLarge, undefined); assert.equal(result.json.ok, true); assert.deepEqual(result.json.entries, [1, 2, 3]); } finally { stopServer(server); } }); test("httpJson accepts a body of exactly 16 MiB (cap is strictly greater-than)", async () => { let server; try { // {"ok":true,"pad":"AAAA…"} sized to exactly 16 MiB so both the // Content-Length pre-check and the streaming counter land ON the // boundary, not past it. const prefix = '{"ok":true,"pad":"'; const suffix = '"}'; const padLen = CAP - Buffer.byteLength(prefix) - Buffer.byteLength(suffix); const body = prefix + "A".repeat(padLen) + suffix; assert.equal(Buffer.byteLength(body), CAP, "test body must be exactly at the cap"); ({ server } = await startNodeHttpServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json", "Content-Length": String(CAP) }); res.end(body); })); const port = server.address().port; const result = await nodes.httpJson(`http://127.0.0.1:${port}/`, { timeoutMs: 30000 }); assert.equal(result.status, 200); assert.equal(result.json.ok, true, "a body at the cap is daemon-legal and must parse"); assert.equal(result.tooLarge, undefined); } finally { stopServer(server); } }); test("callNodeApi listens for response errors before rejecting oversized headers", async () => { const { configureNodeHttp } = require("../services/node-http"); const tlsAgent = new https.Agent(); for (const [sslEnabled, transport] of [[false, http], [true, https]]) { const originalRequest = transport.request; const upstream = new EventEmitter(); upstream.statusCode = 200; upstream.headers = { "content-length": String(CAP + 1) }; let escapedError; let listenerCounts; let requestAgent; upstream.destroy = () => { listenerCounts = [upstream.listenerCount("error"), upstream.listenerCount("aborted")]; upstream.emit("aborted"); try { upstream.emit("error", new Error("upstream reset during rejection")); } catch (error) { escapedError = error; } }; transport.request = (url, options, callback) => { requestAgent = options.agent; const request = new EventEmitter(); request.setTimeout = () => request; request.destroy = () => {}; request.end = () => process.nextTick(() => callback(upstream)); return request; }; try { configureNodeHttp({ getNodeMtlsAgent: () => tlsAgent }); const result = await nodes.callNodeApi({ address: "127.0.0.1", api_port: 8080, ssl_enabled: sslEnabled }, "/v1/disks", "GET", null, 1000); assert.strictEqual(requestAgent, sslEnabled ? tlsAgent : undefined); assert.strictEqual(escapedError, undefined, "an oversized response must not escape through an unhandled error"); assert.ok(listenerCounts.every((count) => count > 0), "both listeners must attach before response destruction"); assert.strictEqual(result.tooLarge, true); assert.strictEqual(result.error, "response too large"); assert.strictEqual(upstream.listenerCount("data"), 0, "no over-cap body may be buffered"); } finally { transport.request = originalRequest; configureNodeHttp({ getNodeMtlsAgent: () => null }); } } }); test("callNodeApi (callNodeApiOnce) rejects an over-cap node response with the tooLarge shape", async () => { let server; const state = { clientAborted: false }; try { ({ server } = await startNodeHttpServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); const chunk = Buffer.alloc(1024 * 1024, 0x61); const pump = setInterval(() => { if (state.clientAborted || res.destroyed) return; try { res.write(chunk); } catch { } }, 1); const stop = () => { state.clientAborted = true; clearInterval(pump); try { res.destroy(); } catch { } }; res.on("close", stop); res.on("error", stop); req.on("error", stop); })); const port = server.address().port; const result = await withDeadline( nodes.callNodeApi( { address: "127.0.0.1", api_port: port, ssl_enabled: false, token: "test-token", token_id: "1" }, "/v1/disks", "GET", null, 30000 ), 15000, "callNodeApi never settled — the response cap did not trigger" ); assert.equal(result.status, 0); assert.equal(result.tooLarge, true); assert.equal(result.error, "response too large"); assert.equal(result.json, null); await waitFor( () => state.clientAborted, 2000, "the client never destroyed the response mid-stream" ); } finally { stopServer(server); } }); // --------------------------------------------------------------------------- // httpJson {status, json, text} shape asymmetry (behavioral pin) // // The shape is load-bearing and was only comment-verified: the backup // performers' logging reads `String(json?.error || text || "no body")`, which // stays shape-exact only while the end path carries the raw body as `text`, // the guard-/response-error/too-large paths carry `text: null`, and the // timeout / request-error / setup-failure paths resolve WITHOUT the text key // at all (services/node-http.js noBodyResult vs the bare timeout shapes). // These four tests drive nodes.httpJson over real loopback dials so a core // refactor cannot silently flatten the asymmetry. // --------------------------------------------------------------------------- test("httpJson carries the raw response body as text on the end path", async () => { let server; try { ({ server } = await startNodeHttpServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); res.end('{"ok":true,"marker":"end-path"}'); })); const port = server.address().port; const result = await nodes.httpJson(`http://127.0.0.1:${port}/`, { timeoutMs: 10000 }); assert.equal(result.status, 200); assert.ok("text" in result, "the end path must carry the text key"); assert.equal(result.text, '{"ok":true,"marker":"end-path"}'); assert.equal(result.json.ok, true); } finally { stopServer(server); } }); test("httpJson resolves text: null (key present) on a mid-body response abort", async () => { let server; try { ({ server } = await startNodeHttpServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json", "Content-Length": "1000" }); res.write('{"ok":true,"partial"'); // Destroy mid-body so the client's 'aborted'/'error' path settles — // the response error branch, not the end branch. setTimeout(() => { try { res.destroy(); } catch { } }, 20); })); const port = server.address().port; const result = await withDeadline( nodes.httpJson(`http://127.0.0.1:${port}/`, { timeoutMs: 10000 }), 10000, "httpJson never settled after a mid-body response abort" ); assert.equal(result.status, 0); assert.equal(result.json, null); assert.ok("text" in result, "the response-error/aborted branch must keep the text key (as text: null)"); assert.equal(result.text, null); } finally { stopServer(server); } }); test("httpJson omits the text key entirely on the timeout path", async () => { let server; try { // Accept the connection and never answer: only the inactivity/hard // timeout can settle the promise. ({ server } = await startNodeHttpServer(() => { })); const port = server.address().port; const result = await withDeadline( nodes.httpJson(`http://127.0.0.1:${port}/`, { timeoutMs: 250 }), 10000, "httpJson never settled — the timeout path did not fire" ); assert.equal(result.status, 0); assert.equal(result.json, null); assert.ok(!("text" in result), "the timeout path must resolve WITHOUT the text key — String(json?.error || text || …) logging relies on the absence"); } finally { stopServer(server); } }); test("httpJson omits the text key entirely on the request-error path", async () => { // Claim a port, then close it: dialing it refuses with ECONNREFUSED, which // settles through req.on("error") without a response object. const server = http.createServer(() => { }); const port = await new Promise((resolve, reject) => { server.on("error", reject); server.listen(0, "127.0.0.1", () => resolve(server.address().port)); }); await new Promise((resolve) => server.close(resolve)); stopServer(server); const result = await nodes.httpJson(`http://127.0.0.1:${port}/`, { timeoutMs: 5000 }); assert.equal(result.status, 0); assert.equal(result.json, null); assert.ok(!("text" in result), "the request-error path must resolve WITHOUT the text key"); }); // --------------------------------------------------------------------------- // Source-level pins // --------------------------------------------------------------------------- const nodesSrc = fs.readFileSync(NODES_JS, "utf8"); // adpanel:relay-helper-consolidation — index.js's httpRequestJson (and the 16 // MiB MAX_RESPONSE_BYTES cap it carried) moved verbatim to // services/node-http.js; the parity pin below now reads that module. Same // invariant: the panel-side cap stays 16 MiB and mirrors MAX_NODE_RESPONSE_BYTES. const NODE_HTTP_JS = path.join(ROOT, "services", "node-http.js"); const nodeHttpSrc = fs.readFileSync(NODE_HTTP_JS, "utf8"); // Slice a function body out of the source: from its "function name(" up to // the next top-level "function " marker (all four helpers live at column 0). function functionBody(src, name, nextName) { const start = src.indexOf(`function ${name}(`); assert.notStrictEqual(start, -1, `expected function ${name} to exist in nodes.js`); const end = nextName ? src.indexOf(`function ${nextName}(`, start) : src.length; assert.notStrictEqual(end, -1, `expected function ${nextName} after ${name} in nodes.js`); return src.slice(start, end); } // Wave 3 re-point (adpanel:relay-helper-consolidation): httpRequestJson and // httpJson became thin wrappers over services/node-http.js's hardened core — // the 16 MiB cap, the Content-Length pre-check and the tooLarge shape live // there now (core-side pins below) — and httpRequestJsonWithBody (zero // callers) was deleted. The invariant this file exists to make ("every // nodes.js HTTP helper enforces the 16 MiB cap and answers // node_response_too_large with index.js's wording") is asserted over the // helpers that EXIST: the one helper that still buffers inline // (callNodeApiOnce) is pinned by body as before, and the wrappers are pinned // to delegate to the capped core so a private buffered reimplementation // cannot quietly reappear. const CAPPED_HELPERS = [ ["callNodeApiOnce", "callNodeApi"], ]; for (const [name, nextName] of CAPPED_HELPERS) { test(`nodes.js ${name} enforces the response cap (Content-Length pre-check + streaming cap)`, () => { const body = functionBody(nodesSrc, name, nextName); assert.match( body, /MAX_NODE_RESPONSE_BYTES/, `${name} must reference MAX_NODE_RESPONSE_BYTES — it buffers node responses and a misbehaving daemon must not be able to exhaust worker memory through it` ); assert.match( body, /content-length[\s\S]{0,200}MAX_NODE_RESPONSE_BYTES/, `${name} must reject an over-cap Content-Length from the headers, before buffering any body bytes` ); assert.match( body, /nodeResponseTooLarge\(\)/, `${name} must resolve the shared { status: 0, tooLarge: true } shape so routes can answer node_response_too_large` ); }); } const WRAPPED_HELPERS = [ ["httpRequestJson", "callNodeApiOnce"], ["httpJson", "tcpCheck"], ]; for (const [name, nextName] of WRAPPED_HELPERS) { test(`nodes.js ${name} is a thin wrapper over the shared hardened core (cap enforced there)`, () => { const body = functionBody(nodesSrc, name, nextName); assert.match( body, /httpRequestJsonCore\(/, `${name} must dial through services/node-http.js's hardened core — a private buffered reimplementation here would re-open the unbounded-buffer class this file guards` ); assert.doesNotMatch( body, /\b(?:http|https)\.request\(/, `${name} must not open its own request — the cap/listener/timer posture lives once, in the core` ); }); } // The wording half of the invariant, asserted where it is built now: the // core's too-large result keeps the error marker the routes answer // node_response_too_large from (the wrappers and callNodeApiOnce resolve this // same shape). test("the shared core keeps the tooLarge marker and 'response too large' wording", () => { assert.match( nodeHttpSrc, /error: "response too large", tooLarge: true/, "the core's too-large result must keep the marker and wording node_response_too_large mapping depends on" ); }); test("MAX_NODE_RESPONSE_BYTES is 16 MiB, mirroring index.js MAX_RESPONSE_BYTES", () => { assert.match(nodesSrc, /const MAX_NODE_RESPONSE_BYTES = 16 \* 1024 \* 1024;/); assert.match(nodeHttpSrc, /const MAX_RESPONSE_BYTES = 16 \* 1024 \* 1024;/, "the shared module's cap drifted — keep both sides of the parity together"); }); // The two relays called out by the finding must answer node_response_too_large // BEFORE the generic failure, with index.js's user-facing wording. // Wave 2 Step B3 re-point: the mapping now lives in the shared renderer, so // each pin has two halves — the ROUTE window must delegate (dial the shared // core, render the relay variant with no local mapping of its own), and the // RENDERER body must order too_large before the generic failure and carry // index.js's wording (the same guarantee the old route-body pins made, moved // to where the bodies are built now). const RELAY_FS_MOD = path.join(ROOT, "services", "node-fs-relay.js"); const relayFsModSrc = fs.readFileSync(RELAY_FS_MOD, "utf8"); function relayRendererBody(name, nextName) { const start = relayFsModSrc.indexOf(`function ${name}(`); assert.notStrictEqual(start, -1, `expected function ${name} to exist in services/node-fs-relay.js`); const end = nextName ? relayFsModSrc.indexOf(`function ${nextName}(`, start) : relayFsModSrc.length; assert.notStrictEqual(end, -1, `expected function ${nextName} after ${name} in services/node-fs-relay.js`); return relayFsModSrc.slice(start, end); } const ROUTE_PINS = [ { route: 'app.get("/api/nodes/server/:name/entries"', renderer: "renderFsListOutcome", nextRenderer: "renderFsReadOutcome", variantNeedle: 'renderFsListOutcome(outcome, rel, { variant: "relay", entryMapper: mapFsEntries })', genericError: "node_list_failed", messagePart: "Open a subdirectory instead", }, { route: 'app.get("/api/nodes/server/:name/file"', renderer: "renderFsReadOutcome", nextRenderer: "renderFsStreamOutcome", variantNeedle: 'renderFsReadOutcome(outcome, rel, { variant: "relay" })', genericError: "node_read_failed", messagePart: "Download the file instead", }, ]; for (const { route, renderer, nextRenderer, variantNeedle, genericError, messagePart } of ROUTE_PINS) { test(`${route} answers node_response_too_large before ${genericError}`, () => { // Route half: the relay must delegate to the shared core + relay renderer. const start = nodesSrc.indexOf(route); assert.notStrictEqual(start, -1, `expected the ${route} relay to exist`); const nextRoute = nodesSrc.indexOf("\napp.get(", start + 1); const body = nodesSrc.slice(start, nextRoute === -1 ? nodesSrc.length : nextRoute); assert.match( body, /relayFsJson\(/, "the relay must dial through the shared services/node-fs-relay.js core (relayFsJson)" ); assert.ok( body.includes(variantNeedle), `the relay must render through ${renderer} with the relay variant (no local response mapping left in the route)` ); // Renderer half: the shared renderer answers an over-cap dial through an // explicit too_large case carrying node_response_too_large (the wording // lives in the module's shared message constant, pinned just below) — // the size failure arrives as status 0 and must never fall into the // generic failure branch. The generic failure itself must remain for // genuine node failures. const rb = relayRendererBody(renderer, nextRenderer); assert.match( rb, /case "too_large":\s*\n\s*return \{ status: 502, json: \{ error: "node_response_too_large", message: FS_[A-Z_]+_TOO_LARGE_MESSAGE \} \};/, "the renderer must answer a too-large dial with node_response_too_large through its own case, never the generic failure" ); assert.ok( rb.includes(`error: "${genericError}"`), `the generic ${genericError} failure must remain for genuine node failures` ); const escapedPart = messagePart.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); assert.match( relayFsModSrc, new RegExp(`const FS_[A-Z_]+_TOO_LARGE_MESSAGE = "[^"]*${escapedPart}`), `the 502 message must carry index.js's user guidance ("${messagePart}")` ); }); } // The classification invariant the former route bodies enforced inline // (`status === 0 && tooLarge` before the generic failure) now lives in // classifyNodeJsonResult: a status-0 dial with the tooLarge marker must be // classified too_large, never offline. test("classifyNodeJsonResult separates a too-large dial from offline before any node-failure kind", () => { const cb = relayRendererBody("classifyNodeJsonResult", null); const tooLargeAt = cb.indexOf("too_large"); const offlineAt = cb.indexOf('"offline"'); assert.notStrictEqual(tooLargeAt, -1, "expected a too_large classification"); assert.notStrictEqual(offlineAt, -1, "expected an offline classification"); assert.ok(tooLargeAt < offlineAt, "too_large must be classified before offline"); assert.match(cb, /status === 0 && result && result\.tooLarge/); });