Files
Kelx/tests/server-suspension-rest-bridge.test.js
T
2026-11-30 16:32:37 +00:00

1028 lines
43 KiB
JavaScript

"use strict";
// Regression tests for the REST node-bridge suspension gap.
//
// The socket path in index.js refuses every interaction with a suspended
// server (join, action, command, readFile/writeFile/deleteFile,
// resources:subscribe) — but the REST bridge in nodes.js checked only
// checkServerAccess + checkUserPerm. The panel's own client prefers the HTTP
// endpoints in remote mode (power actions POST /api/nodes/server/:name/action
// first, console commands use the HTTP fallback whenever the socket is down,
// remote file editing uses the file routes exclusively), so suspension was
// silently unenforced on every non-socket interaction: a user with a live
// session could keep starting/stopping/killing a suspended server, sending
// console commands and writing/deleting its files.
//
// The fix mirrors the socket policy onto the REST bridge: every server-scoped
// route and every performPanel* performer (also used by the index.js AI tools
// and the /api/nodes/:id/server/* variants) answers 423 { code:
// "server-suspended" } with NO admin exemption — same as the socket handlers
// (unsuspend first). ORDER PARITY NOTE (adpanel:fs-perms-before-suspension):
// the fine-grained-fs-perm file routes now answer the perm denial (403)
// BEFORE the suspension body (423), matching the panel fs routes — see
// tests/relay-perms-before-suspension.test.js; the non-fs routes (power
// action, console, logs, EULA) keep the historical gate-before-perm order.
// The stub below grants every fs perm, so the 423 matrix here holds under
// either order for the fs routes.
//
// These tests boot the real nodes.js express app against a stubbed db module
// (injected through Module._load — nodes.js cannot be exercised through
// index.js, which boots servers on require) and drive the actual HTTP
// surface. A local fake node answers every daemon call with an instant 404 so
// the control cases prove the suspension gate — not node reachability — is
// what produces the refusals. index.js's two same-class paths (store version
// apply, reinstall) are locked with source-order assertions because index.js
// cannot be loaded in-process (same technique as server-op-guard /
// reinstall-route-protection).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const http = require("node:http");
const { once } = require("node:events");
const Module = require("node:module");
const express = require("express");
const session = require("express-session");
process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1"; // fake node runs on loopback
const ROOT = path.join(__dirname, "..");
const NODES_JS = path.join(ROOT, "nodes.js");
const INDEX_JS = path.join(ROOT, "index.js");
// ---------------------------------------------------------------------------
// Fake node daemon: every endpoint answers 404 { ok: false } instantly, so
// calls that pass the suspension gate fail fast and deterministically.
// The /v1/fs/download endpoint (panel download proxy upstream) has modes for
// the download-relay tests: "error404" (default), "ok" (streams a known body
// with forwarding headers) and "destroy-mid-body" (cuts the socket mid-body).
// ---------------------------------------------------------------------------
const DOWNLOAD_BODY = Buffer.alloc(16 * 1024, 0x41); // 16 KiB of 'A'
const DOWNLOAD_PROMISED_LENGTH = DOWNLOAD_BODY.length * 4; // more than is ever sent
let downloadMode = "error404";
// Last JSON body the relay forwarded to POST /v1/fs/uploadUrl, captured for
// the upload-url live-relay control test below.
let lastUploadUrlBody = null;
const uploadMethods = [];
let protectedUploadStatus = 409;
let extractRequests = null;
let lastStartBody = null;
let lastEulaBody = null;
let eulaRequests = [];
let eulaResult = null;
let startRequestCount = 0;
let dropNextStartReply = false;
let logResponse = null;
const fakeNode = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/v1/servers/Alpha/logs?tail=0") {
logResponse = res;
res.setHeader("Content-Type", "text/event-stream");
res.write("event: hello\ndata: {}\n\n");
return;
}
if (["POST", "PUT"].includes(req.method) && req.url === "/v1/servers/Alpha/eula-accept") {
let raw = "";
req.on("data", (chunk) => { raw += chunk; });
req.on("end", () => {
lastEulaBody = JSON.parse(raw);
eulaRequests.push({ method: req.method, body: lastEulaBody });
res.setHeader("Content-Type", "application/json");
res.statusCode = eulaResult?.status || 200;
res.end(JSON.stringify(eulaResult?.body || { ok: true, accepted: true, starting: lastEulaBody.autostart !== false }));
});
return;
}
if (req.url === "/v1/fs/extract" && extractRequests) {
extractRequests.push(req.method);
req.resume();
res.statusCode = req.method === "PUT" ? 404 : 200;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(req.method === "PUT" ? { error: "not found" } : { ok: true }));
return;
}
if (["POST", "PUT"].includes(req.method) && ["/v1/fs/upload", "/v1/fs/uploadUrl"].includes(req.url)) {
uploadMethods.push(req.method);
if (req.method === "PUT" || req.url === "/v1/fs/upload") {
req.resume();
req.on("end", () => {
const protectedUpload = req.method === "PUT";
res.statusCode = protectedUpload ? protectedUploadStatus : 200;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(protectedUpload
? { error: protectedUploadStatus === 409 ? "destination_exists" : "not_found" }
: { ok: true }));
});
return;
}
}
if (req.method === "POST" && req.url === "/v1/fs/download") {
req.resume(); // drain the proxy's JSON request body
if (downloadMode === "ok") {
res.statusCode = 200;
// Deliberately hostile (adpanel:download-headers-pinning): a compromised
// node declaring text/html inline. The relay must pin octet-stream +
// attachment and derive the filename from the requested path, never
// from these node-supplied headers.
res.setHeader("Content-Type", "text/html");
res.setHeader("Content-Disposition", 'inline; filename="<script>alert(1)</script>.html"');
res.setHeader("Content-Length", String(DOWNLOAD_BODY.length));
res.end(DOWNLOAD_BODY);
return;
}
if (downloadMode === "destroy-mid-body") {
res.statusCode = 200;
res.setHeader("Content-Type", "application/zip");
res.setHeader("Content-Disposition", 'attachment; filename="world.zip"');
res.setHeader("Content-Length", String(DOWNLOAD_PROMISED_LENGTH));
res.write(DOWNLOAD_BODY);
// Let the first chunk flush to the panel and be forwarded, then cut the
// connection mid-body: the proxy must close the client response cleanly
// instead of hanging or appending JSON to the binary stream.
setTimeout(() => {
try { res.socket.destroy(); } catch { }
}, 150);
return;
}
}
if (req.method === "POST" && req.url === "/v1/fs/uploadUrl") {
// Capture the relay's forwarded body so the live-relay control test can
// pin the forwarded contract. The body is drained before answering so the
// capture is deterministic; the response stays the standard 404, so the
// relay-side behavior under test is unchanged.
let raw = "";
req.on("data", (c) => { raw += c; });
req.on("end", () => {
try { lastUploadUrlBody = JSON.parse(raw); } catch { lastUploadUrlBody = null; }
res.statusCode = 404;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ ok: false, error: "not_found" }));
});
return;
}
if (req.method === "POST" && /^\/v1\/servers\/[^/]+\/start\?wait=false$/.test(req.url)) {
let raw = "";
req.on("data", (chunk) => { raw += chunk; });
req.on("end", () => {
lastStartBody = JSON.parse(raw);
startRequestCount += 1;
if (dropNextStartReply) {
dropNextStartReply = false;
res.destroy();
return;
}
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ ok: true }));
});
return;
}
res.statusCode = 404;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ ok: false, error: "not_found" }));
});
let fakeNodePort = 0;
// ---------------------------------------------------------------------------
// db stub
// ---------------------------------------------------------------------------
let NODE_ROW = null;
function nodeRow() {
return {
id: 1,
uuid: "node-uuid-1",
name: "node-one",
address: "127.0.0.1",
ram_mb: 8192,
disk_gb: 100,
ports: JSON.stringify({ mode: "range", start: 25565, count: 10 }),
token_id: "tok-1",
token: "test-node-token",
token_status: "active",
created_at: Date.now(),
api_port: fakeNodePort,
sftp_port: 2022,
max_upload_mb: 10240,
port_ok: 1,
last_seen: Date.now(),
last_check: Date.now(),
online: 1,
build_config: null,
};
}
function makeServerRow(overrides = {}) {
return Object.assign(
{
id: 42,
name: "Alpha",
legacy_id: "alpha-legacy",
bot: "alpha-bot",
template: "minecraft",
start: "java -jar server.jar",
node_id: "node-uuid-1",
ip: null,
port: 25565,
status: "running",
suspended: 0,
suspended_at: null,
suspended_by: null,
runtime: null,
docker: null,
acl: JSON.stringify({ users: [] }),
resources: null,
},
overrides
);
}
const serversByName = new Map(); // lower(name|legacy_id|bot) -> row
function registerServer(row) {
for (const key of [row.name, row.legacy_id, row.bot]) {
if (key) serversByName.set(String(key).toLowerCase(), row);
}
}
registerServer(makeServerRow()); // Alpha — live server (control)
registerServer(
makeServerRow({
id: 43,
name: "Suspended",
legacy_id: "suspended-legacy",
bot: "suspended-bot",
suspended: 1,
suspended_at: 1760000000000,
suspended_by: "admin@example.com",
})
);
// Distinct legacy_id/bot aliases: the row-aware checkServerAccess probes the
// resolved row's identifiers, so a fixture that silently inherited Alpha's
// aliases would let the Hidden server's legacy/bot names pass the access stub.
registerServer(
makeServerRow({ id: 44, name: "Hidden", legacy_id: "hidden-legacy", bot: "hidden-bot", suspended: 1 })
); // suspended + NOT accessible to the test user
const dbStub = {
async query(sql, params = []) {
const normalized = String(sql).replace(/\s+/g, " ").trim();
if (/^SELECT \* FROM servers WHERE/i.test(normalized)) {
const needle = String(params[0] || "").toLowerCase();
const numericId = params[3];
for (const row of new Set(serversByName.values())) {
if (
String(row.name).toLowerCase() === needle ||
String(row.legacy_id || "").toLowerCase() === needle ||
String(row.bot || "").toLowerCase() === needle ||
(numericId != null && row.id === numericId)
) {
return [row];
}
}
return [];
}
if (/^SELECT \* FROM nodes WHERE/i.test(normalized)) return [nodeRow()];
return [];
},
pool: {
async execute() { return [[]]; },
async query() { return [[]]; },
},
};
// ---------------------------------------------------------------------------
// Load nodes.js with the stubbed db module
// ---------------------------------------------------------------------------
const nodesApp = (() => {
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;
}
})();
let ADMIN_MODE = false;
let FILES_WRITE = true;
let FILES_CREATE = true;
let SERVER_START = true;
let CONSOLE_READ = true;
let SERVER_ACCESS = true;
let SESSION_VERDICT = "alive";
nodesApp.setPermissionCheckers(
async () => ({
server_start: SERVER_START,
server_stop: true,
console_read: CONSOLE_READ,
console_write: true,
files_read: true,
files_write: FILES_WRITE,
files_create: FILES_CREATE,
files_delete: true,
files_rename: true,
files_archive: true,
files_upload: true,
backups_view: true,
backups_create: true,
backups_delete: true,
}),
async () => ADMIN_MODE,
async (_email, serverName) => {
// Mirror production semantics: the access list is a set of granted
// identifiers, and the row-aware checkServerAccess probes the resolved
// row's name, legacy_id AND bot. The test user has no grant for the
// Hidden server under ANY of its identifiers; everything else stays
// granted so unknown servers still reach their 404 (see the Ghost test).
const n = String(serverName).toLowerCase();
return SERVER_ACCESS && n !== "hidden" && n !== "hidden-legacy" && n !== "hidden-bot";
},
{
getLoggedInUser: async () => ({ email: TEST_EMAIL }),
checkSocketSessionLiveness: async () => ({ verdict: SESSION_VERDICT }),
withTimeout: (promise) => promise,
recheckIntervalMs: 20,
}
);
// The node-proxy upload route now enforces the same upload policy as POST
// /upload (extension list, filename sanitizer, session-bound action token,
// rate limiter), injected by index.js in production and fail-closed when
// missing. These tests target the SUSPENSION gate, so inject hooks that
// mirror the production semantics without making every matrix entry mint an
// HMAC token: UPLOAD_TOKEN_ACCEPT=false flips the verifier into the rejecting
// state to pin the gate itself (see the token-gate test below).
let UPLOAD_TOKEN_ACCEPT = true;
let UPLOAD_EXT_ALLOWED = true;
nodesApp.setUploadPolicyHooks({
fsReadRateLimiter: (req, res, next) => next(),
fsMutateRateLimiter: (req, res, next) => next(),
isUploadExtensionAllowed: () => UPLOAD_EXT_ALLOWED,
sanitizeUploadFilename: (name) => {
const raw = String(name ?? "").trim();
return raw ? raw : null;
},
requireActionTokenOr403: async (req, res) => {
if (UPLOAD_TOKEN_ACCEPT) return true;
res.status(403).json({ error: "invalid or missing action token", code: "ACTION_TOKEN_INVALID" });
return false;
},
uploadRateLimiter: (req, res, next) => next(),
// adpanel:backups-list-brake — index.js injects the ALWAYS-ON backups-list
// read brake through this same setter in production; these tests target the
// suspension gate, so the pass-through stub mirrors that injection without
// testing the brake here (the gate's fail-closed posture is pinned in
// tests/node-backups-list-brake.test.js).
backupsListRateLimiter: (req, res, next) => next(),
});
const TEST_EMAIL = "user@example.com";
const parent = express();
parent.use(session({ secret: "test-secret", resave: false, saveUninitialized: true }));
parent.use((req, res, next) => {
req.isAdmin = ADMIN_MODE;
if (req.session) req.session.user = TEST_EMAIL;
next();
});
parent.use(nodesApp);
let baseUrl = "";
let httpServer = null;
test.before(async () => {
await new Promise((resolve) => fakeNode.listen(0, "127.0.0.1", resolve));
fakeNodePort = fakeNode.address().port;
await new Promise((resolve) => {
httpServer = parent.listen(0, "127.0.0.1", resolve);
});
baseUrl = `http://127.0.0.1:${httpServer.address().port}`;
});
test.after(() => {
return new Promise((resolve) =>
httpServer.close(() => fakeNode.close(() => resolve()))
);
});
async function call(method, route, body, headers = {}) {
const res = await fetch(`${baseUrl}${route}`, {
method,
headers:
body === undefined
? headers
: { "Content-Type": "application/json", ...headers },
body: body === undefined ? undefined : JSON.stringify(body),
});
const json = await res.json().catch(() => null);
return { status: res.status, json, headers: res.headers };
}
function fakeReq() {
return {
session: { user: TEST_EMAIL },
headers: {},
ip: "127.0.0.1",
connection: { remoteAddress: "127.0.0.1" },
};
}
function assertSuspended(result, expectedServer) {
assert.strictEqual(result.status, 423);
assert.strictEqual(result.json && result.json.code, "server-suspended");
assert.strictEqual(result.json && result.json.error, "server suspended");
assert.strictEqual(result.json && result.json.server, expectedServer);
assert.ok(String(result.headers.get("cache-control") || "").includes("no-store"));
}
// ---------------------------------------------------------------------------
// Suspended server: every server-scoped REST route refuses with 423
// ---------------------------------------------------------------------------
const suspendedMatrix = [
["GET", "/api/nodes/server/Suspended/info", undefined],
["GET", "/api/nodes/server/Suspended/entries?path=/", undefined],
["GET", "/api/nodes/server/Suspended/file?path=server.properties", undefined],
["GET", "/api/nodes/server/Suspended/download?path=server.properties", undefined],
["GET", "/api/nodes/server/Suspended/logs", undefined],
["POST", "/api/nodes/server/Suspended/action", { cmd: "stop" }],
["POST", "/api/nodes/server/Suspended/command", { command: "say hi" }],
["POST", "/api/nodes/server/Suspended/file", { path: "a.txt", content: "hello" }],
["POST", "/api/nodes/server/Suspended/delete", { path: "a.txt" }],
["POST", "/api/nodes/server/Suspended/delete-batch", { items: [{ path: "a.txt" }] }],
["POST", "/api/nodes/server/Suspended/rename", { path: "a.txt", newName: "b.txt" }],
["POST", "/api/nodes/server/Suspended/extract", { path: "a.zip" }],
["POST", "/api/nodes/server/Suspended/archive", { paths: ["a.txt"], destDir: "" }],
["POST", "/api/nodes/server/Suspended/upload", undefined],
["POST", "/api/nodes/server/Suspended/upload-url", { url: "https://example.com/x.zip" }],
["POST", "/api/nodes/server/Suspended/create", { type: "file", name: "x.txt", path: "" }],
["POST", "/api/nodes/server/Suspended/eula/accept", {}],
["GET", "/api/nodes/server/Suspended/backups", undefined],
["POST", "/api/nodes/server/Suspended/backups", { name: "b1" }],
["POST", "/api/nodes/server/Suspended/backups/b1/restore", { deleteOldFiles: false }],
["DELETE", "/api/nodes/server/Suspended/backups/b1", undefined],
];
for (const [method, route, body] of suspendedMatrix) {
test(`suspended server refused over REST: ${method} ${route}`, async () => {
const result = await call(method, route, body);
assertSuspended(result, "Suspended");
});
}
// The :id URL variants share the performers, so they inherit the gate.
test("suspended server refused on /api/nodes/:id/server/action variant", async () => {
ADMIN_MODE = true; // this variant sits behind the /api/nodes admin gate
try {
const result = await call("POST", "/api/nodes/node-uuid-1/server/action", { name: "Suspended", cmd: "stop" });
assertSuspended(result, "Suspended");
const command = await call("POST", "/api/nodes/node-uuid-1/server/command", { name: "Suspended", command: "say hi" });
assertSuspended(command, "Suspended");
} finally {
ADMIN_MODE = false;
}
});
// Admins are NOT exempt on the REST bridge — same as the socket handlers.
test("admin is not exempt from the suspension gate", async () => {
ADMIN_MODE = true;
try {
const result = await call("POST", "/api/nodes/server/Suspended/action", { cmd: "kill" });
assertSuspended(result, "Suspended");
} finally {
ADMIN_MODE = false;
}
});
// ---------------------------------------------------------------------------
// Ordering: access check first, suspension second, permissions third
// ---------------------------------------------------------------------------
test("suspension never leaks to callers without server access (403 before 423)", async () => {
const result = await call("GET", "/api/nodes/server/Hidden/file?path=server.properties");
assert.strictEqual(result.status, 403);
});
test("suspension fires before command validation (423 beats invalid_cmd)", async () => {
const result = await call("POST", "/api/nodes/server/Suspended/action", { cmd: "bogus" });
assertSuspended(result, "Suspended");
});
test("unknown server still answers 404, not 423", async () => {
const result = await call("POST", "/api/nodes/server/Ghost/delete", { path: "a.txt" });
assert.strictEqual(result.status, 404);
});
// ---------------------------------------------------------------------------
// Control: the same routes on a live server are NOT 423 — the guard, not the
// fake node's 404s, is what produces the refusals above.
// ---------------------------------------------------------------------------
const controlMatrix = [
["POST", "/api/nodes/server/Alpha/action", { cmd: "stop" }, 502], // node_action_failed
["POST", "/api/nodes/server/Alpha/command", { command: "say hi" }, 502], // node_command_failed
["GET", "/api/nodes/server/Alpha/file?path=server.properties", undefined, 502], // node_read_failed
["POST", "/api/nodes/server/Alpha/file", { path: "a.txt", content: "x" }, 502], // node_write_failed
["POST", "/api/nodes/server/Alpha/delete", { path: "a.txt" }, 502], // node_delete_failed
["GET", "/api/nodes/server/Alpha/backups", undefined, 502], // node_unreachable
["GET", "/api/nodes/server/Alpha/info", undefined, 200],
];
for (const [method, route, body, expected] of controlMatrix) {
test(`live server passes the suspension gate: ${method} ${route}`, async () => {
const result = await call(method, route, body);
assert.strictEqual(result.status, expected);
assert.notStrictEqual(result.json && result.json.code, "server-suspended");
});
}
test("live server upload passes the suspension gate (empty multipart -> no_file)", async () => {
const res = await fetch(`${baseUrl}/api/nodes/server/Alpha/upload`, {
method: "POST",
headers: { "Content-Type": "multipart/form-data; boundary=----adptest" },
body: "------adptest--\r\n",
});
const json = await res.json().catch(() => null);
assert.strictEqual(res.status, 400);
assert.strictEqual(json && json.error, "no_file");
});
test("multipart setup failures answer without relaying an upload", async () => {
uploadMethods.length = 0;
const response = await fetch(`${baseUrl}/api/nodes/server/Alpha/upload`, {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
signal: AbortSignal.timeout(2000),
});
assert.strictEqual(response.status, 400);
assert.strictEqual((await response.json()).error, "bad_multipart");
assert.deepStrictEqual(uploadMethods, []);
});
test("create-only extraction fails closed without node support", async () => {
extractRequests = [];
FILES_WRITE = false;
try {
const extract = () => call("POST", "/api/nodes/server/Alpha/extract", { path: "fixture.zip" });
const restricted = await extract();
assert.strictEqual(restricted.status, 503);
assert.strictEqual(restricted.json.error, "node_extract_upgrade_required");
assert.deepStrictEqual(extractRequests, ["PUT"]);
FILES_WRITE = true;
assert.strictEqual((await extract()).status, 200);
assert.deepStrictEqual(extractRequests, ["PUT", "POST"]);
} finally {
extractRequests = null;
FILES_WRITE = true;
}
});
test("multipart relay permits replacement only with the edit grant or admin", async () => {
const upload = async () => {
const form = new FormData();
form.set("file", new Blob(["synthetic fixture content"]), "fixture.txt");
const response = await fetch(`${baseUrl}/api/nodes/server/Alpha/upload`, {
method: "POST", body: form, signal: AbortSignal.timeout(2000),
});
return { status: response.status, body: await response.json() };
};
uploadMethods.length = 0;
FILES_WRITE = false;
try {
const collision = await upload();
assert.strictEqual(collision.status, 409);
assert.strictEqual(collision.body.error, "destination_exists");
protectedUploadStatus = 404;
const oldNode = await upload();
assert.strictEqual(oldNode.status, 503);
assert.strictEqual(oldNode.body.error, "node_upload_upgrade_required");
ADMIN_MODE = true;
assert.strictEqual((await upload()).status, 200);
ADMIN_MODE = false;
FILES_WRITE = true;
assert.strictEqual((await upload()).status, 200);
assert.deepStrictEqual(uploadMethods, ["PUT", "PUT", "POST", "POST"]);
} finally {
protectedUploadStatus = 409;
FILES_WRITE = true;
ADMIN_MODE = false;
}
});
// The upload route requires the same session-bound action token as POST
// /upload, and that gate runs before the suspension check (same order as the
// panel-side route: token -> access -> suspension -> permission). A request
// without a usable token is refused with the canonical 403 shape no matter
// what server state it targets; a valid token still reaches the 423 gate
// (covered by the suspended matrix entry above, whose verifier accepts).
test("upload route refuses requests without a valid action token (403 before 423)", async () => {
UPLOAD_TOKEN_ACCEPT = false;
try {
const res = await fetch(`${baseUrl}/api/nodes/server/Suspended/upload`, {
method: "POST",
headers: { "Content-Type": "multipart/form-data; boundary=----adptest" },
body: "------adptest--\r\n",
});
const json = await res.json().catch(() => null);
assert.strictEqual(res.status, 403);
assert.strictEqual(json && json.error, "invalid or missing action token");
assert.strictEqual(json && json.code, "ACTION_TOKEN_INVALID");
} finally {
UPLOAD_TOKEN_ACCEPT = true;
}
});
// The URL uploader rides the same two gates as the direct upload relay. The
// panel's own POST /upload-url verifies "POST /upload" + {serverName} — the
// exact pair the node-proxy route checks — so a request without a usable
// token is refused with the canonical 403 shape before any server state is
// consulted (in particular before the 423 suspension gate, mirroring the
// panel-side order token -> access -> suspension -> permission).
test("upload-url route refuses requests without a valid action token (403 before 423)", async () => {
UPLOAD_TOKEN_ACCEPT = false;
try {
const result = await call("POST", "/api/nodes/server/Suspended/upload-url", { url: "https://example.com/x.zip" });
assert.strictEqual(result.status, 403);
assert.strictEqual(result.json && result.json.error, "invalid or missing action token");
assert.strictEqual(result.json && result.json.code, "ACTION_TOKEN_INVALID");
} finally {
UPLOAD_TOKEN_ACCEPT = true;
}
});
// Same extension policy as the panel's POST /upload-url: the filename derived
// from the URL's last path segment must pass the allow/block list, and the
// decision happens before any DNS or network work (same order as the panel
// route), so a blocked file type cannot be pulled in through the node proxy.
test("upload-url route enforces the URL-derived extension policy (400 before any relay work)", async () => {
UPLOAD_EXT_ALLOWED = false;
try {
const result = await call("POST", "/api/nodes/server/Alpha/upload-url", { url: "https://example.com/pack.exe" });
assert.strictEqual(result.status, 400);
assert.strictEqual(result.json && result.json.error, "file-type-not-allowed");
} finally {
UPLOAD_EXT_ALLOWED = true;
}
});
// Control: with the policy satisfied, a live server reaches the relay — the
// fake node's 404 surfaces as 502 node_upload_url_failed. The URL host is a
// PUBLIC literal IP (a long-standing example.com A record), so the SSRF
// pre-flight never does DNS and nothing is ever fetched: the URL is validated,
// not requested, and the fake node intercepts the relay before any daemon-side
// fetch could exist. It must NOT be an RFC 5737 TEST-NET address
// (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24): those are deliberately
// rejected as private/reserved by the shared SSRF validator
// (utils/remote-url-guard.js) the relay now runs — an earlier version of this
// test leaned on the relay's old weak local validator accepting TEST-NET-1,
// which is exactly the gap that was closed.
test("live server upload-url passes the token and policy gates (relay 502 from fake node)", async () => {
lastUploadUrlBody = null;
const result = await call("POST", "/api/nodes/server/Alpha/upload-url", { url: "http://93.184.216.34/pack.zip" });
assert.strictEqual(result.status, 502);
assert.strictEqual(result.json && result.json.error, "node_upload_url_failed");
// The relay forwards the policy-approved name — the sanitized URL-derived
// filename, post "download.bin" fallback, post extension approval —
// alongside the existing fields, so the daemon stores the spelling the
// policy saw instead of trusting the remote server's Content-Disposition.
assert.ok(lastUploadUrlBody && typeof lastUploadUrlBody === "object", "fake node captured the forwarded uploadUrl body");
assert.deepStrictEqual(Object.keys(lastUploadUrlBody).sort(), ["dir", "filename", "server", "url"]);
assert.strictEqual(lastUploadUrlBody.url, "http://93.184.216.34/pack.zip");
assert.strictEqual(lastUploadUrlBody.server, "Alpha");
assert.strictEqual(lastUploadUrlBody.filename, "pack.zip");
assert.strictEqual(typeof lastUploadUrlBody.dir, "string");
assert.ok(lastUploadUrlBody.dir.length > 0);
});
test("URL relay applies the same protected destination policy", async () => {
uploadMethods.length = 0;
FILES_WRITE = false;
try {
const result = await call("POST", "/api/nodes/server/Alpha/upload-url", { url: "http://93.184.216.34/fixture.txt" });
assert.strictEqual(result.status, 409);
assert.strictEqual(result.json.error, "destination_exists");
assert.deepStrictEqual(uploadMethods, ["PUT"]);
} finally {
FILES_WRITE = true;
}
});
// ---------------------------------------------------------------------------
// Performers: the index.js AI tools and any future caller inherit the gate
// ---------------------------------------------------------------------------
test("performers refuse suspended servers with the 423 result shape", async () => {
const results = await Promise.all([
nodesApp.performPanelServerAction(fakeReq(), "Suspended", "stop"),
nodesApp.performPanelConsoleCommand(fakeReq(), "Suspended", "say hi"),
nodesApp.performPanelListBackups(fakeReq(), "Suspended"),
nodesApp.performPanelCreateBackup(fakeReq(), "Suspended", "b1", ""),
nodesApp.performPanelRestoreBackup(fakeReq(), "Suspended", "b1", false),
nodesApp.performPanelDeleteBackup(fakeReq(), "Suspended", "b1"),
nodesApp.performPanelEulaAccept(fakeReq(), "Suspended"),
]);
for (const result of results) {
assert.strictEqual(result.status, 423);
assert.strictEqual(result.body && result.body.code, "server-suspended");
}
});
test("performers still work for live servers (502 from the fake node's 404s)", async () => {
const results = await Promise.all([
nodesApp.performPanelServerAction(fakeReq(), "Alpha", "stop"),
nodesApp.performPanelConsoleCommand(fakeReq(), "Alpha", "say hi"),
nodesApp.performPanelListBackups(fakeReq(), "Alpha"),
]);
for (const result of results) {
assert.strictEqual(result.status, 502);
}
});
test("power relay waits for the reinstall claim and uses the published port afterwards", async () => {
const entry = serversByName.get("alpha");
const { status, port } = entry;
lastStartBody = null;
try {
entry.status = "reinstalling";
for (const cmd of ["start", "stop", "restart", "kill"]) {
const result = await nodesApp.performPanelServerAction(fakeReq(), "Alpha", cmd);
assert.equal(result.status, 409);
assert.equal(result.body.code, "reinstall_in_progress");
}
assert.equal(lastStartBody, null);
entry.port = 25566;
entry.status = "stopped";
const result = await nodesApp.performPanelServerAction(fakeReq(), "Alpha", "start");
assert.equal(result.status, 200);
assert.deepEqual(lastStartBody, { hostPort: 25566 });
} finally {
Object.assign(entry, { status, port });
}
});
test("power relay reports a lost start reply without sending another start", async () => {
const priorRequests = startRequestCount;
dropNextStartReply = true;
try {
const result = await nodesApp.performPanelServerAction(fakeReq(), "Alpha", "start");
assert.equal(startRequestCount - priorRequests, 1);
assert.equal(result.status, 502);
assert.equal(result.body.error, "server_action_result_unconfirmed");
assert.match(result.body.detail, /check the server state before retrying/i);
} finally {
dropNextStartReply = false;
}
});
test("EULA acceptance never starts a server; power authorization stays on the power relay", async () => {
const priorRequests = startRequestCount;
SERVER_START = false;
try {
const result = await call("POST", "/api/nodes/server/Alpha/eula/accept", {});
assert.equal(result.status, 200);
assert.deepEqual(result.json, { ok: true, accepted: true, starting: false });
assert.deepEqual(lastEulaBody, { autostart: false });
const denied = await call("POST", "/api/nodes/server/Alpha/action", { cmd: "run" });
assert.equal(denied.status, 403);
assert.equal(denied.json.permission, "server_start");
assert.equal(startRequestCount, priorRequests);
} finally {
SERVER_START = true;
}
});
test("restricted EULA consent uses the node's no-clobber or edit-only mode without legacy fallback", async () => {
for (const scenario of [
{ create: true, write: false, mode: "create", status: 409, error: "eula_file_exists", denied: "files_write" },
{ create: false, write: true, mode: "update", status: 404, error: "eula_file_missing", denied: "files_create" },
{ create: true, write: false, mode: "create", status: 404, error: "not found" },
]) {
eulaRequests = [];
FILES_CREATE = scenario.create;
FILES_WRITE = scenario.write;
eulaResult = { status: scenario.status, body: { ok: false, error: scenario.error } };
try {
const result = await call("POST", "/api/nodes/server/Alpha/eula/accept", {});
assert.equal(result.status, scenario.denied ? 403 : 502);
assert.equal(result.json.permission, scenario.denied);
assert.deepEqual(eulaRequests, [{ method: "PUT", body: { autostart: false, mode: scenario.mode } }]);
} finally {
FILES_CREATE = true;
FILES_WRITE = true;
eulaResult = null;
}
}
});
test("open Console streams close on permission, access, session or suspension changes", async () => {
const server = serversByName.get("alpha");
const initialSuspended = server.suspended;
for (const revoke of [
() => { CONSOLE_READ = false; },
() => { SERVER_ACCESS = false; },
() => { SESSION_VERDICT = "dead"; },
() => { SESSION_VERDICT = "unknown"; },
() => { server.suspended = 1; },
]) {
logResponse = null;
const signal = AbortSignal.timeout(2000);
try {
const response = await fetch(`${baseUrl}/api/nodes/server/Alpha/logs?tail=0`, { signal });
assert.equal(response.status, 200);
const reader = response.body.getReader();
assert.match(Buffer.from((await reader.read()).value).toString(), /event: hello/);
const upstreamClosed = once(logResponse, "close", { signal });
revoke();
await assert.rejects(reader.read(), { message: "terminated" });
await upstreamClosed;
} finally {
logResponse?.destroy();
CONSOLE_READ = true;
SERVER_ACCESS = true;
SESSION_VERDICT = "alive";
server.suspended = initialSuspended;
}
}
});
// GET eula stays intentionally open (read-only, single bit: does eula.txt
// already accept the Minecraft EULA) — pinned so a future guard is a
// decision, not an accident.
test("GET eula status remains readable on a suspended server", async () => {
const result = await call("GET", "/api/nodes/server/Suspended/eula");
assert.strictEqual(result.status, 502); // node 404, not suspension-gated
});
// ---------------------------------------------------------------------------
// index.js same-class paths (store version apply, reinstall): source-order
// assertions — index.js boots servers on require and cannot load in-process.
// ---------------------------------------------------------------------------
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
function sliceBetween(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
test("index.js: store version apply refuses suspended servers", () => {
const block = sliceBetween(
indexSource,
'app.post("/api/servers/:bot/versions/apply"',
'app.post("/api/servers/create"'
);
assert.ok(block.includes("isServerSuspended(entry)) return sendSuspendedServerJson(res, entry);"));
});
test("index.js: reinstall refuses suspended servers", () => {
const block = sliceBetween(
indexSource,
'app.post("/api/servers/:name/reinstall"',
'app.patch("/api/settings/servers/:name/resources"'
);
assert.ok(block.includes("isServerSuspended(entry)) return sendSuspendedServerJson(res, entry);"));
});
// ---------------------------------------------------------------------------
// Download proxy relay (GET /api/nodes/server/:name/download): the panel must
// forward the node daemon's bytes byte-exactly, PIN the response headers
// (adpanel:download-headers-pinning — node-supplied Content-Type /
// Content-Disposition are never trusted: a malicious node declaring text/html
// inline would execute HTML on the panel origin), and close cleanly — no hang,
// no appended JSON, no crash — when the node dies mid-body.
// These tests run after every test that relies on the pass-through upload
// limiter below (the last one flips that hook off), and each restores
// downloadMode in a finally.
// ---------------------------------------------------------------------------
test("download proxy pins octet-stream/attachment and forwards the node body byte-exactly", async () => {
downloadMode = "ok";
try {
const res = await fetch(`${baseUrl}/api/nodes/server/Alpha/download?path=world.zip`);
assert.strictEqual(res.status, 200);
// The fake node declares text/html + inline (see downloadMode "ok"): both
// must be ignored — the type pinned, the name derived from the requested
// path (basename of world.zip), not from the node's headers.
assert.strictEqual(res.headers.get("content-type"), "application/octet-stream");
assert.strictEqual(res.headers.get("content-disposition"), 'attachment; filename="world.zip"');
assert.strictEqual(res.headers.get("content-length"), String(DOWNLOAD_BODY.length));
const body = Buffer.from(await res.arrayBuffer());
assert.strictEqual(body.length, DOWNLOAD_BODY.length, "the full body must arrive");
assert.strictEqual(body.compare(DOWNLOAD_BODY), 0, "the body must be byte-exact");
} finally {
downloadMode = "error404";
}
});
test("download proxy maps a non-200 node answer to its JSON error (control)", async () => {
downloadMode = "error404";
const result = await call("GET", "/api/nodes/server/Alpha/download?path=world.zip");
assert.strictEqual(result.status, 404);
assert.strictEqual(result.json && result.json.error, "download failed");
});
test("download proxy closes cleanly when the node dies mid-body (no JSON appended, no crash)", async () => {
downloadMode = "destroy-mid-body";
try {
// The test process surviving this test IS the no-crash assertion: an
// unhandled proxyRes/proxyReq 'error' would take down the whole run.
const res = await fetch(`${baseUrl}/api/nodes/server/Alpha/download?path=world.zip`, {
signal: AbortSignal.timeout(5000),
});
assert.strictEqual(res.status, 200, "the forwarded 200 headers must already be out before the abort");
const reader = res.body.getReader();
const chunks = [];
let terminated = null;
try {
for (;;) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
}
} catch (err) {
terminated = err;
assert.notStrictEqual(
err && err.name, "TimeoutError",
"the panel must close the response after the upstream abort, not hang"
);
}
const received = Buffer.concat(chunks).toString("latin1");
assert.match(
received, /^A*$/,
`only upstream body bytes may reach the client; got: ${JSON.stringify(received.slice(0, 120))}`
);
assert.ok(
terminated !== null || received.length < DOWNLOAD_PROMISED_LENGTH,
"the response must end before the body length the node promised"
);
} finally {
downloadMode = "error404";
}
});
// ---------------------------------------------------------------------------
// Fail-closed posture for the injected upload-policy hooks: with the rate
// limiter hook missing (exactly the state a fresh nodes.js module starts in,
// before index.js injects its implementations), the upload relay must answer
// with the limiter's own 429 shape instead of proceeding unthrottled.
// Declared last: it replaces the hooks and restores them in a finally.
// ---------------------------------------------------------------------------
test("upload relay fails closed with the limiter's 429 shape when the limiter hook is missing", async () => {
nodesApp.setUploadPolicyHooks({
isUploadExtensionAllowed: () => true,
sanitizeUploadFilename: (name) => String(name ?? "").trim() || null,
requireActionTokenOr403: async () => true,
// uploadRateLimiter deliberately omitted -> the hook is missing.
});
try {
const multipart = {
method: "POST",
headers: { "Content-Type": "multipart/form-data; boundary=----adptest" },
body: "------adptest--\r\n",
};
const live = await fetch(`${baseUrl}/api/nodes/server/Alpha/upload`, multipart);
const liveJson = await live.json().catch(() => null);
assert.strictEqual(live.status, 429);
assert.strictEqual(liveJson && liveJson.error, "Too many upload attempts, slow down.");
// The gate sits in front of every other check, so the 429 must fire even
// for a suspended server and without any action token.
const suspended = await fetch(`${baseUrl}/api/nodes/server/Suspended/upload`, multipart);
assert.strictEqual(suspended.status, 429);
} finally {
// Restore the production-shaped hooks (defensive: each test file runs in
// its own process, but nothing later in this file should see the gap).
nodesApp.setUploadPolicyHooks({
fsReadRateLimiter: (req, res, next) => next(),
fsMutateRateLimiter: (req, res, next) => next(),
isUploadExtensionAllowed: () => UPLOAD_EXT_ALLOWED,
sanitizeUploadFilename: (name) => {
const raw = String(name ?? "").trim();
return raw ? raw : null;
},
requireActionTokenOr403: async (req, res) => {
if (UPLOAD_TOKEN_ACCEPT) return true;
res.status(403).json({ error: "invalid or missing action token", code: "ACTION_TOKEN_INVALID" });
return false;
},
uploadRateLimiter: (req, res, next) => next(),
// Restore the production shape including the backups-list brake stub
// (adpanel:backups-list-brake) so nothing later in this file sees a
// fail-closed gap on GET /api/nodes/server/:name/backups.
backupsListRateLimiter: (req, res, next) => next(),
});
}
});