Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+833
View File
@@ -0,0 +1,833 @@
"use strict";
// Tests for the self-defending admin check on the node-fleet CRUD handlers.
//
// The audit finding (follow-up to the backup-relay token gates): every node-
// fleet handler carried the internal requireNodeAdmin belt-and-suspenders EXCEPT
// the four most destructive ones — POST /api/nodes (createNodeHandler),
// PATCH /api/nodes/:id (updateNodeHandler), DELETE /api/nodes/:id (inline) and
// POST /api/nodes/:id/build (updateNodeBuildHandler). They relied solely on the
// module-level admin middleware — the exact single-layer posture this file's own
// convention (see requireNodeAdmin's doc comment) exists to eliminate, because
// that gate was bypassed once via case-variant URLs (utils/node-api-path.js).
// The sibling handlers — even read-only ones — already self-check; deleting a
// node (its daemon bearer credential with it) must not be easier to regress.
//
// The fix adds the same first-line `if (!(await requireNodeAdmin(req, res)))
// return;` to all four, placed inside the named handlers (matching
// nodeProxyCreateHandler) so any future caller inherits it. Zero behavior
// change for admins; fail-closed for everyone else.
//
// Deliberately NOT covered here (each has its own, non-admin auth layer):
// GET /api/nodes/:id/config.yml — daemon-credential auth (X-Node-Bootstrap or
// the node's own bearer token), never session-based by design;
// POST /api/nodes/:id/heartbeat — daemon-authenticated, exempted from the
// admin gate;
// POST /api/nodes/:id/server/{action,command} — per-server aliases whose
// performers enforce per-user access themselves; a middleware regression
// grants nothing the /api/nodes/server/:name twins don't already grant.
//
// This file locks in:
// 1. requireNodeAdmin's own logic (exported for this purpose): fast path for
// req.isAdmin, injected-checker fallback, FAIL-CLOSED when the checker
// throws, canonical 403 { error: "admin required" }.
// 2. Source wiring: all four handlers begin with the self-check, the seven
// pre-existing call sites are untouched (exact-count tripwire), and the
// documented exclusions keep their own auth.
// 3. Live behavior (real nodes.js app, db-stub technique): non-admin requests
// to all four routes are refused by the outer middleware with the same
// 403 shape, and admin requests pass the gate into the handler logic —
// proving the added checks change nothing for admins.
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 Module = require("node:module");
const express = require("express");
const ROOT = path.join(__dirname, "..");
const NODES_JS = path.join(ROOT, "nodes.js");
const nodesSource = fs.readFileSync(NODES_JS, "utf8");
// ---------------------------------------------------------------------------
// 1. requireNodeAdmin's own logic — exported so the fail-closed fallback is
// executable here instead of pattern-matched.
// ---------------------------------------------------------------------------
process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1"; // fake node runs on loopback
process.env.SESSION_SECRET = "node-crud-test-fixture-session-secret";
let fakeNodeResponding = false;
let fakeNodeUnauthenticatedHealth = false;
let deferNodeInfo;
const fakeNode = http.createServer((req, res) => {
req.resume();
res.setHeader("Content-Type", "application/json");
if (fakeNodeResponding && req.url === "/v1/info") {
const reply = JSON.stringify({ ok: true, node: { uuid: NODE_ROW.uuid } });
if (deferNodeInfo) deferNodeInfo(() => res.end(reply));
else res.end(reply);
return;
}
if (fakeNodeUnauthenticatedHealth && req.url === "/health") {
res.end(JSON.stringify({ ok: true, uuid: NODE_ROW.uuid }));
return;
}
if (fakeNodeUnauthenticatedHealth && req.url === "/v1/info") {
res.statusCode = 401;
res.end(JSON.stringify({ ok: false, error: "unauthorized" }));
return;
}
res.statusCode = 404;
res.end(JSON.stringify({ ok: false, error: "not_found" }));
});
let fakeNodePort = 0;
let NODE_ROW = null;
let SERVER_ROWS = [];
let NODE_DELETES = [];
const OTHER_NODE = { id: 9, uuid: "node-uuid-9" };
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,
};
}
const dbStub = {
async query(sql, params = []) {
const normalized = String(sql).replace(/\s+/g, " ").trim();
if (/^SELECT \* FROM nodes WHERE/i.test(normalized)) return [NODE_ROW];
if (/^SELECT (id, name, display_name, legacy_id, node_id, ip, port,|1 FROM servers WHERE)/i.test(normalized)) {
const guardsExplicitAssignment = /AND NOT EXISTS \( SELECT 1 FROM nodes n WHERE \(n.id = servers.node_id OR n.uuid = servers.node_id\) AND n.id <> \? \)/.test(normalized);
const assignedTo = (row, [nodeId, uuid, name, address, excludedId]) => {
if (row.node_id === nodeId) return true;
const isLegacyMatch = row.node_id === uuid || String(row.node_id || "").toLowerCase() === name || row.ip === address;
const differentNode = guardsExplicitAssignment && OTHER_NODE.id !== excludedId && [OTHER_NODE.id, OTHER_NODE.uuid].includes(row.node_id);
return isLegacyMatch && !differentNode;
};
const [previousName, nextName, nodeId, nodeUuid] = params.slice(10);
return SERVER_ROWS.filter(row => {
const rowId = String(row.node_id || "").toLowerCase();
const losesName = rowId === previousName && rowId !== nextName && ![nodeId, nodeUuid].includes(row.node_id);
return assignedTo(row, params) && (params.length === 5 || !assignedTo(row, params.slice(5)) || losesName);
});
}
if (/^UPDATE nodes SET port_ok = \?, last_seen = NULLIF\(GREATEST\(COALESCE\(last_seen, 0\), \?\), 0\), last_check = \?, online = \?/i.test(normalized)) {
const [port_ok, last_seen, last_check, online] = params;
NODE_ROW = { ...NODE_ROW, port_ok, last_seen: Math.max(NODE_ROW.last_seen || 0, last_seen) || null, last_check, online };
}
if (/^UPDATE nodes SET uuid = \?, name = \?, address = \?/i.test(normalized)) {
NODE_ROW = {
...NODE_ROW, name: params[1], address: params[2], ports: params[5], api_port: params[10],
port_ok: params[12], last_seen: params[13], last_check: params[14], online: params[15], build_config: params[16],
};
}
if (/^DELETE FROM nodes WHERE/i.test(normalized)) NODE_DELETES.push({ sql: normalized, params });
return [];
},
pool: {
async execute() { return [[]]; },
async query() { return [[]]; },
},
};
const nodesApp = (() => {
const originalLoad = Module._load;
Module._load = function (request, parent, isMain) {
if (request === "./db" && parent && parent.filename === NODES_JS) return dbStub;
if (request === "dns" && parent?.filename === NODES_JS) {
return { promises: { Resolver: class {
setServers() {}
async resolve4() { return ["104.16.0.1"]; }
async resolve6() { return []; }
} } };
}
if (request === "https" && parent?.filename === NODES_JS) {
return { ...require("node:https"), get() { throw new Error("Use bundled ranges in the network-free fixture"); } };
}
return originalLoad.apply(this, arguments);
};
try {
return require(NODES_JS);
} finally {
Module._load = originalLoad;
}
})();
// The injected _isAdmin checker is module state — each scenario re-injects.
function injectIsAdmin(fn) {
nodesApp.setPermissionCheckers(async () => ({}), fn, async () => true);
}
function stubRes() {
const calls = { status: null, payload: null };
return {
res: {
status(c) { calls.status = c; return { json(p) { calls.payload = p; } }; },
},
calls,
};
}
test("requireNodeAdmin fast-paths req.isAdmin without consulting the checker", async () => {
injectIsAdmin(async () => { throw new Error("checker must not run for req.isAdmin"); });
const { res } = stubRes();
const ok = await nodesApp.requireNodeAdmin({ isAdmin: true }, res);
assert.equal(ok, true, "an attested admin passes even if the fallback checker would throw");
});
test("requireNodeAdmin refuses a non-admin through the injected checker (403 admin required)", async () => {
injectIsAdmin(async () => false);
const { res, calls } = stubRes();
const ok = await nodesApp.requireNodeAdmin({ isAdmin: false }, res);
assert.equal(ok, false);
assert.equal(calls.status, 403);
assert.equal(calls.payload && calls.payload.error, "admin required");
});
test("requireNodeAdmin's checker fallback can rescue a request whose req.isAdmin flag is missing", async () => {
injectIsAdmin(async () => true);
const { res } = stubRes();
const ok = await nodesApp.requireNodeAdmin({}, res); // no isAdmin flag at all
assert.equal(ok, true, "the fallback checker allowing must let the request through");
});
test("requireNodeAdmin fails CLOSED when the injected checker throws", async () => {
injectIsAdmin(async () => { throw new Error("db down"); });
const { res, calls } = stubRes();
const ok = await nodesApp.requireNodeAdmin({ isAdmin: false }, res);
assert.equal(ok, false, "a throwing checker must deny, never default-allow");
assert.equal(calls.status, 403);
assert.equal(calls.payload && calls.payload.error, "admin required");
});
// ---------------------------------------------------------------------------
// 2. Source wiring — the four handlers self-check, the prior sites remain, and
// the documented exclusions keep their own auth layers.
// ---------------------------------------------------------------------------
const HANDLER_ANCHORS = [
["createNodeHandler", /async function createNodeHandler\(req, res\) \{\n if \(!\(await requireNodeAdmin\(req, res\)\)\) return;\n/],
["updateNodeHandler", /async function updateNodeHandler\(req, res\) \{\n if \(!\(await requireNodeAdmin\(req, res\)\)\) return;\n/],
["updateNodeBuildHandler", /async function updateNodeBuildHandler\(req, res\) \{\n if \(!\(await requireNodeAdmin\(req, res\)\)\) return;\n/],
// DELETE's check sits INSIDE the containment try: requireNodeAdmin never
// throws, but if its 403-send ever did, the wrapper must answer 500 behind
// its headersSent guard instead of the rejection escaping uncaught.
["DELETE /api/nodes/:id (inline, inside the containment try)", /app\.delete\("\/api\/nodes\/:id", async \(req, res\) => \{\n \/\/ Express 4[\s\S]*?try \{\n if \(!\(await requireNodeAdmin\(req, res\)\)\) return;\n/],
];
for (const [name, re] of HANDLER_ANCHORS) {
test(`${name} begins with the requireNodeAdmin self-check`, () => {
assert.match(nodesSource, re, `${name} must self-check — it must not rely solely on the module middleware`);
});
}
test("self-check call-site count is pinned (7 pre-existing + 4 new = 11)", () => {
const sites = nodesSource.match(/await requireNodeAdmin\(req, res\)/g) || [];
assert.equal(
sites.length, 11,
"the self-check call sites moved — if a handler lost its check this fails; if a new one was added, update this pin consciously"
);
});
test("the documented exclusions keep their own (non-admin) auth layers", () => {
// config.yml must keep its daemon-credential gate, NOT a session/admin check.
const cfgAt = nodesSource.indexOf('app.get("/api/nodes/:id/config.yml"');
assert.ok(cfgAt !== -1, "config.yml route not found");
const cfgBlock = nodesSource.slice(cfgAt, cfgAt + 2500);
assert.match(cfgBlock, /X-Node-Bootstrap/, "config.yml must keep the bootstrap-header auth");
assert.match(cfgBlock, /authentication required/, "config.yml must keep its 401 posture");
assert.doesNotMatch(cfgBlock, /requireNodeAdmin/, "config.yml must NOT gain an admin-session check (it serves the daemon)");
});
test("the :id/server/{action,command} aliases keep performer-based authz (no admin self-check added)", () => {
// These aliases delegate to the same per-server performers as the
// /api/nodes/server/:name twins; the performers enforce checkServerAccess +
// per-cmd perms for the requesting user, so the exclusion is a semantic
// decision — pin it so a future "symmetry" change cannot silently add an
// admin-session gate to per-server surfaces.
for (const marker of ['app.post("/api/nodes/:id/server/action"', 'app.post("/api/nodes/:id/server/command"']) {
const at = nodesSource.indexOf(marker);
assert.ok(at !== -1, `alias route not found: ${marker}`);
const block = nodesSource.slice(at, at + 500);
assert.doesNotMatch(
block,
/requireNodeAdmin/,
`${marker} must not gain an admin-session check — its performers enforce per-user access`
);
assert.match(
block,
/performPanel/,
`${marker} must keep delegating to the per-server performers`
);
}
});
// ---------------------------------------------------------------------------
// 3. Live behavior — real nodes.js app against the db stub: the outer
// middleware still refuses non-admins on all four routes, and admins reach
// the handler logic (the added checks change nothing for them).
// ---------------------------------------------------------------------------
const parent = express();
let ADMIN_MODE = false;
let verifiedMutationId;
let mutationUsedGrace = false;
parent.use((req, res, next) => {
req.isAdmin = ADMIN_MODE;
req.verifiedNodeMutationId = verifiedMutationId;
req.nodeMutationUsedGrace = mutationUsedGrace;
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;
NODE_ROW = nodeRow();
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) {
const res = await fetch(`${baseUrl}${route}`, {
method,
headers: body === undefined ? {} : { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
const json = await res.json().catch(() => null);
return { status: res.status, json };
}
test("changing the node API port discards health from the previous endpoint", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
NODE_ROW = nodeRow();
try {
assert.strictEqual((await call("GET", route)).json.online, true);
const nextPort = fakeNodePort === 8080 ? 8081 : 8080;
const saved = await call("PATCH", route, { api_port: nextPort });
assert.strictEqual(saved.status, 200);
assert.strictEqual(saved.json.online, false);
const actual = await call("GET", route);
assert.strictEqual(actual.json.api_port, nextPort);
assert.strictEqual(actual.json.online, false);
assert.strictEqual(actual.json.port_ok, null);
assert.strictEqual(actual.json.last_seen, null);
} finally {
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("changing a node address only moves unoccupied allocations on its previous primary address", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
const previousAddress = originalRow.address;
const nextAddress = "127.0.0.2";
const secondaryAddress = "127.0.0.3";
ADMIN_MODE = true;
NODE_ROW = {
...originalRow,
ports: JSON.stringify({ mode: "list", allocations: [
{ ip: previousAddress, port: 25565 },
{ ip: secondaryAddress, port: 25566 },
{ ip: previousAddress, port: 25567 },
] }),
};
SERVER_ROWS = [{ id: 2, name: "assigned-server", node_id: NODE_ROW.id, ip: previousAddress, port: 25567 }];
try {
const after = await call("PATCH", route, { address: nextAddress });
assert.strictEqual(after.status, 200);
assert.deepStrictEqual(after.json.ports.allocations, [
{ ip: nextAddress, port: 25565 },
{ ip: secondaryAddress, port: 25566 },
{ ip: previousAddress, port: 25567 },
]);
} finally {
NODE_ROW = originalRow;
SERVER_ROWS = [];
ADMIN_MODE = false;
}
});
test("changing a node identity cannot release a legacy server's port reservation", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
try {
SERVER_ROWS = [{ id: 2, name: "by-address", node_id: null, ip: originalRow.address, port: 25566 }];
const addressEdit = await call("PATCH", route, { address: "127.0.0.2" });
assert.strictEqual(addressEdit.status, 409);
assert.match(addressEdit.json.error, /server assignments first/);
assert.strictEqual(NODE_ROW.address, originalRow.address);
SERVER_ROWS = [{ id: 3, name: "by-name", node_id: originalRow.name.toUpperCase(), ip: originalRow.address, port: 25567 }];
const rename = await call("PATCH", route, { name: "node-renamed" });
assert.strictEqual(rename.status, 409);
assert.strictEqual(NODE_ROW.name, originalRow.name);
assert.deepStrictEqual((await call("GET", `${route}/ports/in-use`)).json.inUse, { 25567: ["by-name"] });
SERVER_ROWS = [{ id: 4, name: "stable-id", node_id: originalRow.id, ip: originalRow.address, port: 25568 }];
const stableRename = await call("PATCH", route, { name: "node-renamed" });
assert.strictEqual(stableRename.status, 200);
assert.strictEqual(NODE_ROW.name, "node-renamed");
} finally {
NODE_ROW = originalRow;
SERVER_ROWS = [];
ADMIN_MODE = false;
}
});
test("a probe of the previous endpoint cannot restore its discarded health", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
NODE_ROW = nodeRow();
fakeNodeResponding = true;
const probeStarted = new Promise(resolve => { deferNodeInfo = resolve; });
const check = call("POST", `${route}/check`);
try {
const reply = await Promise.race([probeStarted, check.then(() => {
throw new Error("Expected a probe of the original endpoint");
})]);
try {
const nextPort = fakeNodePort === 8080 ? 8081 : 8080;
assert.strictEqual((await call("PATCH", route, { api_port: nextPort })).status, 200);
} finally {
reply();
}
const result = await check;
assert.strictEqual(result.status, 200);
assert.strictEqual(result.json.node.online, false);
assert.strictEqual((await call("GET", route)).json.port_ok, null);
} finally {
deferNodeInfo = undefined;
fakeNodeResponding = false;
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("disabling Cloudflare persists instead of reviving the old proxy mode", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
try {
for (const [method, target] of [["PATCH", route], ["POST", `${route}/build`]]) {
NODE_ROW = {
...originalRow,
api_port: 8443,
build_config: JSON.stringify({ ssl_enabled: true, cloudflare_proxy: true }),
};
const before = await call("GET", route);
assert.strictEqual(before.json.under_cloudflare, true);
const saved = await call(method, target, { under_cloudflare: false });
assert.strictEqual(saved.status, 200);
const after = await call("GET", route);
assert.strictEqual(after.status, 200);
assert.strictEqual(after.json.under_cloudflare, false);
assert.strictEqual(after.json.ssl_enabled, true);
}
} finally {
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("grace-verified saves cannot change connection settings on the locked row", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
verifiedMutationId = String(originalRow.id);
mutationUsedGrace = true;
NODE_ROW = { ...originalRow, api_port: 8443, build_config: JSON.stringify({ ssl_enabled: true }) };
try {
for (const [method, target, body] of [
["PATCH", route, { api_port: 8080 }],
["PATCH", route, { ssl_enabled: false }],
["POST", `${route}/build`, { ssl_enabled: false }],
]) {
const result = await call(method, target, body);
assert.strictEqual(result.status, 409);
assert.match(result.json.error, /connection settings changed/i);
}
assert.strictEqual(NODE_ROW.api_port, 8443);
assert.strictEqual(JSON.parse(NODE_ROW.build_config).ssl_enabled, true);
assert.strictEqual((await call("PATCH", route, { cpu_cores: 2 })).status, 200);
assert.strictEqual((await call("POST", `${route}/build`, { ssl_enabled: true })).status, 200);
mutationUsedGrace = false;
assert.strictEqual((await call("PATCH", route, { ssl_enabled: false })).status, 200);
} finally {
NODE_ROW = originalRow;
verifiedMutationId = undefined;
mutationUsedGrace = false;
ADMIN_MODE = false;
}
});
test("Cloudflare writes reject undialable addresses before looking up DNS", async () => {
const originalRow = NODE_ROW;
const route = "/api/nodes/node-one";
const address = "https://user@node.example.test:2053";
const connection = { api_port: 8443, ssl_enabled: true, under_cloudflare: true };
ADMIN_MODE = true;
try {
const created = await call("POST", "/api/nodes", {
name: "proxy-node", address, cpu_cores: 2, ram_mb: 1024, disk_gb: 10, ...connection,
});
assert.strictEqual(created.status, 400);
assert.match(created.json.error, /must not embed credentials/);
const updated = await call("PATCH", route, { address, ...connection });
assert.strictEqual(updated.status, 400);
assert.match(updated.json.error, /must not embed credentials/);
assert.strictEqual(NODE_ROW, originalRow);
const beforeBuild = NODE_ROW = { ...originalRow, address: "node.example.test:65536", api_port: 8443 };
const build = await call("POST", `${route}/build`, { ssl_enabled: true, under_cloudflare: true });
assert.strictEqual(build.status, 400);
assert.match(build.json.error, /invalid port/);
assert.strictEqual(NODE_ROW, beforeBuild);
} finally {
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("Cloudflare node writes reject allocations on the management hostname", async () => {
const originalRow = NODE_ROW;
const address = "node.example.test";
const ports = { mode: "list", allocations: [{ ip: address, port: 25565 }] };
const connection = { api_port: 8443, ssl_enabled: true, under_cloudflare: true };
const route = "/api/nodes/node-one";
ADMIN_MODE = true;
NODE_ROW = { ...originalRow, address, api_port: 8443, ports: JSON.stringify(ports) };
try {
const before = NODE_ROW;
for (const [method, target, body] of [
["POST", "/api/nodes", { name: "proxy-node", address, cpu_cores: 2, ram_mb: 1024, disk_gb: 10, ports, ...connection }],
["PATCH", route, connection],
["POST", `${route}/build`, connection],
]) {
const result = await call(method, target, body);
assert.strictEqual(result.status, 400);
assert.match(result.json.error, /Allocate port 25565 to a local interface IP/);
assert.strictEqual(NODE_ROW, before);
}
NODE_ROW = { ...before, ports: "{}", build_config: JSON.stringify(connection) };
const result = await call("PATCH", route, { ports });
assert.strictEqual(result.status, 400);
assert.match(result.json.error, /Allocate port 25565 to a local interface IP/);
assert.strictEqual(NODE_ROW.ports, "{}");
} finally {
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("switching to a Cloudflare management hostname preserves existing game addresses", async () => {
const originalRow = NODE_ROW;
ADMIN_MODE = true;
try {
const result = await call("PATCH", "/api/nodes/node-one", {
address: "node.example.test", api_port: 8443, ssl_enabled: true, under_cloudflare: true,
});
assert.strictEqual(result.status, 200);
assert.strictEqual(result.json.under_cloudflare, true);
assert.strictEqual(result.json.ports.allocations.length, 10);
assert.ok(result.json.ports.allocations.every(({ ip }) => ip === originalRow.address));
} finally {
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("a successful health check recovers a previously offline node", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
fakeNodeResponding = true;
NODE_ROW = { ...originalRow, port_ok: 0, last_seen: null, online: 0 };
try {
const result = await call("POST", `${route}/check`);
assert.strictEqual(result.status, 200);
assert.strictEqual(result.json.ok, true);
assert.strictEqual(result.json.node.online, true);
assert.strictEqual(NODE_ROW.online, 1);
assert.strictEqual((await call("GET", route)).json.online, true);
} finally {
NODE_ROW = originalRow;
fakeNodeResponding = false;
ADMIN_MODE = false;
}
});
test("matching public health cannot keep a node online when daemon authentication fails", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
fakeNodeUnauthenticatedHealth = true;
try {
const result = await call("POST", `${route}/check`);
assert.strictEqual(result.status, 200);
assert.strictEqual(result.json.ok, false);
assert.strictEqual(result.json.node.port_ok, false);
assert.strictEqual(NODE_ROW.online, 0);
assert.strictEqual((await call("GET", route)).json.online, false);
} finally {
NODE_ROW = originalRow;
fakeNodeUnauthenticatedHealth = false;
ADMIN_MODE = false;
}
});
test("a stale Nodes-tab allocation edit cannot replace a newer port pool", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
try {
const initial = await call("GET", route);
assert.strictEqual(initial.status, 200);
assert.match(initial.json.ports_revision, /^[a-f0-9]{64}$/);
NODE_ROW = { ...originalRow, ports: JSON.stringify({ mode: "list", ports: [25570, 25565] }) };
const result = await call("PATCH", route, {
ports: { mode: "list", ports: [25565, 25580] },
ports_revision: initial.json.ports_revision,
});
assert.strictEqual(result.status, 409);
assert.match(result.json.error, /allocations changed/i);
const current = await call("GET", route);
assert.strictEqual(current.status, 200);
assert.deepStrictEqual(current.json.ports.ports, [25570, 25565]);
assert.notStrictEqual(current.json.ports_revision, initial.json.ports_revision);
const saved = await call("PATCH", route, {
ports: { mode: "list", ports: [25570, 25580] },
ports_revision: current.json.ports_revision,
});
assert.strictEqual(saved.status, 200);
assert.deepStrictEqual(saved.json.ports.ports, [25570, 25580]);
assert.strictEqual((await call("GET", route)).json.ports_revision, saved.json.ports_revision);
} finally {
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("missing or unknown node port pools do not create assignable ports", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
try {
for (const ports of [null, "{}", JSON.stringify({ mode: "range", start: 25565, count: 10, allocations: [], ports: [] }),
JSON.stringify({ mode: "range", start: "invalid", count: 10 })]) {
NODE_ROW = { ...originalRow, ports };
const result = await call("GET", route);
assert.strictEqual(result.status, 200);
assert.deepStrictEqual(result.json.ports, { mode: "list", ports: [], allocations: [] });
}
NODE_ROW = { ...originalRow, ports: JSON.stringify({ mode: "range", start: 25565, count: 2 }) };
const result = await call("GET", route);
assert.strictEqual(result.status, 200);
assert.deepStrictEqual(result.json.ports.ports, [25565, 25566]);
NODE_ROW = { ...originalRow, ports: JSON.stringify({ mode: "list", allocations: [], ports: [25565] }) };
assert.deepStrictEqual((await call("GET", route)).json.ports.ports, [25565]);
} finally {
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("unusable port-pool payloads are refused without changing the stored pool", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
try {
for (const ports of [[25565.5], { mode: "list", ports: "25565" }, { mode: "range", start: "unknown", count: 2 },
{ mode: "range", start: 65535, count: 2 }]) {
const result = await call("PATCH", route, { ports });
assert.strictEqual(result.status, 400);
assert.strictEqual(NODE_ROW.ports, originalRow.ports);
}
const legacy = await call("PATCH", route, { port_list: "25565, 25566" });
assert.strictEqual(legacy.status, 200);
assert.deepStrictEqual(legacy.json.ports.ports, [25565, 25566]);
const primary = NODE_ROW.address;
const secondary = "127.0.0.2";
const allocations = [{ ip: primary, port: 25565 }, { ip: secondary, port: 25565 }];
const duplicate = await call("PATCH", route, { ports: { mode: "list", allocations } });
assert.strictEqual(duplicate.status, 400);
assert.match(duplicate.json.error, /only be allocated once/);
NODE_ROW = { ...NODE_ROW, ports: JSON.stringify({ mode: "list", allocations }) };
const cleanup = await call("PATCH", route, { ports: { mode: "list", allocations: [allocations[0]] } });
assert.strictEqual(cleanup.status, 200);
assert.deepStrictEqual(cleanup.json.ports.allocations, [allocations[0]]);
} finally {
NODE_ROW = originalRow;
ADMIN_MODE = false;
}
});
test("the node protects host bindings without reserving container-only template ports", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
SERVER_ROWS = [{
id: 2, name: "fixture-server", node_id: NODE_ROW.id, ip: NODE_ROW.address,
port: 25566, reinstall_pending_port: 25568, status: "stopped",
runtime: JSON.stringify({ ports: [25565] }),
resources: JSON.stringify({ ports: [25567], portAllocations: [] }),
}];
try {
const inUse = await call("GET", `${route}/ports/in-use`);
assert.strictEqual(inUse.status, 200);
assert.deepStrictEqual(inUse.json.inUse, {
25566: ["fixture-server"], 25567: ["fixture-server"], 25568: ["fixture-server"],
});
for (const port of [25566, 25567, 25568]) {
const check = await call("GET", `${route}/ports/check?port=${port}`);
assert.strictEqual(check.status, 200);
assert.strictEqual(check.json.available, false);
assert.strictEqual(check.json.reason, "assigned-to-server");
}
const containerOnly = await call("GET", `${route}/ports/check?port=25565`);
assert.strictEqual(containerOnly.json.available, null);
const refused = await call("PATCH", route, { ports: [25566, 25568] });
assert.strictEqual(refused.status, 409);
assert.match(refused.json.error, /25567/);
const saved = await call("PATCH", route, { ports: [25566, 25567, 25568] });
assert.strictEqual(saved.status, 200);
assert.deepStrictEqual(saved.json.ports.ports, [25566, 25567, 25568]);
} finally {
NODE_ROW = originalRow;
SERVER_ROWS = [];
ADMIN_MODE = false;
}
});
test("an explicit assignment to another node does not lock this node's shared-address ports", async () => {
const route = "/api/nodes/node-one";
const originalRow = NODE_ROW;
ADMIN_MODE = true;
SERVER_ROWS = [
{ id: 2, name: "other-by-id", node_id: OTHER_NODE.id, ip: NODE_ROW.address, port: 25565 },
{ id: 3, name: "other-by-uuid", node_id: OTHER_NODE.uuid, ip: NODE_ROW.address, port: 25566 },
{ id: 4, name: "assigned-here", node_id: NODE_ROW.id, ip: NODE_ROW.address, port: 25567 },
{ id: 5, name: "legacy-by-address", node_id: null, ip: NODE_ROW.address, port: 25568 },
];
try {
const inUse = await call("GET", `${route}/ports/in-use`);
assert.strictEqual(inUse.status, 200);
assert.deepStrictEqual(inUse.json.inUse, { 25567: ["assigned-here"], 25568: ["legacy-by-address"] });
const refused = await call("PATCH", route, { ports: [25567] });
assert.strictEqual(refused.status, 409);
assert.match(refused.json.error, /legacy-by-address/);
const saved = await call("PATCH", route, { ports: [25567, 25568] });
assert.strictEqual(saved.status, 200);
assert.deepStrictEqual(saved.json.ports.ports, [25567, 25568]);
} finally {
NODE_ROW = originalRow;
SERVER_ROWS = [];
ADMIN_MODE = false;
}
});
test("node deletion writes only the primary key that was checked for assignments", async () => {
ADMIN_MODE = true;
NODE_DELETES = [];
try {
const result = await call("DELETE", "/api/nodes/node-one");
assert.strictEqual(result.status, 200);
assert.deepStrictEqual(NODE_DELETES, [{ sql: "DELETE FROM nodes WHERE id = ?", params: [NODE_ROW.id] }]);
} finally {
ADMIN_MODE = false;
}
});
test("a step-up target that now resolves as another node's alias cannot be mutated", async () => {
ADMIN_MODE = true;
verifiedMutationId = NODE_ROW.uuid;
NODE_DELETES = [];
try {
assert.strictEqual((await call("DELETE", "/api/nodes/node-one")).status, 404);
assert.strictEqual((await call("PATCH", "/api/nodes/node-one", { ram_mb: 4096 })).status, 404);
assert.strictEqual((await call("POST", "/api/nodes/node-one/build", {})).status, 404);
assert.deepStrictEqual(NODE_DELETES, []);
} finally {
verifiedMutationId = undefined;
ADMIN_MODE = false;
}
});
const FLEET_MUTATIONS = [
["POST", "/api/nodes", { name: "node-two", address: "127.0.0.1" }],
["PATCH", "/api/nodes/node-one", { ram_mb: 4096 }],
["DELETE", "/api/nodes/node-one"],
["POST", "/api/nodes/node-one/build", {}],
];
test("non-admin: the module middleware still refuses all four routes with 403 admin required", async () => {
injectIsAdmin(async () => false);
for (const [method, route, body] of FLEET_MUTATIONS) {
const result = await call(method, route, body);
assert.strictEqual(result.status, 403, `${method} ${route}`);
assert.strictEqual(result.json && result.json.error, "admin required", `${method} ${route}`);
}
});
test("admin: all four routes pass the admin gate into the handler logic (no behavior change)", async () => {
// Simulate the request as the panel's own admin middlewares would deliver
// it: req.isAdmin already attested true before the router runs. Even a
// rejecting injected checker must not matter for an attested admin.
ADMIN_MODE = true;
try {
injectIsAdmin(async () => false);
for (const [method, route, body] of FLEET_MUTATIONS) {
const result = await call(method, route, body);
const adminRefusal = result.status === 403 &&
result.json && result.json.error === "admin required";
assert.notStrictEqual(
adminRefusal, true,
`${method} ${route} must not be stopped by the admin gate for an attested admin (got ${result.status})`
);
}
} finally {
ADMIN_MODE = false;
}
});