Files
Kelx/utils/server-asset-apply-streaming.test.js
2026-11-30 16:32:37 +00:00

379 lines
16 KiB
JavaScript

"use strict";
// Regression tests for the proxy-download apply path (REMOTE_APPLY_PROXY_
// DOWNLOAD=1, the panel default): the artifact downloaded from the tenant-
// supplied URL must be streamed into the panel's temp file and relayed from
// disk, never accumulated in heap.
//
// The old implementation called httpGetRaw, which collected the whole body as
// chunks and then Buffer.concat'ed a second full copy — up to
// 2x REMOTE_APPLY_MAX_BYTES (default 1 GiB) of heap per request, with no
// route-level limiter and the global limiter shipped disabled (security.json
// rate_limiting: false). A single store_access tenant looping mint→apply
// against a large file it hosted could OOM the panel worker and drop every
// tenant's session. The fix streams via the same SSRF-safe getter the FiveM
// and /upload-url paths use, caps the panel-wide concurrent applies with a
// download gate, and the routes carry always-on abuse brakes (pinned
// structurally in tests/store-route-abuse-brakes.test.js).
const test = require("node:test");
const assert = require("node:assert");
const http = require("http");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { PassThrough } = require("stream");
const { EventEmitter } = require("events");
const { setTimeout: delay } = require("timers/promises");
const { createRemoteHttpGetters } = require("./remote-http");
// The fake upload sink runs on loopback; uploadFileToNode now carries the same
// SSRF guard as every other node-credential dial, so the suite needs the same
// loopback opt-in every sibling behavioral file sets (see
// tests/server-suspension-rest-bridge.test.js for the convention).
process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1";
const { applyRemoteAssetToServer, createDownloadGate } = require("./server-asset-apply");
const ENTRY = { name: "Test Server", bot: "test-server", nodeId: "node-1" };
const BASE_DIR = "/srv/test-server";
const JAR_URL = "https://example.com/server.jar";
// Local multipart sink standing in for the node's /v1/fs/upload: captures the
// raw form body so tests can assert exactly what the panel relayed.
function startUploadSink() {
const state = { requests: [], releases: [] };
const server = http.createServer((req, res) => {
const chunks = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
const record = {
headers: req.headers,
body: Buffer.concat(chunks),
released: false,
respond: () => {
if (record.released) return;
record.released = true;
res.statusCode = 200;
res.end(JSON.stringify({ ok: true }));
},
};
state.requests.push(record);
if (state.holdResponses) return;
record.respond();
});
});
return new Promise((resolve) => {
server.listen(0, "127.0.0.1", () => {
state.port = server.address().port;
state.close = () => new Promise((done) => server.close(done));
resolve(state);
});
});
}
function makeProxyDeps(sink, overrides = {}) {
const calls = { streams: [], uploads: [] };
const deps = {
findServer: async () => ENTRY,
isRemoteEntry: () => true,
findNodeByIdOrName: async () => ({ id: "node-1", address: "127.0.0.1", api_port: sink.port, ssl_enabled: false }),
buildNodeBaseUrl: () => `http://127.0.0.1:${sink.port}`,
nodeUnderCloudflare: () => false,
nodeAuthHeadersFor: () => ({ Authorization: "Bearer node-token" }),
nodeAdminSigningSecrets: () => ["ab".repeat(32)],
// Proxy mode must never take the signed-forward lane.
httpRequestJson: async () => {
throw new Error("forward-to-node must not run in proxy-download mode");
},
assertSafeRemoteUrl: async (u) => new URL(u),
resolveRemoteFsContext: async () => ({ remote: true, node: { id: "node-1" }, baseDir: BASE_DIR, serverName: "test-server" }),
nodeFsPost: async () => ({ status: 200, json: { ok: true } }),
// The buffered getter is banned on this path: if the util ever reaches for
// it again, this fails the test instead of silently re-buffering.
httpGetRaw: async () => {
throw new Error("httpGetRaw (heap buffering) must not be used by the apply path");
},
httpGetStream: async (url, opts) => {
calls.streams.push({ url, opts });
const stream = new PassThrough();
calls._source = stream;
return { stream, contentType: "application/java-archive", finalUrl: url };
},
remoteApplyProxyDownload: true,
remoteApplyMaxBytes: 1024 * 1024,
remoteApplyTimeoutMs: 5000,
remoteFetchMaxRedirects: 4,
...overrides,
};
return { deps, calls };
}
const BASE_PARAMS = {
serverName: "test-server",
entry: ENTRY,
url: JAR_URL,
destPath: "plugins/Test.jar",
};
function strayApplyTempFiles() {
return fs.readdirSync(os.tmpdir()).filter((f) => f.startsWith("adpanel-apply-"));
}
function extractUploadedFilePart(record) {
const contentType = String(record.headers["content-type"] || "");
const boundaryMatch = contentType.match(/boundary=(.+)$/);
assert.ok(boundaryMatch, "upload request must be multipart with a boundary");
const delimiter = Buffer.from(`--${boundaryMatch[1]}`);
const body = record.body;
const parts = [];
let at = body.indexOf(delimiter);
while (at !== -1) {
const start = at + delimiter.length + 2; // skip CRLF
let next = body.indexOf(delimiter, start);
if (next === -1) break;
const headerEnd = body.indexOf("\r\n\r\n", start);
if (headerEnd !== -1 && headerEnd < next) {
parts.push({ headers: body.slice(start, headerEnd).toString(), data: body.slice(headerEnd + 4, next - 2) });
}
at = next;
}
return parts;
}
test("proxy mode streams the artifact to disk and relays the full body from the temp file", async () => {
const sink = await startUploadSink();
const straysBefore = strayApplyTempFiles();
try {
// 768 KiB payload in 64 KiB chunks: multi-write, multi-chunk, and safely
// under the 1 MiB remoteApplyMaxBytes cap the oversized-download test
// exercises separately.
const payload = Buffer.alloc(768 * 1024);
for (let i = 0; i < payload.length; i++) payload[i] = i & 0xff;
const { deps, calls } = makeProxyDeps(sink);
const pending = applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
// Feed the fake download stream after the util is parked on it.
await delay(10);
const CHUNK = 64 * 1024;
for (let at = 0; at < payload.length; at += CHUNK) {
calls._source.write(payload.subarray(at, Math.min(at + CHUNK, payload.length)));
}
calls._source.end();
const result = await pending;
assert.strictEqual(result.ok, true);
assert.strictEqual(result.msg, "downloaded-and-uploaded");
assert.strictEqual(result.destPath, "plugins/Test.jar");
// The streaming getter received the apply cap, not the small default.
assert.strictEqual(calls.streams.length, 1);
assert.strictEqual(calls.streams[0].url, JAR_URL);
assert.strictEqual(calls.streams[0].opts.maxBytes, 1024 * 1024);
// Exactly one relayed upload, carrying the store scope and the byte-exact
// artifact read back from the temp file.
assert.strictEqual(sink.requests.length, 1);
const record = sink.requests[0];
const parts = extractUploadedFilePart(record);
const dirPart = parts.find((p) => p.headers.includes('name="dir"'));
const serverPart = parts.find((p) => p.headers.includes('name="server"'));
const filePart = parts.find((p) => p.headers.includes('name="file"'));
assert.strictEqual(dirPart.data.toString(), `${BASE_DIR}/plugins`);
assert.strictEqual(serverPart.data.toString(), "test-server");
assert.ok(filePart.headers.includes('filename="Test.jar"'));
assert.ok(filePart.data.equals(payload), "relayed bytes must equal the downloaded artifact exactly");
} finally {
await sink.close();
assert.deepStrictEqual(strayApplyTempFiles(), straysBefore, "the temp artifact file must be removed after the apply");
}
});
test("proxy mode aborts an oversized download before any upload", async () => {
const sink = await startUploadSink();
const straysBefore = strayApplyTempFiles();
try {
const { deps, calls } = makeProxyDeps(sink);
const pending = applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
await delay(10);
// 1.25 MiB against a 1 MiB cap: the util's counting Transform must abort
// even though the (faked) getter does not enforce maxBytes itself.
const chunk = Buffer.alloc(64 * 1024, 0x41);
for (let i = 0; i < 20; i++) calls._source.write(chunk);
calls._source.end();
const result = await pending;
assert.strictEqual(result.ok, false);
assert.strictEqual(result.statusCode, 400);
assert.strictEqual(result.error, "remote-download-failed");
assert.strictEqual(sink.requests.length, 0, "nothing may be relayed from an aborted download");
} finally {
await sink.close();
assert.deepStrictEqual(strayApplyTempFiles(), straysBefore, "the aborted temp file must be cleaned up");
}
});
test("proxy mode fails 400 when the download stream errors mid-flight", async () => {
const sink = await startUploadSink();
const straysBefore = strayApplyTempFiles();
try {
const { deps, calls } = makeProxyDeps(sink);
const pending = applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
await delay(10);
calls._source.write(Buffer.alloc(128 * 1024, 0x42));
calls._source.destroy(new Error("connection reset mid-download"));
const result = await pending;
assert.strictEqual(result.ok, false);
assert.strictEqual(result.statusCode, 400);
assert.strictEqual(result.error, "remote-download-failed");
assert.strictEqual(sink.requests.length, 0, "a partial download must never be relayed");
} finally {
await sink.close();
assert.deepStrictEqual(strayApplyTempFiles(), straysBefore, "the partial temp file must be cleaned up");
}
});
test("real remote getter deadline removes partial artifacts and frees the apply slot", async () => {
const sink = await startUploadSink();
const straysBefore = strayApplyTempFiles();
const gate = createDownloadGate(1, 100);
const upstream = new PassThrough();
Object.assign(upstream, { statusCode: 200, headers: {} });
const request = new EventEmitter();
Object.assign(request, { destroyed: false, end() {}, destroy() { this.destroyed = true; } });
let respond;
let deadline;
let cleared = false;
const transport = { request: (opts, callback) => { respond = callback; return request; } };
const getter = createRemoteHttpGetters({
http: transport, https: transport, maxBytes: 1024, timeoutMs: 20, maxRedirects: 3,
now: () => 0,
setTimeout: (callback) => { deadline = callback; return callback; },
clearTimeout: () => { cleared = true; },
assertSafeRemoteUrlWithResolvedIp: async (url) => ({ url: new URL(url), resolvedIp: "8.8.8.8", originalHostname: "download.test" }),
createSsrfSafeAgent: () => undefined, tlsServernameForHost: (host) => host,
}).ssrfPipedHttpGet;
const { deps } = makeProxyDeps(sink, { httpGetStream: getter, remoteApplyDownloadGate: gate });
try {
const pending = applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
await new Promise((resolve) => setImmediate(resolve));
respond(upstream);
await new Promise((resolve) => setImmediate(resolve));
upstream.write("partial download bytes");
await new Promise((resolve) => setImmediate(resolve));
deadline();
const result = await pending;
assert.strictEqual(result.error, "remote-download-failed");
assert.strictEqual(result.statusCode, 400);
assert.strictEqual(upstream.destroyed, true);
assert.strictEqual(request.destroyed, true);
assert.strictEqual(cleared, true);
assert.strictEqual(sink.requests.length, 0, "an incomplete artifact must never reach the node");
assert.deepStrictEqual(strayApplyTempFiles(), straysBefore);
await gate.acquire();
gate.release();
} finally {
upstream.destroy();
await sink.close();
}
});
test("proxy mode answers 503 apply-download-busy when the download gate is saturated", async () => {
const sink = await startUploadSink();
try {
// limit 0 = permanently saturated; waitMs 25 keeps the test fast while
// proving the queue-budget path (not an immediate synchronous reject).
const gate = createDownloadGate(0, 25);
const { deps } = makeProxyDeps(sink, { remoteApplyDownloadGate: gate });
const result = await applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
assert.strictEqual(result.ok, false);
assert.strictEqual(result.statusCode, 503);
assert.strictEqual(result.error, "apply-download-busy");
assert.strictEqual(sink.requests.length, 0);
} finally {
await sink.close();
}
});
test("proxy mode releases its gate slot after the apply completes", async () => {
const sink = await startUploadSink();
try {
const gate = createDownloadGate(1, 500);
const { deps, calls } = makeProxyDeps(sink, { remoteApplyDownloadGate: gate });
const payload = Buffer.alloc(64 * 1024, 0x43);
const pending = applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
await delay(10);
calls._source.write(payload);
calls._source.end();
const first = await pending;
assert.strictEqual(first.ok, true);
// The slot must be free again: a fresh acquire through the same gate
// succeeds immediately (a leaked count would park this acquire for the
// 500 ms queue budget and fail the run).
const second = applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
await delay(10);
calls._source.write(payload);
calls._source.end();
const result = await second;
assert.strictEqual(result.ok, true, "the gate slot must be reusable after the first apply released it");
} finally {
await sink.close();
}
});
test("download gate hands off a freed slot to the waiting apply without double-counting", async () => {
const gate = createDownloadGate(1, 500);
await gate.acquire();
let granted = false;
const parked = gate.acquire().then(() => {
granted = true;
});
await delay(20);
assert.strictEqual(granted, false, "a saturated gate must not grant the waiter before a release");
gate.release();
const handOffDeadline = delay(400);
await Promise.race([parked, handOffDeadline.then(() => {
throw new Error("the parked waiter was not handed the freed slot within the queue budget");
})]);
assert.ok(granted);
// Slot transfer must keep the count exact: exactly one more release frees
// the gate, and the next acquire is immediate.
gate.release();
await Promise.race([gate.acquire(), delay(50).then(() => {
throw new Error("gate leaked a slot: an immediate acquire parked");
})]);
gate.release();
});
test("download gate rejects an expired waiter and keeps the accounting intact", async () => {
const gate = createDownloadGate(1, 30);
await gate.acquire();
await assert.rejects(
() => gate.acquire(),
(err) => err && err.code === "apply-download-busy"
);
// A timed-out waiter must not free a phantom slot: while the original holder
// still owns the gate, the next waiter must park to its own budget and time
// out (a timeout path that wrongly decremented `active` would grant this
// acquire immediately and fail the assert.rejects below).
await assert.rejects(
() => gate.acquire(),
(err) => err && err.code === "apply-download-busy"
);
// And after exactly one release the slot is free: an immediate acquire must
// succeed (a timeout path that phantom-DECREMENTED twice, or a release that
// no-oped, fails this).
gate.release();
await Promise.race([gate.acquire(), delay(50).then(() => {
throw new Error("gate accounting broken after a waiter timeout: an immediate acquire parked");
})]);
gate.release();
});