Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,279 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:proxy-create-contract — behavioral pin for POST
|
||||
// /api/nodes/:id/servers/create's SUCCESS contract (spec-risk item: nothing
|
||||
// pinned what the proxy returns on success or the lean row it commits).
|
||||
//
|
||||
// The proxy's success contract, driven here end-to-end against a fake daemon:
|
||||
// 1. the response body is the DAEMON'S create reply forwarded VERBATIM
|
||||
// (res.json(createOutcome.json) with json = the daemon 200 body) — the
|
||||
// panel flow and admin tooling read meta.setupStatus/asyncSetup off it;
|
||||
// 2. the committed index row is the lean serverEntry shape: token-form
|
||||
// name, displayName fallback, per-template start file, node uuid
|
||||
// binding, the requested host port, and — with asyncSetup — status
|
||||
// "installing" keyed off the daemon's setupStatus ("failed" → "error"),
|
||||
// committed through the shared guarded writer (never an upsert);
|
||||
// 3. the cross-process create lock acquired by the handler is released on
|
||||
// the success path.
|
||||
//
|
||||
// Same loading technique as tests/node-response-cap.test.js: nodes.js is
|
||||
// required in-process against a stubbed ./db (it cannot be exercised through
|
||||
// index.js, which boots servers on require), with its injection seams
|
||||
// (setPermissionCheckers / setServerIndexWriters / setServerCreateHelpers)
|
||||
// wired to fakes, and a loopback daemon answering the two dials the locked
|
||||
// continuation makes (/v1/ports/check, /v1/servers/create).
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const http = require("node:http");
|
||||
const path = require("node:path");
|
||||
const Module = require("node:module");
|
||||
|
||||
process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1";
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const NODES_JS = path.join(ROOT, "nodes.js");
|
||||
|
||||
// The lean row the proxy must commit through the guarded writer.
|
||||
let committedEntry = null;
|
||||
let guardedWriterCalls = 0;
|
||||
let createLockReleased = false;
|
||||
|
||||
function makeDbStub(nodeRow, serverRows) {
|
||||
return {
|
||||
async query(sql) {
|
||||
const text = String(sql || "");
|
||||
if (/^SELECT \* FROM nodes\b/i.test(text)) return nodeRow ? [nodeRow] : [];
|
||||
if (/^SELECT id, name, display_name, legacy_id, node_id, ip, port, status, resources, runtime,/i.test(text)) return serverRows;
|
||||
return [];
|
||||
},
|
||||
pool: {
|
||||
async execute() { return [[]]; },
|
||||
async query() { return [[]]; },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const DAEMON_REPLY = {
|
||||
ok: true,
|
||||
name: "ProxyCreateTest",
|
||||
asyncSetup: true,
|
||||
meta: {
|
||||
setupStatus: "installing",
|
||||
setupMessage: "jar download queued",
|
||||
},
|
||||
};
|
||||
|
||||
async function loadNodesAgainst(dbStub) {
|
||||
const originalLoad = Module._load;
|
||||
Module._load = function (request, parent, isMain) {
|
||||
if (request === "./db" && parent && parent.filename === NODES_JS) return dbStub;
|
||||
return originalLoad.apply(this, arguments);
|
||||
};
|
||||
try {
|
||||
return require(NODES_JS);
|
||||
} finally {
|
||||
Module._load = originalLoad;
|
||||
}
|
||||
}
|
||||
|
||||
function startServer(handler) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = http.createServer(handler);
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => resolve({ server, port: server.address().port }));
|
||||
});
|
||||
}
|
||||
|
||||
function stopServer(server) {
|
||||
if (!server) return;
|
||||
if (typeof server.closeAllConnections === "function") server.closeAllConnections();
|
||||
server.close();
|
||||
}
|
||||
|
||||
function postJson(port, urlPath, body) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const data = JSON.stringify(body);
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: "127.0.0.1",
|
||||
port,
|
||||
path: urlPath,
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) },
|
||||
},
|
||||
(res) => {
|
||||
const chunks = [];
|
||||
res.on("data", (d) => chunks.push(d));
|
||||
res.on("error", reject);
|
||||
res.on("end", () => {
|
||||
let parsed = null;
|
||||
try { parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { }
|
||||
resolve({ status: res.statusCode, body: parsed });
|
||||
});
|
||||
}
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.end(data);
|
||||
});
|
||||
}
|
||||
|
||||
test("proxy create forwards the daemon reply verbatim and commits the lean guarded row", async () => {
|
||||
let daemon;
|
||||
let panelApp;
|
||||
let createPayload;
|
||||
let portProbeCalls = 0;
|
||||
const serverRows = [];
|
||||
try {
|
||||
// Fake node daemon: the port check passes, the create succeeds async.
|
||||
({ server: daemon } = await startServer((req, res) => {
|
||||
res.writeHead(200, { "Content-Type": "application/json" });
|
||||
if (req.method === "GET" && req.url.startsWith("/v1/ports/check")) {
|
||||
portProbeCalls += 1;
|
||||
return res.end(JSON.stringify({ ok: true, available: true }));
|
||||
}
|
||||
if (req.method === "POST" && req.url.startsWith("/v1/servers/create")) {
|
||||
const chunks = [];
|
||||
req.on("data", chunk => chunks.push(chunk));
|
||||
req.on("end", () => {
|
||||
createPayload = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
||||
res.end(JSON.stringify(DAEMON_REPLY));
|
||||
});
|
||||
return;
|
||||
}
|
||||
return res.end(JSON.stringify({ ok: false, error: "unexpected dial" }));
|
||||
}));
|
||||
|
||||
const nodeRow = {
|
||||
id: "node-1",
|
||||
uuid: "uuid-node-1",
|
||||
name: "Node One",
|
||||
address: "127.0.0.1",
|
||||
api_port: daemon.address().port,
|
||||
token: "test-token", // legacy plaintext passes decryptNodeToken unchanged
|
||||
token_id: "1",
|
||||
ports: JSON.stringify({ mode: "list", allocations: [{ ip: "127.0.0.2", port: 25565 }] }),
|
||||
build_config: "{}",
|
||||
};
|
||||
|
||||
const nodes = await loadNodesAgainst(makeDbStub(nodeRow, serverRows));
|
||||
|
||||
nodes.setPermissionCheckers(
|
||||
async () => ({}),
|
||||
async () => true,
|
||||
async () => true
|
||||
);
|
||||
nodes.setServerIndexWriters({
|
||||
insertServerIndexEntryGuarded: async (entry) => {
|
||||
guardedWriterCalls += 1;
|
||||
committedEntry = entry;
|
||||
return { ok: true };
|
||||
},
|
||||
acquireServerCreateLock: () => {
|
||||
return () => { createLockReleased = true; };
|
||||
},
|
||||
});
|
||||
nodes.setServerCreateHelpers({
|
||||
findServer: async () => null, // no duplicate pre-check hit
|
||||
normalizeTemplateId: (id) => id,
|
||||
});
|
||||
|
||||
// The app-wide node-API gate (nodes.js, registered at module scope)
|
||||
// requires req.isAdmin — set in production by index.js's session
|
||||
// middleware, which cannot load here. Swap the gate layer's handle for
|
||||
// one that stamps the same identity the real middleware would, at the
|
||||
// same point in the stack; the gate's per-route self-defense
|
||||
// (requireNodeAdmin) still runs for real underneath.
|
||||
const stack = nodes._router && nodes._router.stack;
|
||||
assert.ok(Array.isArray(stack), "expected the express 4 router stack");
|
||||
const gateLayer = stack.find((l) => l && typeof l.handle === "function" && String(l.handle).includes("admin required"));
|
||||
assert.ok(gateLayer, "expected the app-wide node-api admin gate layer");
|
||||
gateLayer.handle = function testAdminImpersonation(req, res, next) {
|
||||
req.isAdmin = true;
|
||||
next();
|
||||
};
|
||||
|
||||
// module.exports IS the express app (property exports ride on it), so
|
||||
// the app is bound directly.
|
||||
({ server: panelApp } = await startServer(nodes));
|
||||
const { status, body } = await postJson(
|
||||
panelApp.address().port,
|
||||
"/api/nodes/node-1/servers/create",
|
||||
{ name: "ProxyCreateTest", templateId: "minecraft", mcFork: "vanilla", mcVersion: "1.21.8", hostPort: 25565 }
|
||||
);
|
||||
|
||||
// Contract 1: the daemon reply is forwarded verbatim.
|
||||
assert.equal(status, 200, `expected the daemon 200 to relay, got ${status}: ${JSON.stringify(body)}`);
|
||||
assert.deepEqual(body, DAEMON_REPLY);
|
||||
assert.equal(createPayload.bind_ip, "127.0.0.2");
|
||||
|
||||
// Contract 2: the lean committed row.
|
||||
assert.equal(guardedWriterCalls, 1, "the commit must go through the shared guarded writer exactly once");
|
||||
assert.ok(committedEntry, "the guarded writer must receive the server entry");
|
||||
assert.equal(committedEntry.name, "ProxyCreateTest");
|
||||
assert.equal(committedEntry.template, "minecraft");
|
||||
assert.equal(committedEntry.start, "server.jar");
|
||||
assert.equal(committedEntry.mcFork, "vanilla");
|
||||
assert.equal(committedEntry.mcVersion, "1.21.8");
|
||||
assert.equal(committedEntry.nodeId, "uuid-node-1", "the row must bind the node's uuid");
|
||||
assert.equal(committedEntry.ip, "127.0.0.2");
|
||||
assert.equal(committedEntry.port, 25565);
|
||||
assert.equal(committedEntry.status, "installing", "asyncSetup rows must commit status 'installing'");
|
||||
assert.equal(committedEntry.setupStatus, "installing");
|
||||
assert.equal(committedEntry.setupMessage, "jar download queued");
|
||||
|
||||
// Contract 3: the create lock is released on the success path.
|
||||
assert.equal(createLockReleased, true, "the cross-process create lock must be released in the handler's finally");
|
||||
|
||||
nodeRow.ports = JSON.stringify({ mode: "list", allocations: [{ ip: nodeRow.address, port: 25565 }] });
|
||||
const primary = await postJson(
|
||||
panelApp.address().port,
|
||||
"/api/nodes/node-1/servers/create",
|
||||
{ name: "ProxyPrimaryBind", templateId: "minecraft", mcFork: "vanilla", mcVersion: "1.21.8", hostPort: 25565 }
|
||||
);
|
||||
assert.equal(primary.status, 200);
|
||||
assert.equal(createPayload.bind_ip, nodeRow.address);
|
||||
assert.equal(createPayload.host_ip, nodeRow.address);
|
||||
|
||||
nodeRow.ports = JSON.stringify({ mode: "range", start: 25565, count: 16 });
|
||||
const legacy = await postJson(
|
||||
panelApp.address().port,
|
||||
"/api/nodes/node-1/servers/create",
|
||||
{ name: "ProxyLegacyBind", templateId: "minecraft", mcFork: "vanilla", mcVersion: "1.21.8", hostPort: 25565 }
|
||||
);
|
||||
assert.equal(legacy.status, 200);
|
||||
assert.equal(createPayload.bind_ip, undefined);
|
||||
assert.equal(createPayload.host_ip, undefined);
|
||||
assert.equal(committedEntry.ip, nodeRow.address);
|
||||
|
||||
serverRows.push({
|
||||
id: 4, name: "DeletingServer", node_id: nodeRow.id, status: "deleting",
|
||||
port: 25566, resources: JSON.stringify({ ports: [25567] }), reinstall_pending_port: 25568,
|
||||
});
|
||||
const previousPortProbes = portProbeCalls;
|
||||
const previousWrites = guardedWriterCalls;
|
||||
for (const hostPort of [25567, 25568, 25566]) {
|
||||
createLockReleased = false;
|
||||
const blocked = await postJson(
|
||||
panelApp.address().port,
|
||||
"/api/nodes/node-1/servers/create",
|
||||
{ name: "BlockedCreate", templateId: "minecraft", mcFork: "vanilla", mcVersion: "1.21.8", hostPort }
|
||||
);
|
||||
assert.equal(blocked.status, 409);
|
||||
assert.deepEqual(blocked.body, {
|
||||
error: `Port ${hostPort} is being released by server "DeletingServer" on this node; retry in a moment.`,
|
||||
code: "port_in_use",
|
||||
});
|
||||
assert.equal(createLockReleased, true);
|
||||
}
|
||||
assert.equal(portProbeCalls, previousPortProbes, "the daemon cannot override assigned ports during teardown");
|
||||
assert.equal(guardedWriterCalls, previousWrites);
|
||||
} finally {
|
||||
stopServer(panelApp);
|
||||
stopServer(daemon);
|
||||
// Settle the activity-log flush timers recordActivity scheduled, so the
|
||||
// test process does not linger on them.
|
||||
try { nodes && nodes.flushActivityLogs("ProxyCreateTest"); } catch { }
|
||||
try { nodes && nodes.flushActivityLogs("_system"); } catch { }
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user