1658 lines
83 KiB
JavaScript
1658 lines
83 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the F2 remediation: the non-admin reinstall route
|
|
// (POST /api/servers/:name/reinstall) sat behind a session + server_reinstall
|
|
// permission check only, so a phished or XSS'd session — or a cross-site POST,
|
|
// had the origin check ever regressed — could wipe a server in one unthrottled
|
|
// request.
|
|
//
|
|
// The remediation puts three independent gates in front of the node call, and
|
|
// this file locks each one in:
|
|
// 1. serverReinstallRateLimiter — dedicated per-user+session budget
|
|
// (behaviorally executed in a vm sandbox with a stubbed express-rate-limit).
|
|
// 2. A one-time, session-bound, server-scoped action token minted by
|
|
// GET /api/servers/:name/permissions under server_reinstall (the real
|
|
// verifyActionToken machinery is executed: mint → verify, then replay,
|
|
// wrong server, wrong session, expired and missing tokens all fail).
|
|
// 3. requireDestructiveActionStepUp — fresh password/2FA proof with
|
|
// persistGrant: false, wired BEFORE the node reinstall call (source-order
|
|
// assertions, because index.js boots servers on require and cannot be
|
|
// loaded in-process — same technique as template-store-install-review).
|
|
// Plus the frontend contract in bot.js / bot.ejs: the modal sends the fresh
|
|
// one-time token, reacts to the step-up 403 codes, and collects the credential.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const vm = require("node:vm");
|
|
const crypto = require("node:crypto");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
|
|
const BOT_EJS = path.join(ROOT, "views", "bot.ejs");
|
|
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const botSource = fs.readFileSync(BOT_JS, "utf8");
|
|
const botEjsSource = fs.readFileSync(BOT_EJS, "utf8");
|
|
const reinstallSource = fs.readFileSync(path.join(ROOT, "public", "js", "server-reinstall.js"), "utf8");
|
|
|
|
test("completed reinstall classification preserves consent and failure boundaries", () => {
|
|
const { isNodeReinstallComplete } = require("../utils/server-reinstall");
|
|
assert.equal(isNodeReinstallComplete({ status: 200, json: { ok: true } }, "custom"), true);
|
|
const eulaResult = { status: 409, json: { ok: false, code: "minecraft_eula_required" } };
|
|
assert.equal(isNodeReinstallComplete(eulaResult, "minecraft"), true);
|
|
assert.equal(isNodeReinstallComplete(eulaResult, "nodejs"), false);
|
|
assert.equal(isNodeReinstallComplete({ ...eulaResult, status: 403 }, "minecraft"), false);
|
|
assert.equal(isNodeReinstallComplete({ status: 409, json: { code: "reinstall_in_progress" } }, "minecraft"), false);
|
|
assert.equal(isNodeReinstallComplete({ status: 200, json: { ok: false } }, "minecraft"), false);
|
|
assert.equal(isNodeReinstallComplete({ status: 200, json: { ok: "true" } }, "custom"), false);
|
|
assert.equal(isNodeReinstallComplete(null, "minecraft"), false);
|
|
});
|
|
|
|
test("reinstall partial completion requires a confirmed persisted rebuild, not an arbitrary failure", () => {
|
|
const { getNodeReinstallFailure } = require("../utils/server-reinstall");
|
|
assert.equal(getNodeReinstallFailure({ status: 200, json: { ok: true } }, "custom"), null);
|
|
for (const body of [
|
|
{ ok: false, code: "reinstall_start_failed", reinstalled: true },
|
|
{ ok: false, error: "server files reinstalled but container failed to start" },
|
|
{ ok: false, code: "reinstall_install_failed", reinstalled: true },
|
|
{ ok: false, code: "reinstall_cleanup_failed", reinstalled: true, serverStopped: true },
|
|
{ ok: false, code: "reinstall_image_pull_failed", reinstalled: true },
|
|
{ ok: false, code: "reinstall_jar_resolution_failed", reinstalled: true },
|
|
{ ok: false, code: "reinstall_download_failed", reinstalled: true },
|
|
]) {
|
|
const failure = getNodeReinstallFailure({ status: 500, json: body }, "custom");
|
|
assert.equal(failure.ok, false);
|
|
assert.equal(failure.reinstalled, true);
|
|
assert.equal(failure.statusCode, 502);
|
|
}
|
|
const quotaFailure = getNodeReinstallFailure({ status: 507, json: {
|
|
ok: false, code: "reinstall_disk_limit_exceeded", reinstalled: true,
|
|
} }, "minecraft");
|
|
assert.equal(quotaFailure.reinstalled, true);
|
|
assert.equal(quotaFailure.statusCode, 502);
|
|
for (const result of [
|
|
{ status: 0, json: null },
|
|
{ status: 500, json: { ok: false, error: "install failed" } },
|
|
{ status: 500, json: { ok: false, code: "reinstall_start_failed" } },
|
|
{ status: 500, json: { ok: false, code: "reinstall_image_pull_failed", reinstalled: "true" } },
|
|
{ status: 400, json: { ok: false, code: "reinstall_start_failed", reinstalled: true } },
|
|
{ status: 200, json: { ok: "true" } },
|
|
null,
|
|
]) {
|
|
assert.notEqual(getNodeReinstallFailure(result, "custom").reinstalled, true);
|
|
}
|
|
});
|
|
|
|
test("reinstall target validation ignores status/display changes but rejects destructive configuration changes", async () => {
|
|
const { validateReinstallTarget } = require("../utils/server-reinstall");
|
|
const expectedEntry = {
|
|
name: "alpha", rowId: 1, id: "legacy-alpha", bot: "alpha", nodeId: "node1", template: "nodejs", port: 30005,
|
|
runtime: { image: "node", env: { FIRST: "one", SECOND: "two" } },
|
|
acl: { "member@example.com": { server_reinstall: true } }, status: "stopped",
|
|
};
|
|
const currentEntry = { ...expectedEntry, status: "reinstalling", displayName: "Changed title",
|
|
runtime: { env: { SECOND: "two", FIRST: "one" }, image: "node" },
|
|
};
|
|
assert.equal((await validateReinstallTarget({ findServer: async () => currentEntry }, expectedEntry)).ok, true);
|
|
for (const changed of [
|
|
{ ...currentEntry, rowId: 2 },
|
|
{ ...currentEntry, nodeId: "node2" },
|
|
{ ...currentEntry, suspended: true },
|
|
{ ...currentEntry, runtime: { image: "python" } },
|
|
{ ...currentEntry, acl: { "member@example.com": { server_reinstall: false } } },
|
|
null,
|
|
]) {
|
|
const result = await validateReinstallTarget({ findServer: async () => changed }, expectedEntry);
|
|
assert.equal(result.ok, false);
|
|
assert.equal(result.code, "reinstall-target-changed");
|
|
}
|
|
});
|
|
|
|
test("reinstall signing retry reaches legacy fallback when node rotation is unavailable", async () => {
|
|
const attempts = [];
|
|
const sandbox = {
|
|
nodeAdminSigningSecrets: () => ["derived", "master"],
|
|
ensureNodePanelHmacSecret: async () => false,
|
|
isLegacySigningRejection: (result) => result?.status === 403 && result.json?.error === "bad-signature",
|
|
signPanelAdminReinstallHeaders: (headers, _node, _name, _template, options) => {
|
|
headers.secret = options.secret;
|
|
headers.legacy = options.legacy === true;
|
|
return true;
|
|
},
|
|
};
|
|
const retry = require("../utils/server-reinstall").createReinstallSigningRetry(sandbox);
|
|
assert.match(indexSource, /const retryReinstallAfterSigningRejection = createReinstallSigningRetry\(/);
|
|
const headers = {};
|
|
const result = await retry({}, headers, "alpha", "custom", async () => {
|
|
attempts.push({ ...headers });
|
|
return { res: headers.secret === "master" && headers.legacy
|
|
? { status: 200, json: { ok: true } }
|
|
: { status: 403, json: { error: "bad-signature" } } };
|
|
});
|
|
assert.equal(result?.res.status, 200);
|
|
assert.ok(attempts.some((attempt) => attempt.secret === "master" && attempt.legacy));
|
|
});
|
|
|
|
test("reinstall signing retries stop on transport, execution, or consent results", async () => {
|
|
for (const result of [
|
|
{ status: 0, json: null },
|
|
{ status: 500, json: { error: "install failed" } },
|
|
{ status: 409, json: { code: "minecraft_eula_required" } },
|
|
{ status: 200, json: { ok: true } },
|
|
]) {
|
|
let attempts = 0;
|
|
const retry = require("../utils/server-reinstall").createReinstallSigningRetry({
|
|
nodeAdminSigningSecrets: () => ["derived", "master"],
|
|
ensureNodePanelHmacSecret: async () => false,
|
|
signPanelAdminReinstallHeaders: () => true,
|
|
isLegacySigningRejection: (response) => response?.status === 403 && response.json?.error === "bad-signature",
|
|
});
|
|
const returned = await retry({}, {}, "alpha", "minecraft", async () => {
|
|
attempts += 1;
|
|
return { res: result };
|
|
});
|
|
assert.equal(attempts, 1, "only pre-execution signature rejection permits another destructive attempt");
|
|
assert.equal(returned.res, result);
|
|
}
|
|
});
|
|
|
|
// Slice a `{ ... }`-balanced block starting at startMarker, including any
|
|
// trailing call syntax (`});`) so `const x = rateLimit({...});` stays parseable.
|
|
function extractBlock(source, startMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
|
const bodyStart = source.indexOf("{", start);
|
|
let depth = 0;
|
|
let i = bodyStart;
|
|
for (; i < source.length; i += 1) {
|
|
if (source[i] === "{") depth += 1;
|
|
else if (source[i] === "}") {
|
|
depth -= 1;
|
|
if (depth === 0) {
|
|
i += 1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
|
|
// Swallow the statement terminator (and any closing paren of the call).
|
|
while (i < source.length && (source[i] === ")" || source[i] === ";" || /\s/.test(source[i]))) {
|
|
i += 1;
|
|
if (source[i - 1] === ";") break;
|
|
}
|
|
return source.slice(start, i);
|
|
}
|
|
|
|
function extractRoute(source, routeMarker, nextRouteMarker) {
|
|
const start = source.indexOf(routeMarker);
|
|
assert.ok(start >= 0, `route marker not found: ${routeMarker}`);
|
|
const end = source.indexOf(nextRouteMarker, start);
|
|
assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`);
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
function buildReinstallTransportHarness(rejectField) {
|
|
const calls = [];
|
|
const sandbox = {
|
|
...require("../utils/daemon-protocol"),
|
|
console: { warn() {} },
|
|
httpRequestJson: async (_url, _method, _headers, body) => {
|
|
calls.push(structuredClone(body));
|
|
return Object.hasOwn(body, rejectField) || (body.docker && Object.hasOwn(body.docker, rejectField))
|
|
? { status: 400, json: { error: "bad json", detail: `json: unknown field "${rejectField}"` } }
|
|
: { status: 200, json: { ok: true } };
|
|
},
|
|
};
|
|
for (const marker of ["function cloneJsonPayload(value)", "function removeJsonFieldDeep(value, fieldName)"]) {
|
|
vm.runInNewContext(extractBlock(indexSource, marker), sandbox);
|
|
}
|
|
assert.match(indexSource, /const \{ NODE_REQUEST_CRITICAL_FIELDS,[^\n]*\} = require\("\.\/utils\/daemon-protocol"\);/);
|
|
vm.runInNewContext(extractBlock(indexSource,
|
|
"async function httpRequestJsonPruningUnknownFields("), sandbox);
|
|
return { calls, request: sandbox.httpRequestJsonPruningUnknownFields };
|
|
}
|
|
|
|
test("reinstall transport: legacy rejection must not prune the allocated host port", async () => {
|
|
const { calls, request } = buildReinstallTransportHarness("hostPort");
|
|
const result = await request("http://node.invalid/reinstall", "POST", {},
|
|
{ templateId: "custom", hostPort: 30005 }, 1000, "node-reinstall");
|
|
assert.equal(calls.length, 1, "a node that cannot honor the allocated port must refuse before another request");
|
|
assert.equal(result.res.status, 400);
|
|
assert.equal(result.blockedUnknownField, "hostPort");
|
|
assert.equal(result.body.hostPort, 30005);
|
|
});
|
|
|
|
test("reinstall transport: legacy rejection must not prune the requested Minecraft Java version", async () => {
|
|
const { calls, request } = buildReinstallTransportHarness("javaVersion");
|
|
const result = await request("http://node.invalid/reinstall", "POST", {},
|
|
{ templateId: "minecraft", hostPort: 30005, javaVersion: "21" }, 1000, "node-reinstall");
|
|
assert.equal(calls.length, 1, "an incompatible daemon must not receive a second request without the requested Java version");
|
|
assert.equal(result.res.status, 400);
|
|
assert.equal(result.blockedUnknownField, "javaVersion");
|
|
assert.equal(result.body.javaVersion, "21");
|
|
});
|
|
|
|
test("node create transport retains its existing Java version compatibility fallback", async () => {
|
|
const { calls, request } = buildReinstallTransportHarness("javaVersion");
|
|
const result = await request("http://node.invalid/create", "POST", {},
|
|
{ templateId: "minecraft", hostPort: 30005, javaVersion: "21" }, 1000, "node-create");
|
|
assert.equal(calls.length, 2);
|
|
assert.equal(result.res.status, 200);
|
|
assert.equal(result.body.javaVersion, undefined);
|
|
});
|
|
|
|
test("reinstall transport: optional legacy fields still retry without changing the allocated host port", async () => {
|
|
const { calls, request } = buildReinstallTransportHarness("console");
|
|
const result = await request("http://node.invalid/reinstall", "POST", {},
|
|
{ templateId: "custom", hostPort: 30005, console: "stdin" }, 1000, "node-reinstall");
|
|
assert.equal(calls.length, 2);
|
|
assert.ok(calls.every((body) => body.hostPort === 30005));
|
|
assert.equal(result.res.status, 200);
|
|
assert.deepEqual(Array.from(result.prunedUnknownFields), ["console"]);
|
|
});
|
|
|
|
test("reinstall transport: a required read-only filesystem cannot be pruned", async () => {
|
|
const { calls, request } = buildReinstallTransportHarness("readonlyRootfs");
|
|
const result = await request("http://node.invalid/reinstall", "POST", {},
|
|
{ templateId: "custom", hostPort: 30005, docker: { readonlyRootfs: true } }, 1000, "node-reinstall");
|
|
assert.equal(calls.length, 1);
|
|
assert.equal(result.res.status, 400);
|
|
assert.equal(result.blockedUnknownField, "readonlyRootfs");
|
|
assert.equal(result.body.docker.readonlyRootfs, true);
|
|
|
|
const optional = buildReinstallTransportHarness("readonlyRootfs");
|
|
const fallback = await optional.request("http://node.invalid/reinstall", "POST", {},
|
|
{ templateId: "custom", hostPort: 30005, docker: { readonlyRootfs: false } }, 1000, "node-reinstall");
|
|
assert.equal(optional.calls.length, 2);
|
|
assert.equal(fallback.res.status, 200);
|
|
assert.deepEqual(Array.from(fallback.prunedUnknownFields), ["readonlyRootfs"]);
|
|
});
|
|
|
|
test("reinstall transport: optional legacy retry cannot dispatch after session revocation", async () => {
|
|
const { calls, request } = buildReinstallTransportHarness("console");
|
|
const actor = { id: 7, email: "admin@example.com", admin: true, password: "synthetic-password-hash" };
|
|
let authorityChecks = 0;
|
|
const result = await require("../utils/server-reinstall").callAuthorizedReinstall({
|
|
isSessionSidRevoked: async () => ++authorityChecks > 1,
|
|
findUserByEmail: async () => actor,
|
|
httpRequestJsonPruningUnknownFields: request,
|
|
}, { session: { user: actor.email }, sessionID: "synthetic-session-id" }, actor, "alpha",
|
|
{ url: "http://node.invalid/reinstall", headers: {}, payload: { templateId: "custom", hostPort: 30005, console: "stdin" } });
|
|
assert.equal(calls.length, 1, "a decode rejection must not authorize a later resend under revoked authority");
|
|
assert.equal(result.authorization?.statusCode, 403);
|
|
assert.equal(result.authorization?.code, "reinstall-authorization-changed");
|
|
});
|
|
|
|
test("serverReinstallRateLimiter: 5 per 10 minutes keyed per account+session", () => {
|
|
let captured = null;
|
|
const sandbox = {
|
|
rateLimit: (config) => {
|
|
captured = config;
|
|
return function middleware() { };
|
|
},
|
|
getRequestIp: () => "203.0.113.7",
|
|
securityLog: () => { },
|
|
console: { log() { }, warn() { }, error() { } },
|
|
// adpanel:per-limiter-redis-stores — the swept limiter references the
|
|
// boot-time Redis client and the store factory; the harness has no
|
|
// Redis, so a null client yields the MemoryStore fallback (store:
|
|
// undefined), the same shape a Redis-less boot takes.
|
|
redisClient: null,
|
|
buildSharedRateLimitRedisStore: () => undefined,
|
|
buildAssistantRedisStore: () => undefined,
|
|
};
|
|
const policies = require("../services/settings-rate-limiters");
|
|
const options = [];
|
|
policies.createSettingsRateLimiters({ rateLimit: (config) => { options.push(config); return () => {}; }, securityLog() {} });
|
|
captured = options[Object.keys(policies.SETTINGS_OPERATION_POLICIES).indexOf("serverReinstallRateLimiter") * 2 + 1];
|
|
|
|
assert.ok(captured, "limiter definition did not run");
|
|
assert.equal(captured.windowMs, 10 * 60 * 1000);
|
|
assert.equal(captured.max, 5);
|
|
assert.equal(captured.skip({ session: null }), true);
|
|
assert.equal(captured.skip({ session: { user: "user@example.com" } }), false);
|
|
|
|
const req = { session: { user: "User@Example.com" }, sessionID: "sid-1" };
|
|
assert.equal(captured.keyGenerator(req), captured.keyGenerator({ ...req, ip: "198.51.100.2" }));
|
|
assert.notEqual(captured.keyGenerator(req), captured.keyGenerator({ ...req, sessionID: "other" }));
|
|
|
|
let statusCode = 0;
|
|
let payload = null;
|
|
const res = {
|
|
status(code) {
|
|
statusCode = code;
|
|
return { json(p) { payload = p; } };
|
|
},
|
|
};
|
|
captured.handler(req, res);
|
|
assert.equal(statusCode, 429);
|
|
assert.equal(payload.code, "reinstall-rate-limit");
|
|
});
|
|
|
|
test("limiter is defined before and mounted on the reinstall route", () => {
|
|
const limiterAt = indexSource.indexOf("const settingsRateLimiters = createSettingsRateLimiters(");
|
|
const routeAt = indexSource.indexOf('app.post("/api/servers/:name/reinstall"');
|
|
assert.ok(limiterAt >= 0 && routeAt > limiterAt, "limiter must be defined before the route uses it");
|
|
});
|
|
|
|
// The token helpers (safeCompare .. requireActionTokenOr403) form one
|
|
// contiguous region in index.js ending right before readJson. The one-time
|
|
// reinstall token's nonce is claimed through the durable consumed-token
|
|
// machinery (claimActionNonce → claimSessionRevokeTargetToken), so that
|
|
// region is eval'd too, with the globals it reads injected (values mirror
|
|
// index.js: SESSION_REVOKE_TARGET_TOKEN_TTL_MS = 10 min; no redisClient in
|
|
// the sandbox routes the claim through the process-local Map path).
|
|
function buildTokenSandbox() {
|
|
const start = indexSource.indexOf("function safeCompare(a, b) {");
|
|
const endMarker = "function readJson(file, fallback) {";
|
|
const end = indexSource.indexOf(endMarker);
|
|
assert.ok(start >= 0 && end > start, "token helper region not found");
|
|
|
|
const claimStart = indexSource.indexOf('const CONSUMED_ACTION_TOKEN_REDIS_PREFIX =');
|
|
const claimEndMarker = "// Single-use consumption.";
|
|
const claimEnd = indexSource.indexOf(claimEndMarker);
|
|
assert.ok(claimStart >= 0 && claimEnd > claimStart, "consumed-token claim region not found");
|
|
|
|
const sandbox = {
|
|
crypto,
|
|
Buffer,
|
|
Date,
|
|
console: { log() { }, warn() { }, error() { } },
|
|
// The sliced region also evaluates SSH_TERM_TOKEN_SECRET at definition
|
|
// time; its fallback HMAC needs SESSION_SECRET to exist.
|
|
process: { env: { ACTION_TOKEN_SECRET: "test-action-token-secret", SESSION_SECRET: "test-session-secret" } },
|
|
// Globals the durable claim slice reads at definition/runtime time.
|
|
SESSION_REVOKE_TARGET_TOKEN_TTL_MS: 10 * 60 * 1000,
|
|
redisClient: undefined,
|
|
getSessionDisplayId: (id) => String(id || ""),
|
|
};
|
|
vm.createContext(sandbox);
|
|
// Claim machinery first: claimActionNonce in the token slice resolves it.
|
|
vm.runInContext(indexSource.slice(claimStart, claimEnd), sandbox);
|
|
vm.runInContext(indexSource.slice(start, end), sandbox);
|
|
return sandbox;
|
|
}
|
|
|
|
test("reinstall action token: valid token verifies once; replay, wrong server, wrong session, expired and missing all fail", async () => {
|
|
const sandbox = buildTokenSandbox();
|
|
const out = await vm.runInContext(`
|
|
(async () => {
|
|
const ACTION = "POST /api/servers/:name/reinstall";
|
|
const RES = { serverName: "my-server" };
|
|
const reqOk = { session: { user: "user@example.com" }, sessionID: "sess-1", get: () => null, body: {} };
|
|
const mint = (req) => issueActionToken(req, ACTION, RES, { ttlSeconds: 120, oneTime: true });
|
|
|
|
const token = mint(reqOk);
|
|
const stranger = { session: { user: "user@example.com" }, sessionID: "sess-2", get: () => null, body: {} };
|
|
|
|
return ({
|
|
first: await verifyActionToken(reqOk, token, ACTION, RES),
|
|
replay: await verifyActionToken(reqOk, token, ACTION, RES),
|
|
wrongServer: await verifyActionToken(reqOk, mint(reqOk), ACTION, { serverName: "other-server" }),
|
|
wrongAction: await verifyActionToken(reqOk, mint(reqOk), "POST /api/servers/:bot/template", RES),
|
|
wrongSession: await verifyActionToken(stranger, mint(reqOk), ACTION, RES),
|
|
expired: await verifyActionToken(reqOk, issueActionToken(reqOk, ACTION, RES, { ttlSeconds: -1, oneTime: true }), ACTION, RES),
|
|
missing: await verifyActionToken(reqOk, null, ACTION, RES),
|
|
});
|
|
})()
|
|
`, sandbox);
|
|
|
|
assert.equal(out.first, true, "a freshly minted one-time token must verify");
|
|
assert.equal(out.replay, false, "one-time token replay must fail (nonce consumed)");
|
|
assert.equal(out.wrongServer, false, "token bound to another server name must fail");
|
|
assert.equal(out.wrongAction, false, "token bound to another action must fail");
|
|
assert.equal(out.wrongSession, false, "token bound to another session id must fail");
|
|
assert.equal(out.expired, false, "expired token must fail");
|
|
assert.equal(out.missing, false, "missing token must fail");
|
|
});
|
|
|
|
test("requireActionTokenOr403 responds 403 'invalid or missing action token' without a token", async () => {
|
|
const sandbox = buildTokenSandbox();
|
|
const out = await vm.runInContext(`
|
|
(async () => {
|
|
const calls = { status: null, payload: null };
|
|
const res = { status(c) { calls.status = c; return { json(p) { calls.payload = p; } }; } };
|
|
const req = { session: { user: "user@example.com" }, sessionID: "sess-1", get: () => null, body: {} };
|
|
const ok = await requireActionTokenOr403(req, res, "POST /api/servers/:name/reinstall", { serverName: "my-server" });
|
|
return ({ ok, status: calls.status, payload: calls.payload });
|
|
})()
|
|
`, sandbox);
|
|
|
|
assert.equal(out.ok, false);
|
|
assert.equal(out.status, 403);
|
|
assert.equal(out.payload.error, "invalid or missing action token");
|
|
});
|
|
|
|
test("reinstall route wiring: limiter middleware, action token gate, fresh-proof step-up before the node call", () => {
|
|
const route = extractRoute(
|
|
indexSource,
|
|
'app.post("/api/servers/:name/reinstall"',
|
|
'app.patch("/api/settings/servers/:name/resources"'
|
|
);
|
|
|
|
assert.match(
|
|
route,
|
|
/app\.post\("\/api\/servers\/:name\/reinstall", serverReinstallRateLimiter, async/,
|
|
"route must mount the dedicated reinstall rate limiter"
|
|
);
|
|
assert.match(
|
|
route,
|
|
/requireActionTokenOr403\(req, res, "POST \/api\/servers\/:name\/reinstall", \{ serverName: name \}\)/,
|
|
"route must verify the one-time server-scoped action token"
|
|
);
|
|
assert.match(
|
|
route,
|
|
/requireDestructiveActionStepUp\(req, res, currentUser, `Server reinstall "\$\{entry\.name \|\| name\}"/,
|
|
"route must run the destructive-action step-up"
|
|
);
|
|
assert.match(route, /scopeKey: `server:\$\{entry\.name \|\| name\}`/, "step-up grant scope must be the server");
|
|
assert.match(route, /persistGrant: false/, "reinstall must never mint a reusable grace grant");
|
|
|
|
const stepUpAt = route.indexOf("requireDestructiveActionStepUp(");
|
|
const nodeSigningAt = route.indexOf("signPanelAdminReinstallHeaders(");
|
|
const nodeCallAt = route.indexOf("callAuthorizedReinstall(");
|
|
assert.ok(stepUpAt > -1 && nodeSigningAt > stepUpAt, "step-up must run before the node request is signed");
|
|
assert.ok(stepUpAt > -1 && nodeCallAt > stepUpAt, "step-up must run before the node request is sent");
|
|
const serviceSource = fs.readFileSync(path.join(ROOT, "utils", "server-reinstall.js"), "utf8");
|
|
assert.match(serviceSource, /return deps\.httpRequestJsonPruningUnknownFields\(url, "POST", headers, payload, REINSTALL_NODE_TIMEOUT_MS, "node-reinstall",/,
|
|
"shared dispatch must retain the hardened transport, payload and long-operation timeout");
|
|
});
|
|
|
|
test("permissions route mints a one-time reinstallServer token under server_reinstall", () => {
|
|
const mintBlock = extractBlock(
|
|
indexSource,
|
|
"if (perms.server_reinstall) {\n // F2: one-time"
|
|
);
|
|
assert.match(
|
|
mintBlock,
|
|
/actionTokens\.reinstallServer = issueActionToken\(req, "POST \/api\/servers\/:name\/reinstall", \{ serverName \}, \{ ttlSeconds: 120, oneTime: true \}\)/
|
|
);
|
|
});
|
|
|
|
test("reinstall controller: one-time token on every attempt, step-up codes handled, credential sent on retry", () => {
|
|
assert.match(
|
|
botSource,
|
|
/ONE_TIME_SERVER_ACTION_TOKENS = new Set\(\[[^\]]*'reinstallServer'[^\]]*\]\)/,
|
|
"reinstallServer must be treated as a one-time token client-side"
|
|
);
|
|
assert.match(
|
|
reinstallSource,
|
|
/fetchWithServerActionToken\(`\/api\/servers\/\$\{encodeURIComponent\(serverName\)\}\/reinstall`[\s\S]*?'reinstallServer', \{ refreshBefore: true \}\)/,
|
|
"each attempt must fetch a fresh one-time token (the server consumes it even on a 403)"
|
|
);
|
|
assert.match(
|
|
reinstallSource,
|
|
/REINSTALL_STEPUP_CODES = \['password-required', '2fa-required', 'invalid-password', 'invalid-2fa'\]/
|
|
);
|
|
assert.match(reinstallSource, /body\.currentPassword = reinstallCredentialInput\?\.value/);
|
|
assert.match(reinstallSource, /body\.twoFactorCode = \(reinstallCredentialInput\?\.value \|\| ''\)\.replace\(\/\\D\/g, ''\)/);
|
|
assert.match(
|
|
reinstallSource,
|
|
/function openReinstallModal\(\) \{[\s\S]*?reinstallResetCredentialStep\(\);[\s\S]*?showModalElement\(reinstallModal\);/,
|
|
"credential field must be reset when the modal reopens"
|
|
);
|
|
assert.match(botSource, /"open-reinstall": \(\) => reinstallController\.open\(\)/);
|
|
assert.match(botSource, /window\.ADPanelReinstall\.createReinstallController\(/);
|
|
assert.match(botEjsSource, /<script nonce="<%= cspNonce %>" data-cfasync="false" src="\/js\/server-reinstall\.js\?v=<%= assetVersion %>-[\w-]+" defer><\/script>/);
|
|
assert.ok(botEjsSource.indexOf("/js/server-reinstall.js") < botEjsSource.indexOf("/js/bot.js"));
|
|
});
|
|
|
|
test("remote power actions do not fall back to the socket after a lost reply", async () => {
|
|
const start = botSource.indexOf("async function requestHttpServerAction(");
|
|
const end = botSource.indexOf("async function apiAction(", start);
|
|
let socketCalls = 0;
|
|
let deadlineMs;
|
|
let deadlineController;
|
|
let requestSignal;
|
|
const sandbox = {
|
|
normalizeAiServerNameCandidate: (name) => name,
|
|
normalizeServerPowerAction: (action) => action,
|
|
createServerActionError: (code, message) => Object.assign(new Error(message), { code }),
|
|
requestSocketServerAction: async () => { socketCalls += 1; return { confirmed: true, via: "socket" }; },
|
|
AbortSignal: {
|
|
timeout(ms) {
|
|
deadlineMs = ms;
|
|
deadlineController = new AbortController();
|
|
return deadlineController.signal;
|
|
},
|
|
},
|
|
fetch: async () => { throw new TypeError("Failed to fetch"); },
|
|
};
|
|
vm.runInNewContext(botSource.slice(start, end), sandbox);
|
|
await assert.rejects(sandbox.requestHttpServerAction("alpha", "start"), { code: "server_action_result_unconfirmed" });
|
|
assert.equal(deadlineMs, 250_000);
|
|
sandbox.fetch = async (_url, { signal }) => {
|
|
requestSignal = signal;
|
|
return {
|
|
ok: true, status: 200,
|
|
json: async () => {
|
|
deadlineController.abort();
|
|
throw signal.reason;
|
|
},
|
|
};
|
|
};
|
|
await assert.rejects(sandbox.requestHttpServerAction("alpha", "kill"), { code: "server_action_result_unconfirmed" });
|
|
assert.equal(deadlineMs, 25_000);
|
|
assert.equal(requestSignal, deadlineController.signal);
|
|
assert.equal(requestSignal.aborted, true);
|
|
assert.equal(socketCalls, 0);
|
|
|
|
sandbox.fetch = async () => ({ ok: false, status: 400, json: async () => ({ error: "not_remote" }) });
|
|
assert.deepEqual(await sandbox.requestHttpServerAction("alpha", "start"), { confirmed: true, via: "socket" });
|
|
assert.equal(socketCalls, 1);
|
|
});
|
|
|
|
test("bot.ejs confirm view carries the credential step", () => {
|
|
assert.match(botEjsSource, /id="reinstallCredentialBlock"/);
|
|
assert.match(botEjsSource, /id="reinstallCredentialLabel"/);
|
|
assert.match(botEjsSource, /id="reinstallCredentialInput"/);
|
|
assert.match(botEjsSource, /id="reinstallCredentialError"/);
|
|
assert.match(botEjsSource, /autocomplete="current-password"/);
|
|
});
|
|
|
|
const REINSTALL_TEST_NODE_ID = `reinstall-fixture-${process.pid}`;
|
|
|
|
function buildReinstallRouteHarness() {
|
|
const captured = { handler: null, nodeCalls: [], saves: [], activities: [], releases: [], cachedStatuses: [], dispatch: null };
|
|
const entry = { rowId: 1, name: "alpha", nodeId: REINSTALL_TEST_NODE_ID, template: "custom", port: 25000, startupCommand: "legacy" };
|
|
const sandbox = {
|
|
...require("../utils/server-reinstall"),
|
|
console: { log() {}, error() {}, warn() {} },
|
|
app: { post: (...args) => { captured.handler = args.at(-1); } },
|
|
serverReinstallRateLimiter() {},
|
|
isAuthenticated: async () => true,
|
|
isAdmin: async () => true,
|
|
requireActionTokenOr403: async () => true,
|
|
userHasAccessToServer: async () => true,
|
|
getEffectivePermsForUserOnServer: async () => ({ server_reinstall: true }),
|
|
findServer: async () => entry,
|
|
db: {
|
|
query: async (sql, values) => {
|
|
if (sql.startsWith("INSERT INTO server_reinstall_dispatch")) {
|
|
assert.equal(captured.dispatch, null);
|
|
const [operation_id, host_port, template_id, intent] = values;
|
|
captured.dispatch = { operation_id, host_port, template_id, intent };
|
|
return { affectedRows: 1 };
|
|
}
|
|
if (sql.startsWith("DELETE FROM server_reinstall_dispatch")) {
|
|
assert.equal(captured.dispatch?.operation_id, values[1]);
|
|
captured.dispatch = null;
|
|
return { affectedRows: 1 };
|
|
}
|
|
return [entry];
|
|
},
|
|
pool: { getConnection: async () => ({
|
|
beginTransaction: async () => {}, commit: async () => {}, rollback: async () => {}, release() {},
|
|
async execute(sql, values) {
|
|
if (sql.startsWith("DELETE FROM server_reinstall_dispatch")) return [await sandbox.db.query(sql, values)];
|
|
const [port, template, start, runtime, docker, rowId] = values;
|
|
if (sql.startsWith("SELECT")) {
|
|
const current = sandbox.freshList.find((record) => record.name === port);
|
|
return [current ? [{ ...current, status: "reinstalling" }] : []];
|
|
}
|
|
const current = sandbox.freshList.find((record) => record.rowId === rowId);
|
|
const updated = { ...current, port, template, start, runtime: JSON.parse(runtime), docker: JSON.parse(docker) };
|
|
delete updated.startupCommand;
|
|
return [{ affectedRows: await sandbox.saveReinstallRow(updated) ? 1 : 0 }];
|
|
},
|
|
}) },
|
|
},
|
|
isServerSuspended: () => false,
|
|
isRemoteEntry: () => true,
|
|
findUserByEmail: async () => ({ id: 7, email: "admin@example.com", admin: true, password: "synthetic-password-hash" }),
|
|
isSessionSidRevoked: async () => false,
|
|
requireDestructiveActionStepUp: async () => ({ ok: true }),
|
|
findNodeByIdOrName: async () => ({ id: REINSTALL_TEST_NODE_ID, ports: { mode: "range", start: 30001, count: 10 } }),
|
|
buildNodeBaseUrl: () => "https://node.invalid:8080",
|
|
nodeUnderCloudflare: () => false,
|
|
nodeAuthHeadersFor: () => ({}),
|
|
claimReinstallOperation: async () => ({ ok: true, prevStatus: "stopped" }),
|
|
releaseReinstallOperation: async (...args) => { captured.releases.push(args); return { restored: true }; },
|
|
setCachedServerStatus: async (...args) => { captured.cachedStatuses.push(args); },
|
|
normalizeTemplateId: (value) => value,
|
|
dockerConfigForNodeRequest: (value) => value || null,
|
|
findFreeNodePoolPort: async () => 30005,
|
|
findServerUsingNodePort: async () => null,
|
|
signPanelAdminReinstallHeaders: () => true,
|
|
stripLogControlChars: (value) => value,
|
|
isLegacySigningRejection: () => false,
|
|
httpRequestJson: async () => ({ status: 0, json: null }),
|
|
httpRequestJsonPruningUnknownFields: async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
return { res: { status: 200, json: { ok: true } } };
|
|
},
|
|
withServersIndexWriteLock: (operation) => operation(),
|
|
freshList: [entry],
|
|
mapServerRow: (row) => row,
|
|
toDbJson: (value) => value == null ? null : JSON.stringify(value),
|
|
invalidateServerIndexCache() {},
|
|
saveResult: true,
|
|
saveReinstallRow: async (row) => { captured.saves.push([row]); return sandbox.saveResult; },
|
|
recordActivity: async (...args) => { captured.activities.push(args); },
|
|
maskPlannerEmailToLocalPart: () => "admin",
|
|
getRequestIp: () => "127.0.0.1",
|
|
};
|
|
for (const marker of ["function validatePort(port)", "function isPortInNodeAllocation(node, port)"]) {
|
|
vm.runInNewContext(extractBlock(indexSource, marker), sandbox);
|
|
}
|
|
vm.runInNewContext(extractRoute(indexSource,
|
|
'app.post("/api/servers/:name/reinstall"',
|
|
'app.patch("/api/settings/servers/:name/resources"'), sandbox);
|
|
const request = { params: { name: "alpha" }, session: { user: "admin@example.com" }, sessionID: "synthetic-session-id", body: {} };
|
|
const response = {
|
|
statusCode: 200, body: null, headersSent: false,
|
|
status(code) { this.statusCode = code; return this; },
|
|
json(body) { assert.equal(this.headersSent, false, "response must settle once"); this.body = body; this.headersSent = true; return this; },
|
|
};
|
|
return { sandbox, captured, request, response };
|
|
}
|
|
|
|
test("reinstall route: current runtime settings override the original template", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
const entry = sandbox.freshList[0];
|
|
entry.template = "nodejs";
|
|
entry.docker = { image: "node", tag: "20-alpine", command: "node index.js", volumes: ["{SERVER_DIR}:/app"] };
|
|
entry.runtime = { image: "node", tag: "22-alpine", command: "node server.js" };
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 200);
|
|
const docker = captured.nodeCalls[0][3].docker;
|
|
assert.equal(docker.tag, "22-alpine");
|
|
assert.equal(docker.command, "node server.js");
|
|
assert.equal(docker.volumes[0], "{SERVER_DIR}:/app");
|
|
});
|
|
|
|
test("reinstall route: current Minecraft Java selection overrides the original template", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
const entry = sandbox.freshList[0];
|
|
entry.template = "minecraft";
|
|
entry.docker = { javaVersion: "17" };
|
|
entry.runtime = { javaVersion: "21" };
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(captured.nodeCalls[0][3].javaVersion, "21");
|
|
});
|
|
|
|
test("reinstall route: missing stored port must not bypass an exhausted allocation pool", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.freshList[0].port = null;
|
|
sandbox.findFreeNodePoolPort = async () => null;
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 409, "an exhausted pool must refuse before the server is wiped");
|
|
assert.equal(captured.nodeCalls.length, 0);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: missing and malformed ports are strictly rebound and committed", async () => {
|
|
for (const storedPort of [null, undefined, "", 0, -1, "30001junk", "30001.5", 30001.5, "030001", 70000]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.freshList[0].port = storedPort;
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 200, `invalid legacy port ${storedPort} must use a checked allocation`);
|
|
assert.equal(captured.nodeCalls.length, 1);
|
|
assert.equal(captured.nodeCalls[0][3].hostPort, 30005);
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.equal(captured.releases.length, 1);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: valid allocated ports are normalized without consulting the allocator", async () => {
|
|
for (const storedPort of [30001, "30001"]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.freshList[0].port = storedPort;
|
|
sandbox.findFreeNodePoolPort = async () => { throw new Error("existing allocation must win"); };
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(captured.nodeCalls[0][3].hostPort, 30001);
|
|
assert.equal(captured.saves[0][0].port, 30001);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: a duplicate stored allocation is refused before the node call", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.freshList[0].port = 30001;
|
|
sandbox.findServerUsingNodePort = async (node, port, excludeName) => {
|
|
assert.equal(node.id, REINSTALL_TEST_NODE_ID);
|
|
assert.equal(port, 30001);
|
|
assert.equal(excludeName, "alpha");
|
|
return { name: "other", status: "stopped" };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 409);
|
|
assert.equal(captured.nodeCalls.length, 0);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: concurrent rebindings serialize selection through the index commit", async () => {
|
|
const first = buildReinstallRouteHarness();
|
|
const second = buildReinstallRouteHarness();
|
|
const { withKeyedLock } = require("../utils/keyed-async-lock");
|
|
let recorded = false;
|
|
let completeFirst;
|
|
let signalFirst;
|
|
const firstEntered = new Promise((resolve) => { signalFirst = resolve; });
|
|
const firstComplete = new Promise((resolve) => { completeFirst = resolve; });
|
|
for (const harness of [first, second]) {
|
|
harness.sandbox.withKeyedLock = withKeyedLock;
|
|
harness.sandbox.findFreeNodePoolPort = async () => recorded ? null : 30005;
|
|
}
|
|
first.sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
first.captured.nodeCalls.push(args);
|
|
signalFirst();
|
|
await firstComplete;
|
|
return { res: { status: 200, json: { ok: true } } };
|
|
};
|
|
first.sandbox.saveReinstallRow = async (row) => {
|
|
first.captured.saves.push([row]);
|
|
recorded = true;
|
|
return true;
|
|
};
|
|
second.sandbox.freshList[0].name = "beta";
|
|
second.request.params.name = "beta";
|
|
const firstAttempt = first.captured.handler(first.request, first.response);
|
|
await firstEntered;
|
|
const secondAttempt = second.captured.handler(second.request, second.response);
|
|
let prematureNodeCalls;
|
|
try {
|
|
await new Promise(setImmediate);
|
|
prematureNodeCalls = second.captured.nodeCalls.length;
|
|
} finally {
|
|
completeFirst();
|
|
await Promise.all([firstAttempt, secondAttempt]);
|
|
}
|
|
assert.equal(prematureNodeCalls, 0, "the second reinstall must not wipe while the first port claim is pending");
|
|
assert.equal(first.response.statusCode, 200);
|
|
assert.equal(second.response.statusCode, 409, "the committed first allocation exhausts the pool");
|
|
assert.equal(second.captured.nodeCalls.length, 0);
|
|
assert.equal(second.captured.saves.length, 0);
|
|
assert.equal(first.captured.releases.length, 1);
|
|
assert.equal(second.captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: verified HTTPS is required before probing or dispatching to the node", async (t) => {
|
|
const { configureNodeHttp } = require("../services/node-http");
|
|
const previousSetting = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
|
|
t.after(() => {
|
|
configureNodeHttp({ getNodeMtlsAgent: () => null });
|
|
if (previousSetting === undefined) delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
|
|
else process.env.NODE_TLS_REJECT_UNAUTHORIZED = previousSetting;
|
|
});
|
|
for (const [url, agentOptions, bypassCa] of [
|
|
["http://node.invalid:8080"],
|
|
["https://node.invalid:8080", { checkServerIdentity: () => undefined }],
|
|
["https://node.invalid:8080", { rejectUnauthorized: false }],
|
|
["https://node.invalid:8080", null, true],
|
|
]) {
|
|
configureNodeHttp({ getNodeMtlsAgent: () => agentOptions && { options: agentOptions } });
|
|
if (bypassCa) process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
|
|
else delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.buildNodeBaseUrl = () => url;
|
|
sandbox.nodeAuthHeadersFor = () => assert.fail("refusal must precede node credential use");
|
|
sandbox.findFreeNodePoolPort = async () => assert.fail("refusal must precede port probes");
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 503);
|
|
assert.equal(response.body.code, "reinstall-insecure-node-transport");
|
|
assert.equal(captured.nodeCalls.length, 0);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: a deleted or substituted node is refused before the wipe", async () => {
|
|
const originalNode = { id: REINSTALL_TEST_NODE_ID, uuid: "original-node" };
|
|
for (const refreshed of [null, { id: "different-id", name: originalNode.id }, { ...originalNode, uuid: "different-node" }]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
let lookups = 0;
|
|
sandbox.findNodeByIdOrName = async () => lookups++ === 0 ? originalNode : refreshed;
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 400);
|
|
assert.equal(captured.nodeCalls.length, 0);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
}
|
|
});
|
|
|
|
test("reinstall commit writes only the claimed server and never saves a full index snapshot", async () => {
|
|
const { commitCompletedReinstall } = require("../utils/server-reinstall");
|
|
const target = { rowId: 13, name: "alpha", nodeId: REINSTALL_TEST_NODE_ID, status: "reinstalling",
|
|
port: 25000, suspended: true, acl: { existing: true }, resources: { storageMb: 1024 } };
|
|
const steps = [];
|
|
const connection = {
|
|
async beginTransaction() { steps.push("begin"); },
|
|
async execute(sql, args) {
|
|
if (sql.startsWith("SELECT")) {
|
|
assert.match(sql, /WHERE name = \? FOR UPDATE$/);
|
|
assert.deepEqual(args, ["alpha"]);
|
|
steps.push("read");
|
|
return [[target]];
|
|
}
|
|
assert.match(sql, /^UPDATE servers SET port = \?, template = \?, start = \?, runtime = \?, docker = \? WHERE id = \?$/);
|
|
assert.equal(args[0], 30005);
|
|
assert.equal(args.at(-1), 13);
|
|
steps.push("update");
|
|
return [{ affectedRows: 1 }];
|
|
},
|
|
async commit() { steps.push("commit"); },
|
|
async rollback() { steps.push("rollback"); },
|
|
release() { steps.push("release"); },
|
|
};
|
|
const result = await commitCompletedReinstall({
|
|
db: { pool: { getConnection: async () => connection } },
|
|
mapServerRow: (row) => row,
|
|
toDbJson: (value) => value == null ? null : JSON.stringify(value),
|
|
withServersIndexWriteLock: (operation) => operation(),
|
|
invalidateServerIndexCache: () => steps.push("invalidate"),
|
|
logger: { error() {} },
|
|
}, target, { reboundHostPort: 30005 });
|
|
assert.equal(result.ok, true);
|
|
assert.deepEqual(result.server, { ...target, port: 30005 });
|
|
assert.deepEqual(steps, ["begin", "read", "update", "commit", "invalidate", "release"]);
|
|
});
|
|
|
|
test("reinstall recovery: absent dispatch uses verified power without saving the proposed runtime", async () => {
|
|
const { recoverPendingReinstall } = require("../utils/server-reinstall");
|
|
const entry = { rowId: 13, name: "alpha", nodeId: REINSTALL_TEST_NODE_ID, status: "reinstalling", port: 30001 };
|
|
const operationId = "a".repeat(32);
|
|
const dispatch = { operation_id: operationId, host_port: 30005, template_id: "custom", intent: {
|
|
technicalName: entry.name, nodeUuid: entry.nodeId, acceptUntil: Date.now() - 1, update: { template: "custom" },
|
|
} };
|
|
for (const powerState of ["running", "stopped", undefined]) {
|
|
const expectedStatus = powerState || "unknown";
|
|
const writes = [];
|
|
const connection = {
|
|
async beginTransaction() {}, async rollback() {}, release() {},
|
|
async execute(sql, args) {
|
|
if (sql.startsWith("SELECT")) return [[entry]];
|
|
assert.match(sql, /^(DELETE FROM server_reinstall_dispatch|UPDATE servers SET status =)/);
|
|
writes.push(args);
|
|
return [{ affectedRows: 1 }];
|
|
},
|
|
async commit() { writes.push("commit"); },
|
|
};
|
|
const handled = await recoverPendingReinstall({
|
|
db: { query: async () => [dispatch], pool: { getConnection: async () => connection } },
|
|
findServer: async () => entry,
|
|
findNodeByIdOrName: async () => ({ id: entry.nodeId }),
|
|
buildNodeBaseUrl: () => "https://node.invalid:8080",
|
|
nodeUnderCloudflare: () => false,
|
|
nodeAuthHeadersFor: () => ({}),
|
|
httpRequestJson: async () => ({ status: 200, json: { operationId, state: "absent", powerState } }),
|
|
withServersIndexWriteLock: (operation) => operation(),
|
|
mapServerRow: (row) => row,
|
|
invalidateServerIndexCache() {},
|
|
setCachedServerStatus: async (...args) => { writes.push(args); },
|
|
}, entry.name);
|
|
assert.equal(handled, true);
|
|
assert.deepEqual(writes, [
|
|
[entry.rowId, operationId], [expectedStatus, entry.rowId], "commit",
|
|
[entry.name, { nodeId: entry.nodeId, status: expectedStatus }],
|
|
]);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: allocation changes while waiting use the freshly loaded node pool", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
let lookups = 0;
|
|
sandbox.freshList[0].port = 30001;
|
|
sandbox.findNodeByIdOrName = async () => ({ id: REINSTALL_TEST_NODE_ID, ports: {
|
|
mode: "range", start: lookups++ === 0 ? 30001 : 31001, count: 1,
|
|
} });
|
|
sandbox.findFreeNodePoolPort = async () => 31001;
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(captured.nodeCalls[0][3].hostPort, 31001);
|
|
assert.equal(captured.saves[0][0].port, 31001);
|
|
});
|
|
|
|
test("reinstall node-port lock: lookup and operation failures release the shared lock", async () => {
|
|
const { withReinstallNodePortLock } = require("../utils/server-reinstall");
|
|
const node = { id: REINSTALL_TEST_NODE_ID };
|
|
await assert.rejects(withReinstallNodePortLock({ findNodeByIdOrName: async () => {
|
|
throw new Error("node lookup unavailable");
|
|
} }, node, async () => assert.fail("failed lookup must not run the operation")), /node lookup unavailable/);
|
|
await assert.rejects(withReinstallNodePortLock({ findNodeByIdOrName: async () => node }, node,
|
|
async () => { throw new Error("rebuild failed"); }), /rebuild failed/);
|
|
const result = await withReinstallNodePortLock({ findNodeByIdOrName: async () => node }, node, async () => "completed");
|
|
assert.equal(result, "completed");
|
|
});
|
|
|
|
test("reinstall node-port lock: a busy shared node lock refuses without queuing another operation", async () => {
|
|
const { withReinstallNodePortLock } = require("../utils/server-reinstall");
|
|
const { withKeyedLock } = require("../utils/keyed-async-lock");
|
|
const node = { id: REINSTALL_TEST_NODE_ID };
|
|
let releaseOwner;
|
|
const ownerHeld = new Promise((resolve) => { releaseOwner = resolve; });
|
|
const owner = withKeyedLock(`node-ports:${node.id}`, () => ownerHeld);
|
|
let lookups = 0;
|
|
let operations = 0;
|
|
try {
|
|
const refused = withReinstallNodePortLock({ findNodeByIdOrName: async () => {
|
|
lookups += 1;
|
|
return node;
|
|
} }, node, async () => { operations += 1; });
|
|
assert.equal(refused.ok, false, "busy admission must settle synchronously, never wait for the owner");
|
|
assert.equal(refused.statusCode, 409);
|
|
assert.equal(refused.code, "node_port_operation_in_progress");
|
|
assert.equal(lookups, 0);
|
|
} finally {
|
|
releaseOwner();
|
|
await owner;
|
|
await new Promise(setImmediate);
|
|
}
|
|
assert.equal(operations, 0, "a refused reinstall must not execute when the original owner releases");
|
|
});
|
|
|
|
test("reinstall node-port lock: another worker must honor the shared allocation lock", async () => {
|
|
const { spawnSync } = require("node:child_process");
|
|
const { randomUUID } = require("node:crypto");
|
|
const { withKeyedLock } = require("../utils/keyed-async-lock");
|
|
const nodeId = `reinstall-test-${randomUUID()}`;
|
|
const runWorker = () => {
|
|
const worker = spawnSync(process.execPath, ["-e", `
|
|
const { withReinstallNodePortLock } = require(process.argv[1]);
|
|
const node = { id: process.argv[2] };
|
|
Promise.resolve(withReinstallNodePortLock({ findNodeByIdOrName: async () => node }, node,
|
|
async () => ({ ok: true }))).then((result) => process.stdout.write(JSON.stringify(result)));
|
|
`, require.resolve("../utils/server-reinstall"), nodeId], { encoding: "utf8", timeout: 5000 });
|
|
assert.equal(worker.status, 0, worker.error?.message || worker.stderr);
|
|
return JSON.parse(worker.stdout);
|
|
};
|
|
|
|
await withKeyedLock(`node-ports:${nodeId}`, () => {
|
|
assert.equal(runWorker().code, "node_port_operation_in_progress");
|
|
});
|
|
assert.deepEqual(runWorker(), { ok: true });
|
|
});
|
|
|
|
test("reinstall route: completed Minecraft reinstall awaiting consent commits the port and reports the EULA", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.freshList[0].template = "minecraft";
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async () => ({ res: { status: 409, json: { ok: false, code: "minecraft_eula_required" } } });
|
|
await captured.handler(request, response);
|
|
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(response.body.ok, true);
|
|
assert.equal(response.body.eulaRequired, true);
|
|
assert.equal(response.body.powerState, "stopped");
|
|
assert.deepEqual(captured.releases, [["alpha", "stopped"]]);
|
|
assert.deepEqual(captured.cachedStatuses, [["alpha", { status: "stopped", nodeId: REINSTALL_TEST_NODE_ID }]]);
|
|
});
|
|
|
|
test("reinstall route: completed rebuild without a runtime does not restore a running status", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async () => ({ res: { status: 200, json: { ok: true, serverStopped: true } } });
|
|
await captured.handler(request, response);
|
|
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(response.body.ok, true);
|
|
assert.equal(response.body.powerState, "stopped");
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.deepEqual(captured.releases, [["alpha", "stopped"]]);
|
|
assert.deepEqual(captured.cachedStatuses, [["alpha", { status: "stopped", nodeId: REINSTALL_TEST_NODE_ID }]]);
|
|
});
|
|
|
|
test("reinstall route: failed index save cannot report a completed panel operation", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.saveResult = false;
|
|
await captured.handler(request, response);
|
|
|
|
assert.equal(captured.nodeCalls.length, 1);
|
|
assert.equal(captured.nodeCalls[0][3].hostPort, 30005);
|
|
assert.equal(captured.nodeCalls[0][4], 145 * 60 * 1000, "panel must wait longer than the node's reinstall deadline");
|
|
assert.equal(captured.saves.length, 1);
|
|
assert.equal(response.statusCode, 500);
|
|
assert.equal(response.body.code, "reinstall-index-save-failed");
|
|
assert.equal(response.body.reinstalled, true);
|
|
assert.equal(captured.activities.length, 1);
|
|
assert.deepEqual(captured.activities[0].slice(0, 4), ["alpha", "reinstall_failed", {
|
|
templateId: "custom", filesReplaced: true, code: "reinstall-index-save-failed",
|
|
}, "admin@example.com"]);
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: confirmed startup does not restore the old stopped status", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.httpRequestJsonPruningUnknownFields = async () => ({ res: { status: 200, json: { ok: true, serverStopped: false, serverRunning: true } } });
|
|
await captured.handler(request, response);
|
|
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(response.body.powerState, "running");
|
|
assert.deepEqual(captured.releases, [["alpha", "running"]]);
|
|
assert.deepEqual(captured.cachedStatuses, [["alpha", { status: "running", nodeId: REINSTALL_TEST_NODE_ID }]]);
|
|
});
|
|
|
|
test("reinstall route: a legacy non-stopped reply is not positive evidence of startup", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.httpRequestJsonPruningUnknownFields = async () => ({ res: { status: 200, json: { ok: true, serverStopped: false } } });
|
|
await captured.handler(request, response);
|
|
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(response.body.powerState, undefined);
|
|
assert.deepEqual(captured.releases, [["alpha", "stopped"]]);
|
|
assert.equal(captured.cachedStatuses.length, 0);
|
|
});
|
|
|
|
test("reinstall route: an installer refusal before the wipe keeps the current allocation and power state", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async () => ({ res: { status: 500, json: {
|
|
ok: false, code: "reinstall_install_failed", reinstalled: false, error: "Template installation failed. No server files were replaced.",
|
|
} } });
|
|
await captured.handler(request, response);
|
|
|
|
assert.equal(response.statusCode, 502);
|
|
assert.match(response.body.error, /No server files were replaced/);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.activities.length, 0);
|
|
assert.deepEqual(captured.releases, [["alpha", "running"]]);
|
|
assert.equal(captured.cachedStatuses.length, 0);
|
|
});
|
|
|
|
test("reinstall route: a confirmed daemon conflict returns 409 without a retry or index change", async () => {
|
|
for (const [code, error] of [
|
|
["server_op_in_progress", "server operation already in progress"],
|
|
["server_stop_in_progress", "server is stopping"],
|
|
["reinstall_template_mismatch", "The panel and node have different templates. No files were replaced."],
|
|
]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
return { res: { status: 409, json: { ok: false, code, error } } };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 409);
|
|
assert.equal(response.body.code, code);
|
|
assert.equal(response.body.error, error);
|
|
assert.equal(captured.nodeCalls.length, 1);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.deepEqual(captured.releases, [["alpha", "running"]]);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: lost or invalid node replies report an unconfirmed result without retrying or saving", async () => {
|
|
for (const result of [
|
|
{ status: 0, json: null }, { status: 502, json: null }, { status: 200, json: null },
|
|
{ status: 502, json: { ok: false, error: "bad gateway" } },
|
|
{ status: 503, json: { ok: false, error: "service unavailable" } },
|
|
{ status: 503, json: { ok: false, code: "reinstall_startup_pending" } },
|
|
{ status: 504, json: { ok: false, error: "gateway timeout" } },
|
|
]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
return { res: result };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 502);
|
|
assert.equal(response.body.code, "reinstall-result-unconfirmed");
|
|
assert.match(response.body.error, /may still be running or may have completed/);
|
|
assert.equal(captured.nodeCalls.length, 1);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.activities.length, 0);
|
|
assert.equal(captured.dispatch?.host_port, 30005);
|
|
assert.deepEqual(captured.releases, [["alpha", "running"]]);
|
|
assert.equal(captured.cachedStatuses.length, 0);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: a confirmed journal result reconciles the allocation without repeating POST", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
assert.equal(args[3].operationId, captured.dispatch.operation_id);
|
|
return { res: { status: 0 } };
|
|
};
|
|
sandbox.httpRequestJson = async (url, method) => {
|
|
assert.equal(method, "GET");
|
|
assert.equal(new URL(url).pathname, "/v1/servers/alpha/reinstall-result");
|
|
return { status: 200, json: {
|
|
operationId: captured.dispatch.operation_id, state: "completed", outcome: "running", powerState: "stopped", template: "custom", hostPort: 30005,
|
|
} };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(captured.nodeCalls.length, 1);
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.equal(captured.dispatch, null);
|
|
assert.equal(response.body.powerState, "stopped");
|
|
assert.deepEqual(captured.releases, [["alpha", "stopped"]]);
|
|
});
|
|
|
|
test("reinstall route: verified absence restores the observed power state without committing", async (t) => {
|
|
for (const powerState of ["running", "stopped", undefined]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
let now = Date.now();
|
|
const clock = t.mock.method(Date, "now", () => now);
|
|
try {
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "online" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async () => ({ res: { status: 0 } });
|
|
sandbox.httpRequestJson = async (url, method) => {
|
|
assert.equal(method, "GET");
|
|
const params = new URL(url).searchParams;
|
|
now = Number(params.get("acceptUntil")) + 1;
|
|
return { status: 200, json: { operationId: params.get("id"), state: "absent", powerState } };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 502);
|
|
assert.equal(response.body.code, "reinstall-not-applied");
|
|
assert.equal(captured.dispatch, null);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.deepEqual(captured.releases, [["alpha", powerState || "online"]]);
|
|
} finally {
|
|
clock.mock.restore();
|
|
}
|
|
}
|
|
});
|
|
|
|
test("reinstall route: a refusal after stopping the container does not commit the proposed port", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async () => ({ res: { status: 409, json: {
|
|
ok: false, serverStopped: true, error: "The old container was stopped. Required host port is in use; no server files were replaced",
|
|
} } });
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 502);
|
|
assert.match(response.body.error, /no server files were replaced/);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.activities.length, 0);
|
|
assert.deepEqual(captured.releases, [["alpha", "stopped"]]);
|
|
assert.deepEqual(captured.cachedStatuses, [["alpha", { status: "stopped", nodeId: REINSTALL_TEST_NODE_ID }]]);
|
|
});
|
|
|
|
test("reinstall route: rebuilt files with a failed start still commit the rebound port without reporting success", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
return { res: { status: 500, json: {
|
|
ok: false, code: "reinstall_start_failed", reinstalled: true,
|
|
error: "server files reinstalled but container failed to start",
|
|
} } };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 502);
|
|
assert.equal(response.body.ok, false);
|
|
assert.equal(response.body.reinstalled, true);
|
|
assert.equal(captured.saves.length, 1, "rebuilt node configuration must remain authoritative even if startup fails");
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.deepEqual(captured.activities.map((activity) => activity[1]), ["reinstall_failed"]);
|
|
assert.equal(captured.activities[0][2].code, "reinstall-start-failed");
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: an unverified Docker start keeps the committed allocation without claiming a power state", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.httpRequestJsonPruningUnknownFields = async () => ({ res: { status: 500, json: {
|
|
ok: false, code: "reinstall_start_unconfirmed", reinstalled: true, serverStopped: false,
|
|
} } });
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 502);
|
|
assert.equal(response.body.code, "reinstall-start-unconfirmed");
|
|
assert.equal(response.body.reinstalled, true);
|
|
assert.match(response.body.error, /files were replaced, but container startup could not be confirmed/);
|
|
assert.equal(captured.saves.length, 1);
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.equal(captured.cachedStatuses.length, 0);
|
|
});
|
|
|
|
test("reinstall route: confirmed image-pull failure records rebuilt allocation without another node request", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
return { res: { status: 500, json: { ok: false, code: "reinstall_image_pull_failed", reinstalled: true } } };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 502);
|
|
assert.equal(response.body.reinstalled, true);
|
|
assert.equal(response.body.code, "reinstall-image-pull-failed");
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.equal(captured.nodeCalls.length, 1);
|
|
assert.deepEqual(captured.activities.map((activity) => activity[1]), ["reinstall_failed"]);
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: incomplete wipe commits the new allocation but keeps the server stopped", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
return { res: { status: 500, json: { ok: false, code: "reinstall_cleanup_failed", reinstalled: true, serverStopped: true } } };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 502);
|
|
assert.equal(response.body.code, "reinstall-cleanup-failed");
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.equal(captured.nodeCalls.length, 1);
|
|
assert.deepEqual(captured.releases, [["alpha", "stopped"]]);
|
|
});
|
|
|
|
test("reinstall route: confirmed installer failure commits allocation without reporting success or retrying", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" });
|
|
sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
return { res: { status: 500, json: { ok: false, code: "reinstall_install_failed", reinstalled: true } } };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 502);
|
|
assert.equal(response.body.ok, false);
|
|
assert.equal(response.body.reinstalled, true);
|
|
assert.equal(response.body.code, "reinstall-install-failed");
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.equal(captured.nodeCalls.length, 1);
|
|
assert.deepEqual(captured.activities.map((activity) => activity[1]), ["reinstall_failed"]);
|
|
assert.deepEqual(captured.releases, [["alpha", "stopped"]]);
|
|
});
|
|
|
|
test("reinstall route: an ambiguous legacy storage owner refuses before the node wipe", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
const entry = sandbox.freshList[0];
|
|
entry.bot = "daemon-alpha";
|
|
sandbox.getTechnicalServerName = (server) => server.bot;
|
|
const journalQuery = sandbox.db.query;
|
|
sandbox.db.query = async (sql, args) => /server_reinstall_dispatch/.test(sql)
|
|
? journalQuery(sql, args) : [entry, { name: "daemon-alpha", bot: "other-storage" }];
|
|
await captured.handler(request, response);
|
|
|
|
assert.equal(response.statusCode, 409);
|
|
assert.equal(response.body.code, "reinstall-storage-conflict");
|
|
assert.equal(captured.nodeCalls.length, 0);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: configuration changes during step-up refuse before the node wipe", async () => {
|
|
for (const changed of [
|
|
{ template: "python", docker: { image: "python", tag: "3.12" } },
|
|
{ nodeId: "node2", port: 30008 },
|
|
]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
const updatedEntry = { ...sandbox.freshList[0], ...changed };
|
|
sandbox.requireDestructiveActionStepUp = async () => {
|
|
sandbox.freshList = [updatedEntry];
|
|
sandbox.findServer = async () => updatedEntry;
|
|
return { ok: true };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 409, "a stale authorized snapshot must not reach the daemon");
|
|
assert.equal(response.body.code, "reinstall-target-changed");
|
|
assert.equal(captured.nodeCalls.length, 0);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1, "refused target validation must release its claim");
|
|
}
|
|
});
|
|
|
|
test("reinstall route: target changes during port selection refuse before the node wipe", async () => {
|
|
for (const changed of [
|
|
{ suspended: true },
|
|
{ template: "python", docker: { image: "python", tag: "3.12" } },
|
|
{ resources: { storageMb: 1024 } },
|
|
{ port: 30008 },
|
|
]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
const updatedEntry = { ...sandbox.freshList[0], ...changed };
|
|
sandbox.findFreeNodePoolPort = async () => {
|
|
sandbox.freshList = [updatedEntry];
|
|
sandbox.findServer = async () => updatedEntry;
|
|
return 30005;
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 409, "a changed target must invalidate pending destructive dispatch");
|
|
assert.equal(response.body.code, "reinstall-target-changed");
|
|
assert.equal(captured.nodeCalls.length, 0, "no stale configuration may authorize a wipe");
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: authorization revoked during step-up refuses before the node wipe", async () => {
|
|
for (const scenario of ["access removed", "permission removed", "account suspended", "admin demoted", "password changed", "2fa changed", "account replaced", "session revoked", "sealed 2fa"]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
const actor = { id: 7, email: request.session.user, admin: scenario === "admin demoted",
|
|
suspended: false, password: "proved-password-hash", secret: null, session_epoch: 4 };
|
|
let liveActor = { ...actor };
|
|
let accessAllowed = true;
|
|
let permissionAllowed = true;
|
|
let sessionRevoked = false;
|
|
sandbox.isAdmin = async () => actor.admin;
|
|
sandbox.findUserByEmail = async () => ({ ...liveActor });
|
|
sandbox.isSessionSidRevoked = async () => sessionRevoked;
|
|
sandbox.userHasAccessToServer = async () => accessAllowed;
|
|
sandbox.getEffectivePermsForUserOnServer = async () => ({ server_reinstall: permissionAllowed });
|
|
sandbox.requireDestructiveActionStepUp = async () => {
|
|
if (scenario === "access removed") accessAllowed = false;
|
|
if (scenario === "permission removed") permissionAllowed = false;
|
|
if (scenario === "account suspended") liveActor.suspended = true;
|
|
if (scenario === "admin demoted") { liveActor.admin = false; accessAllowed = false; }
|
|
if (scenario === "password changed") { liveActor.password = "replacement-password-hash"; liveActor.session_epoch = 5; }
|
|
if (scenario === "2fa changed") { liveActor.secret = "replacement-2fa-seed"; liveActor.session_epoch = 5; }
|
|
if (scenario === "account replaced") liveActor.id = 8;
|
|
if (scenario === "session revoked") sessionRevoked = true;
|
|
if (scenario === "sealed 2fa") liveActor.totpSealedError = true;
|
|
return { ok: true };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 403, `${scenario} must invalidate pending destructive authorization`);
|
|
assert.equal(captured.nodeCalls.length, 0, "revoked authority must never dispatch a wipe");
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: stable non-admin authority can reinstall and legacy credentials still detect changes", async () => {
|
|
for (const changed of [false, true]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
let actor = { id: 7, email: request.session.user, admin: false, password: "legacy-password-hash", secret: null };
|
|
sandbox.isAdmin = async () => false;
|
|
sandbox.findUserByEmail = async () => ({ ...actor });
|
|
sandbox.requireDestructiveActionStepUp = async () => {
|
|
if (changed) actor = { ...actor, password: "replacement-password-hash" };
|
|
return { ok: true };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, changed ? 403 : 200);
|
|
assert.equal(captured.nodeCalls.length, changed ? 0 : 1);
|
|
assert.equal(captured.releases.length, 1);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: authorization lookup failures refuse before dispatch and release the claim", async () => {
|
|
for (const dependency of ["isSessionSidRevoked", "findUserByEmail", "userHasAccessToServer", "getEffectivePermsForUserOnServer"]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.isAdmin = async () => false;
|
|
sandbox.findUserByEmail = async () => ({ id: 7, email: request.session.user, password: "synthetic-password-hash", admin: false });
|
|
sandbox.findFreeNodePoolPort = async () => {
|
|
sandbox[dependency] = async () => { throw new Error("authorization lookup unavailable"); };
|
|
return 30005;
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 500);
|
|
assert.equal(captured.nodeCalls.length, 0);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: signing retries cannot dispatch after session revocation", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
let sessionRevoked = false;
|
|
sandbox.isSessionSidRevoked = async () => sessionRevoked;
|
|
sandbox.isLegacySigningRejection = (result) => result?.status === 403 && result.json?.error === "bad-signature";
|
|
sandbox.httpRequestJsonPruningUnknownFields = async (...args) => {
|
|
captured.nodeCalls.push(args);
|
|
sessionRevoked = true;
|
|
return { res: { status: 403, json: { error: "bad-signature" } } };
|
|
};
|
|
sandbox.retryReinstallAfterSigningRejection = require("../utils/server-reinstall").createReinstallSigningRetry({
|
|
nodeAdminSigningSecrets: () => ["derived", "master"], ensureNodePanelHmacSecret: async () => true,
|
|
signPanelAdminReinstallHeaders: () => true, isLegacySigningRejection: sandbox.isLegacySigningRejection,
|
|
});
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 403);
|
|
assert.equal(response.body.code, "reinstall-authorization-changed");
|
|
assert.equal(captured.nodeCalls.length, 1, "only the pre-execution signature rejection may contact the node");
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: post-claim target lookup failure releases the claim without a wipe", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.claimReinstallOperation = async () => {
|
|
sandbox.findServer = async () => { throw new Error("target lookup unavailable"); };
|
|
return { ok: true, prevStatus: "stopped" };
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 500);
|
|
assert.equal(captured.nodeCalls.length, 0);
|
|
assert.equal(captured.saves.length, 0);
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
test("reinstall route: a rejected save or vanished row reports partial completion", async () => {
|
|
for (const mode of ["rejected-save", "missing-row"]) {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.logger = sandbox.console;
|
|
if (mode === "rejected-save") sandbox.saveReinstallRow = async () => { throw new Error("database unavailable"); };
|
|
else sandbox.freshList = [];
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, mode === "rejected-save" ? 500 : 409);
|
|
assert.equal(response.body.reinstalled, true);
|
|
assert.deepEqual(captured.activities.map((activity) => activity[1]), ["reinstall_failed"]);
|
|
assert.equal(captured.releases.length, 1);
|
|
}
|
|
});
|
|
|
|
test("reinstall route: a legacy alias commits the resolved canonical row and rebound port", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
request.params.name = "legacy-alpha";
|
|
Object.assign(sandbox.freshList[0], { bot: "_alpha_", runtime: { image: "node", startupCommand: "legacy" } });
|
|
sandbox.signPanelAdminReinstallHeaders = (_headers, _node, daemonName) => {
|
|
assert.equal(daemonName, "alpha");
|
|
return true;
|
|
};
|
|
await captured.handler(request, response);
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(response.body.ok, true);
|
|
assert.equal(new URL(captured.nodeCalls[0][0]).pathname, "/v1/servers/alpha/reinstall");
|
|
assert.equal(captured.saves.length, 1);
|
|
assert.equal(captured.saves[0][0].name, "alpha");
|
|
assert.equal(captured.saves[0][0].port, 30005);
|
|
assert.equal(captured.saves[0][0].startupCommand, undefined);
|
|
assert.equal(captured.saves[0][0].runtime.startupCommand, undefined);
|
|
assert.equal(captured.activities.length, 1);
|
|
assert.equal(captured.releases[0][0], "alpha");
|
|
});
|
|
|
|
test("reinstall route: claim cleanup failure cannot answer a completed response twice", async () => {
|
|
const { sandbox, captured, request, response } = buildReinstallRouteHarness();
|
|
sandbox.releaseReinstallOperation = async (...args) => { captured.releases.push(args); throw new Error("release database unavailable"); };
|
|
await assert.doesNotReject(captured.handler(request, response));
|
|
assert.equal(response.statusCode, 200);
|
|
assert.equal(response.body.ok, true);
|
|
assert.equal(captured.releases.length, 1);
|
|
});
|
|
|
|
function buildReinstallUiHarness({ permitted = true } = {}) {
|
|
const elements = new Map();
|
|
const requests = [];
|
|
const requestDetails = [];
|
|
const authority = { permitted };
|
|
const document = {
|
|
getElementById(id) {
|
|
if (!elements.has(id)) {
|
|
const listeners = new Map();
|
|
const classes = new Set();
|
|
elements.set(id, {
|
|
value: "", disabled: false, textContent: "", style: {},
|
|
classList: { contains: (value) => classes.has(value), add: (value) => classes.add(value), remove: (value) => classes.delete(value) },
|
|
focus() {},
|
|
addEventListener(event, listener) {
|
|
if (!listeners.has(event)) listeners.set(event, []);
|
|
listeners.get(event).push(listener);
|
|
},
|
|
fire(event) {
|
|
return Promise.all((listeners.get(event) || []).map((listener) => listener({ target: this })));
|
|
},
|
|
});
|
|
}
|
|
return elements.get(id);
|
|
},
|
|
addEventListener() {},
|
|
};
|
|
const sandbox = {
|
|
document, serverName: "alpha", hasPerm: () => authority.permitted,
|
|
showModalElement: (element) => element.classList.add("show"),
|
|
animateClose: (element) => element.classList.remove("show"),
|
|
logger: { error() {} },
|
|
fetchWithServerActionToken: (url, options, tokenKey, tokenOptions) => {
|
|
requestDetails.push({ url, options, tokenKey, tokenOptions });
|
|
return new Promise((resolve) => requests.push(resolve));
|
|
},
|
|
};
|
|
const { createReinstallController } = require("../public/js/server-reinstall");
|
|
return { elements, requests, requestDetails, authority, controller: createReinstallController(sandbox) };
|
|
}
|
|
|
|
test("reinstall modal: close and reopen cannot submit a second pending wipe", async () => {
|
|
const { elements, requests, controller } = buildReinstallUiHarness();
|
|
controller.open();
|
|
elements.get("reinstallConfirmYes").fire("click");
|
|
try {
|
|
assert.equal(requests.length, 1);
|
|
controller.close();
|
|
controller.open();
|
|
elements.get("reinstallConfirmYes").fire("click");
|
|
assert.equal(requests.length, 1, "a pending reinstall must keep its admission guard across close/reopen");
|
|
assert.equal(elements.get("reinstallProgressView").style.display, "");
|
|
} finally {
|
|
for (const resolve of requests) resolve({ ok: true, status: 200, json: async () => ({ ok: true }) });
|
|
await new Promise(setImmediate);
|
|
}
|
|
});
|
|
|
|
test("reinstall modal: password and 2FA challenges use fresh tokens and clear canceled credentials", async () => {
|
|
for (const mode of ["password", "2fa"]) {
|
|
const harness = buildReinstallUiHarness();
|
|
harness.controller.open();
|
|
const firstAttempt = harness.elements.get("reinstallConfirmYes").fire("click");
|
|
harness.requests[0]({
|
|
ok: false, status: 403,
|
|
json: async () => ({ code: mode === "2fa" ? "2fa-required" : "password-required", revokeSecurity: { authMethod: mode } }),
|
|
});
|
|
await firstAttempt;
|
|
|
|
assert.equal(harness.elements.get("reinstallCredentialInput").type, mode === "2fa" ? "text" : "password");
|
|
assert.equal(harness.elements.get("reinstallConfirmView").style.display, "");
|
|
const credential = mode === "2fa" ? "123456" : "current password";
|
|
harness.elements.get("reinstallCredentialInput").value = credential;
|
|
const retryAttempt = harness.elements.get("reinstallConfirmYes").fire("click");
|
|
assert.equal(harness.elements.get("reinstallCredentialInput").value, "", "a pending request must not retain credentials in the input");
|
|
harness.requests[1]({ ok: true, status: 200, json: async () => ({ ok: true }) });
|
|
await retryAttempt;
|
|
|
|
assert.deepEqual(JSON.parse(harness.requestDetails[0].options.body), {});
|
|
assert.deepEqual(JSON.parse(harness.requestDetails[1].options.body), mode === "2fa"
|
|
? { twoFactorCode: credential } : { currentPassword: credential });
|
|
for (const request of harness.requestDetails) {
|
|
assert.equal(request.url, "/api/servers/alpha/reinstall");
|
|
assert.equal(request.tokenKey, "reinstallServer");
|
|
assert.deepEqual(request.tokenOptions, { refreshBefore: true });
|
|
}
|
|
assert.equal(harness.elements.get("reinstallCredentialInput").value, "");
|
|
assert.equal(harness.elements.get("reinstallSuccessView").style.display, "");
|
|
|
|
harness.controller.open();
|
|
harness.elements.get("reinstallCredentialInput").value = credential;
|
|
await harness.elements.get("reinstallConfirmNo").fire("click");
|
|
assert.equal(harness.elements.get("reinstallCredentialInput").value, "");
|
|
assert.equal(harness.elements.get("reinstallDefaultView").style.display, "");
|
|
}
|
|
});
|
|
|
|
test("reinstall modal: permission loss sends no request and errors render as text", async () => {
|
|
const harness = buildReinstallUiHarness();
|
|
harness.controller.open();
|
|
harness.authority.permitted = false;
|
|
await harness.elements.get("reinstallConfirmYes").fire("click");
|
|
assert.equal(harness.requests.length, 0);
|
|
|
|
harness.authority.permitted = true;
|
|
harness.controller.open();
|
|
const attempt = harness.elements.get("reinstallConfirmYes").fire("click");
|
|
const hostileError = '<img src=x onerror="alert(1)">';
|
|
harness.requests[0]({ ok: false, status: 502, json: async () => ({ ok: false, error: hostileError }) });
|
|
await attempt;
|
|
assert.equal(harness.elements.get("reinstallErrorDesc").textContent, hostileError);
|
|
assert.equal(harness.elements.get("reinstallErrorView").style.display, "");
|
|
assert.equal(harness.elements.get("reinstallConfirmYes").disabled, false);
|
|
});
|
|
|
|
test("reinstall modal: confirmed Minecraft rebuild explains why startup is blocked", async () => {
|
|
const { elements, requests, controller } = buildReinstallUiHarness();
|
|
controller.open();
|
|
const attempt = elements.get("reinstallConfirmYes").fire("click");
|
|
requests[0]({ ok: true, status: 200, json: async () => ({ ok: true, powerState: "stopped", eulaRequired: true }) });
|
|
await attempt;
|
|
assert.equal(elements.get("reinstallSuccessView").style.display, "");
|
|
assert.match(elements.get("reinstallSuccessDesc").textContent, /Accept the Minecraft EULA.*before starting/);
|
|
});
|
|
|
|
test("reinstall modal: completed rebuild reports when Docker is stopped", async () => {
|
|
const { elements, requests, controller } = buildReinstallUiHarness();
|
|
controller.open();
|
|
const attempt = elements.get("reinstallConfirmYes").fire("click");
|
|
requests[0]({ ok: true, status: 200, json: async () => ({ ok: true, powerState: "stopped" }) });
|
|
await attempt;
|
|
assert.equal(elements.get("reinstallSuccessView").style.display, "");
|
|
assert.match(elements.get("reinstallSuccessDesc").textContent, /files were replaced, but the server is stopped/);
|
|
});
|
|
|
|
test("reinstall modal: a result received away from the scene is shown until dismissed", async () => {
|
|
const { elements, requests, controller } = buildReinstallUiHarness();
|
|
controller.open();
|
|
const attempt = elements.get("reinstallConfirmYes").fire("click");
|
|
elements.get("reinstallModal").classList.remove("show");
|
|
requests[0]({ ok: false, status: 502, json: async () => ({ ok: false, code: "reinstall-result-unconfirmed", error: "Check the server state before retrying." }) });
|
|
await attempt;
|
|
controller.open();
|
|
assert.equal(elements.get("reinstallErrorView").style.display, "");
|
|
assert.equal(elements.get("reinstallErrorTitle").textContent, "Reinstall result unconfirmed");
|
|
await elements.get("reinstallErrorClose").fire("click");
|
|
controller.open();
|
|
assert.equal(elements.get("reinstallDefaultView").style.display, "");
|
|
});
|
|
|
|
test("reinstall modal: inline Done or close dismisses a completed result", async () => {
|
|
assert.match(botEjsSource, /if \(id === 'reinstallModalClose' \|\| id === 'reinstallDoneBtn'\)\s*\{\s*pages\.reinstall\?\.dispatchEvent\(new Event\('adpanel:reinstall-dismiss'\)\)/);
|
|
const { elements, requests, controller } = buildReinstallUiHarness();
|
|
controller.open();
|
|
const attempt = elements.get("reinstallConfirmYes").fire("click");
|
|
requests[0]({ ok: true, status: 200, json: async () => ({ ok: true }) });
|
|
await attempt;
|
|
assert.equal(elements.get("reinstallSuccessView").style.display, "");
|
|
await elements.get("reinstallModal").fire("adpanel:reinstall-dismiss");
|
|
elements.get("reinstallModal").classList.remove("show");
|
|
controller.open();
|
|
assert.equal(elements.get("reinstallDefaultView").style.display, "");
|
|
});
|
|
|
|
test("reinstall modal: unconfirmed successful HTTP responses never report wipe success", async () => {
|
|
for (const payload of [{}, { ok: false }]) {
|
|
const harness = buildReinstallUiHarness();
|
|
harness.controller.open();
|
|
const attempt = harness.elements.get("reinstallConfirmYes").fire("click");
|
|
harness.requests[0]({ ok: true, status: 200, json: async () => payload });
|
|
await attempt;
|
|
assert.equal(harness.elements.get("reinstallSuccessView").style.display, "none");
|
|
assert.equal(harness.elements.get("reinstallErrorView").style.display, "");
|
|
assert.match(harness.elements.get("reinstallErrorDesc").textContent, /confirm|unknown/i);
|
|
}
|
|
});
|
|
|
|
test("reinstall modal: server or gateway errors without a confirmed outcome warn before a retry", async () => {
|
|
for (const [status, payload] of [
|
|
[502, { error: "Bad gateway" }],
|
|
[503, { error: "Service unavailable" }],
|
|
[504, { ok: false, error: "Gateway timeout" }],
|
|
[500, { error: "internal error during reinstall" }],
|
|
]) {
|
|
const { elements, requests, controller } = buildReinstallUiHarness();
|
|
controller.open();
|
|
const attempt = elements.get("reinstallConfirmYes").fire("click");
|
|
requests[0]({ ok: false, status, json: async () => payload });
|
|
await attempt;
|
|
assert.equal(elements.get("reinstallErrorTitle").textContent, "Reinstall result unconfirmed");
|
|
assert.match(elements.get("reinstallErrorDesc").textContent, /may still be running.*Check the server state before retrying/);
|
|
assert.equal(requests.length, 1);
|
|
}
|
|
});
|