Files
Kelx/tests/relay-error-mask.test.js
T
2026-11-30 16:32:37 +00:00

285 lines
13 KiB
JavaScript

"use strict";
// Structure pins for the relay/upload exception-detail mask (adpanel:relay-error-mask).
//
// index.js and nodes.js are application bundles (module side effects, DB and
// network at require time — never require() them from a test), so these tests
// pin the fix structurally on well-anchored source windows, matching the
// convention of tests/node-backups-list-brake.test.js and the scheduler route's
// "the create route 500 no longer leaks internal error text" pin.
//
// The regression each pin exists to prevent: raw exception text
// (err.message/e.message — mysql2 ER_* + host/port fragments, getaddrinfo
// ECONNREFUSED/ENOTFOUND with node addresses, fs paths from temp-upload
// errors, busboy parser text) flowing back into client-visible `detail` /
// `message` fields. The generic detail values are the contract; the full
// error must stay server-side (console.error/warn at the same site).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const { once } = require("node:events");
const { PassThrough } = require("node:stream");
const busboy = require("busboy");
const { createUploadMultipartParser } = require("../services/node-fs-relay");
const ROOT = path.join(__dirname, "..");
const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
const NODES_SRC = fs.readFileSync(path.join(ROOT, "nodes.js"), "utf8");
function functionWindow(src, anchor, label) {
const start = src.indexOf(anchor);
assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`);
const end = src.indexOf("\n}", start);
assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`);
return src.slice(start, end + 2);
}
// Asserts the window's client-visible detail fields are all static: no
// exception object is interpolated into a `detail:`/`message:` payload field.
function assertNoExceptionDerivedDetail(window, label) {
assert.doesNotMatch(
window,
/(?:detail|message):\s*(?:err|e|error)\b/,
`${label}: exception-derived detail text must not reach the client payload (adpanel:relay-error-mask)`
);
}
// ─── 1. The two upload streamers (one responsibility, two surfaces) ──────────
test("nodes.js relay upload streamer settles with generic, path-free detail only", () => {
const win = functionWindow(NODES_SRC, "function streamUploadToNode(", "nodes.js streamUploadToNode");
assertNoExceptionDerivedDetail(win, "nodes.js streamUploadToNode");
assert.ok(
win.includes('error: "upload_network_error", detail: "node connection failed"'),
"network failures keep the actionable generic node-connection wording"
);
assert.ok(
win.includes('error: "upload_stream_error", detail: "upload stream failed"') &&
win.includes('error: "stream_error", detail: "upload failed"'),
"stream failures keep the actionable generic upload wording"
);
// The full error stays server-side at each masked site.
assert.ok(
win.includes('console.warn("[node-upload-relay] node request error:", err)') &&
win.includes('console.error("[node-upload-relay] upload failed:", err)'),
"the raw error must be logged server-side where the detail was masked"
);
// Curated static detail (no exception producer) must survive untouched.
assert.ok(
win.includes('detail: "response stream aborted"'),
"the static aborted detail is curated, not exception-derived — it stays"
);
});
test("index.js panel upload streamer settles with generic, path-free detail only", () => {
const win = functionWindow(INDEX_SRC, "function streamPanelUploadToNode(", "index.js streamPanelUploadToNode");
assertNoExceptionDerivedDetail(win, "index.js streamPanelUploadToNode");
assert.ok(
win.includes('error: "upload_network_error", detail: "node connection failed"') &&
win.includes('error: "upload_stream_error", detail: "upload stream failed"') &&
win.includes('error: "stream_error", detail: "upload failed"'),
"the masked wording is identical to the nodes.js twin (same responsibility, same contract)"
);
assert.ok(
win.includes('console.warn("[upload->node] node request error:", err)') &&
win.includes('console.error("[upload->node] upload failed:", e)'),
"the raw error must be logged server-side where the detail was masked"
);
});
// ─── 2. bad_multipart (busboy errors are exception-derived) ──────────────────
test("both upload routes delegate parse failures to the shared error response", () => {
for (const [src, route, tag] of [
[NODES_SRC, "/api/nodes/server/:name/upload", "[node-upload-relay] multipart parse error:"],
[INDEX_SRC, "/upload", "[/upload] multipart parse error:"],
]) {
const win = functionWindow(src, `app.post("${route}",`, route);
assert.ok(win.includes('createUploadMultipartParser(require("busboy"), req, respond,'), route);
assert.ok(win.includes(`console.warn("${tag}", err)`), `${route}: busboy error stays in the server log`);
assert.ok(win.includes("if (!multipart) return;"), `${route}: stops when setup already answered`);
}
});
function multipartRequest(headers = { "content-type": "multipart/form-data; boundary=fixture" }) {
return Object.assign(new PassThrough(), { headers });
}
test("multipart setup errors and stream errors receive the same generic response", async () => {
for (const headers of [{}, { "content-type": "multipart/form-data; boundary=fixture" }]) {
const errors = [];
const response = await new Promise((resolve) => {
const multipart = createUploadMultipartParser(busboy, multipartRequest(headers), (status, body) => resolve({ status, body }),
(err) => errors.push(err));
if (multipart) multipart.parser.end();
});
assert.deepStrictEqual(response, {
status: 400,
body: { error: "bad_multipart", detail: "invalid multipart form data" },
});
assert.strictEqual(errors.length, 1);
assert.ok(errors[0] instanceof Error);
}
});
test("multipart metadata is fixed at file start and early part errors settle once", () => {
const errors = [];
const responses = [];
const { parser, fields } = createUploadMultipartParser(
busboy,
multipartRequest(),
(status, body) => responses.push({ status, body }),
(err) => errors.push(err)
);
const stream = new PassThrough();
const streamError = new Error("fixture part failed");
parser.emit("field", "bot", "fixture-server");
parser.emit("field", "path", "fixture-dir");
parser.emit("field", "filename", "fixture.txt");
parser.emit("file", "file", stream);
parser.emit("field", "filename", "later.txt");
assert.ok(Object.isFrozen(fields));
assert.deepStrictEqual({ ...fields }, { bot: "fixture-server", path: "fixture-dir", filename: "fixture.txt" });
stream.emit("error", streamError);
parser.emit("error", new Error("fixture parser failed"));
assert.deepStrictEqual(errors, [streamError]);
assert.deepStrictEqual(responses, [{
status: 400,
body: { error: "bad_multipart", detail: "invalid multipart form data" },
}]);
});
test("multipart uploads decode the browser's UTF-8 filename", async () => {
const request = multipartRequest();
const { parser, fields } = createUploadMultipartParser(busboy, request, assert.fail, assert.fail);
let filename;
parser.on("file", (_field, stream) => {
filename = fields.filename;
stream.resume();
});
const finished = once(parser, "finish");
request.pipe(parser);
request.complete = true;
request.end(Buffer.from('--fixture\r\nContent-Disposition: form-data; name="file"; filename="caf\u00e9.txt"\r\n\r\nFixture\r\n--fixture--\r\n'));
await finished;
assert.strictEqual(filename, "caf\u00e9.txt");
});
test("multipart uploads keep quoted names distinct from literal percent-encoded names", async () => {
for (const name of ['notes "draft".txt', 'notes %22draft%22.txt']) {
const form = new FormData();
form.set("filename", name);
form.set("file", new Blob(["Fixture"]), name);
const encoded = new Response(form);
const request = multipartRequest({ "content-type": encoded.headers.get("content-type") });
const { parser, fields } = createUploadMultipartParser(busboy, request, assert.fail, assert.fail);
let filename;
parser.on("file", (_field, stream) => {
filename = fields.filename;
stream.resume();
});
const finished = once(parser, "finish");
request.pipe(parser);
request.complete = true;
request.end(Buffer.from(await encoded.arrayBuffer()));
await finished;
assert.strictEqual(filename, name);
}
});
test("multipart uploads release the active file when the client disconnects", async () => {
const request = multipartRequest();
const { parser } = createUploadMultipartParser(busboy, request, () => {}, () => {});
let file;
parser.on("file", (_field, stream) => { file = stream; stream.resume(); });
request.pipe(parser);
request.write('--fixture\r\nContent-Disposition: form-data; name="file"; filename="fixture.txt"\r\n\r\npartial');
const closed = once(request, "close");
request.destroy();
await closed;
try {
assert.ok(file, "the upload was already being parsed");
assert.strictEqual(parser.destroyed, true);
assert.strictEqual(file.destroyed, true);
} finally {
parser.destroy();
}
});
// ─── 3. Point fixes masked in this campaign ──────────────────────────────────
test("the node-proxy create backstop answers node_create_failed with a generic detail", () => {
const anchor = 'app.post("/api/nodes/:id/servers/create"';
const start = NODES_SRC.indexOf(anchor);
assert.notStrictEqual(start, -1, "create backstop route not found");
const win = NODES_SRC.slice(start, NODES_SRC.indexOf("\n});", start));
assert.ok(
win.includes('error: "node_create_failed", detail: "internal error"'),
"the backstop 500 keeps the key and loses err.message"
);
assert.ok(win.includes('console.error("[nodes] POST /api/nodes/:id/servers/create failed:"'), "the raw error stays in the log above");
assertNoExceptionDerivedDetail(win, "create backstop");
});
test("the fivem artifact download catch answers with a generic detail", () => {
const anchor = 'error: "fivem-artifact-download-failed", detail:';
const start = INDEX_SRC.indexOf(anchor);
assert.notStrictEqual(start, -1, "fivem artifact catch not found");
const win = INDEX_SRC.slice(start - 200, start + 200);
assert.ok(win.includes('detail: "Remote artifact download failed."'), "generic detail required");
assert.ok(win.includes('console.error("[fivem-artifact] artifact download/relay failed:", e)'), "the raw error stays server-side");
assertNoExceptionDerivedDetail(win, "fivem artifact catch");
});
test("the resources-restart 502 keeps its key and loses err.message", () => {
const anchor = 'error: "resources updated but restart failed"';
const start = INDEX_SRC.indexOf(anchor);
assert.notStrictEqual(start, -1, "restart-failed 502 not found");
const win = INDEX_SRC.slice(start - 200, start + 200);
assert.ok(win.includes('detail: "internal error"'), "generic detail required");
assert.ok(win.includes('console.error("[/api/settings/servers/:name/resources] restart failed:", e)'), "the raw error stays server-side");
assertNoExceptionDerivedDetail(win, "restart-failed 502");
});
test("/upload-url download failures keep the actionable generic message", () => {
const anchor = 'error: "download_failed"';
const start = INDEX_SRC.indexOf(anchor);
assert.notStrictEqual(start, -1, "download_failed 502 not found");
const win = INDEX_SRC.slice(start - 200, start + 200);
assert.ok(
win.includes("The remote file could not be downloaded. Check the URL and try again."),
"the user-facing message stays actionable without the raw network error"
);
assert.ok(win.includes('console.error("[/upload-url] download failed:", err)'), "the raw error stays server-side");
assertNoExceptionDerivedDetail(win, "download_failed 502");
});
test("both /api/servers/create 500 catches answer with a generic detail", () => {
for (const logAnchor of [
'console.error("[/api/servers/create] pre-flight failed:", err);',
'console.error("[/api/servers/create] failed:", e);',
]) {
const start = INDEX_SRC.indexOf(logAnchor);
assert.notStrictEqual(start, -1, `create catch not found: ${logAnchor}`);
const win = INDEX_SRC.slice(start, start + 500);
assert.ok(win.includes('error: "create failed"') && win.includes('detail: "internal error"'), "generic 500 detail required");
assertNoExceptionDerivedDetail(win, logAnchor);
}
});
test("the Cloudflare proxy-verify payload no longer carries resolver error text", () => {
const anchor = "Could not resolve ${hostname} in public DNS for Cloudflare proxy verification.";
const win = functionWindow(NODES_SRC, "async function verifyCloudflareProxiedAddress(", "verifyCloudflareProxiedAddress");
const at = win.indexOf(anchor);
assert.notStrictEqual(at, -1, "resolution-failure payload not found");
const payload = win.slice(at - 200, at + 200);
assert.ok(payload.includes("detail: null"), "the per-resolver DNS error text must not reach the client");
assert.ok(
payload.includes('console.warn("[nodes] Cloudflare proxy verification could not resolve"'),
"the raw resolver errors stay in the server log"
);
});