"use strict"; // Behavioral tests for the create_server tool's daemon payload parity // (utils/dashboard-assistant-tools.js vs the main route's payload // construction in index.js POST /api/servers/create). Pinned contract: // - payload carries asyncSetup: true (the daemon then answers after its // preflight and runs jar download / import extraction / container start // in the background — without it the synchronous handler outlasts // createOnRemoteNode's 600 s client timeout and the retry/compensation // races the in-flight create); // - bind pinning mirrors the route: node.address is pinned into // docker.bind_ip/host_ip and the payload's top-level bind_ip/host_ip; // - the payload's docker goes through the injected dockerConfigForNodeRequest // allowlist (the same pass the route runs — panel-only fields such as // startupDisplay must not reach the daemon), falling back to the raw // sanitized docker when the dep is absent (formatting, not a guard); // - the committed index row encodes the async create exactly like the // route/proxy (status "installing", setupStatus from the daemon meta), // and the success result tells the admin setup is still running. // // The runner is exercised directly with contract-compatible dep stubs (no // network, no service/router stack) — the same behavioral style as the // write-probe suite. const test = require("node:test"); const assert = require("node:assert"); const { createDashboardAssistantToolRunner } = require("../utils/dashboard-assistant-tools.js"); // adpanel:backup-cap-daemon-enforced — the payload pins below compare against // the SAME resolver the tool wires into the payload, so the pin stays correct // under any SCHEDULER_MAX_BACKUPS_PER_SERVER the environment carries. const { resolvePanelBackupsCap } = require("../utils/backup-cap"); const USER_EMAIL = "admin@test.local"; const NODE_ADDRESS = "203.0.113.10"; const TEMPLATE = { id: "vanilla", name: "Vanilla", defaultPort: 25565, docker: { image: "ghcr.io/example/mc", tag: "latest", // Panel-only display field: survives sanitizeDockerTemplatePayload but is // NOT on the daemon create payload's docker allowlist — exactly the field // class dockerConfigForNodeRequest exists to strip. startupDisplay: "java -Xms128M -Xmx1024M -jar {{SERVER_JAR}} nogui", }, }; function makeDeps({ createResult, withDockerAllowlistDep = true } = {}) { const calls = {}; const deps = { calls, loadServersIndex: async () => [], loadServersIndexForSubscribeFresh: async () => [], findUserByEmail: async () => ({ email: USER_EMAIL, admin: true }), sanitizeServerName: (value) => String(value || "").trim(), loadTemplatesFile: () => [TEMPLATE], loadNodes: async () => [ { id: "node-1", uuid: "node-1", name: "node-1", address: NODE_ADDRESS, online: true }, ], createOnRemoteNode: async (node, payload) => { calls.createPayload = payload; return ( createResult || { ok: true, name: payload.name, meta: { setupStatus: "queued", setupMessage: "Server setup queued" }, asyncSetup: true, } ); }, insertServerIndexEntryGuarded: async (entry) => { calls.committedEntry = entry; return { ok: true }; }, recordActivity: () => {}, }; if (withDockerAllowlistDep) { // Contract-compatible stand-in for index.js's dockerConfigForNodeRequest: // the tool must route the payload's docker through the injected dep // whatever it returns, so stripping startupDisplay here asserts both the // routing and the allowlist effect. deps.dockerConfigForNodeRequest = (docker) => { calls.dockerAllowlistInput = docker; if (!docker || typeof docker !== "object") return null; const { startupDisplay, ...allowed } = docker; return allowed; }; } return deps; } function createArgs(overrides = {}) { return { name: "newserver", templateId: "vanilla", nodeId: "node-1", hostPort: 25565, ...overrides }; } test("create payload mirrors the route: asyncSetup, bind pinning and allowlisted docker", async () => { const deps = makeDeps(); const runTool = createDashboardAssistantToolRunner(deps); const result = await runTool({ name: "create_server", args: createArgs(), userEmail: USER_EMAIL }); assert.equal(result.ok, true); const payload = deps.calls.createPayload; assert.equal(payload.asyncSetup, true); assert.equal(payload.autoStart, true); // Bind pinning (route: nodeBindIP from node.address||host_ip||bind_ip). assert.equal(payload.bind_ip, NODE_ADDRESS); assert.equal(payload.host_ip, NODE_ADDRESS); assert.equal(payload.docker.bind_ip, NODE_ADDRESS); assert.equal(payload.docker.host_ip, NODE_ADDRESS); // Docker went through the injected allowlist: panel-only startupDisplay is // stripped from the payload exactly like the main route's create. assert.equal(deps.calls.dockerAllowlistInput.startupDisplay, TEMPLATE.docker.startupDisplay); assert.equal(payload.docker.startupDisplay, undefined); assert.equal(payload.docker.image, TEMPLATE.docker.image); }); test("assistant create uses the address allocated to the chosen port", async () => { const ip = "203.0.113.20"; const deps = makeDeps(); const [node] = await deps.loadNodes(); node.ports = { mode: "list", allocations: [{ ip, port: 25565 }] }; deps.loadNodes = async () => [node]; const runTool = createDashboardAssistantToolRunner(deps); assert.equal((await runTool({ name: "create_server", args: createArgs(), userEmail: USER_EMAIL })).ok, true); assert.equal(deps.calls.createPayload.bind_ip, ip); assert.equal(deps.calls.committedEntry.ip, ip); }); test("assistant create refuses a port removed after node selection", async () => { const deps = makeDeps(); const [node] = await deps.loadNodes(); deps.loadNodes = async () => [{ ...node, ports: { ports: [25565] } }]; deps.findNodeByIdOrName = async () => ({ ...node, ports: { ports: [] } }); deps.isPortInNodeAllocation = (record, port) => record.ports.ports.includes(port); deps.dockerTemplateHostPortRequirements = (_, hostPort) => [{ hostPort, protocols: ["tcp"] }]; deps.findServerUsingNodePort = async () => assert.fail("removed allocation reached assignment checks"); const runTool = createDashboardAssistantToolRunner(deps); const outcome = await runTool({ name: "create_server", args: createArgs(), userEmail: USER_EMAIL }); assert.equal(outcome.ok, false); assert.match(outcome.error, /not in this node's allocated ports/); assert.equal(deps.calls.createPayload, undefined); }); test("without the dockerConfigForNodeRequest dep the payload falls back to the raw sanitized docker", async () => { const deps = makeDeps({ withDockerAllowlistDep: false }); const runTool = createDashboardAssistantToolRunner(deps); const result = await runTool({ name: "create_server", args: createArgs(), userEmail: USER_EMAIL }); assert.equal(result.ok, true); const payload = deps.calls.createPayload; // Formatting helper, not a guard: the create must not fail over a missing // dep — the raw sanitized docker (still bind-pinned) is sent instead. assert.equal(payload.docker.startupDisplay, TEMPLATE.docker.startupDisplay); assert.equal(payload.docker.bind_ip, NODE_ADDRESS); assert.equal(payload.asyncSetup, true); }); test("async create commits installing/queued row status and reports setup running in the background", async () => { const deps = makeDeps(); const runTool = createDashboardAssistantToolRunner(deps); const result = await runTool({ name: "create_server", args: createArgs(), userEmail: USER_EMAIL }); assert.equal(result.ok, true); const entry = deps.calls.committedEntry; assert.equal(entry.status, "installing"); assert.equal(entry.setupStatus, "queued"); assert.equal(entry.setupMessage, "Server setup queued"); assert.equal(entry.bind_ip, NODE_ADDRESS); assert.equal(entry.host_ip, NODE_ADDRESS); assert.equal(result.setupQueued, true); assert.equal(result.setupStatus, "queued"); assert.match(result.message, /background/); assert.equal(result.created, true); assert.equal(result.server.name, "newserver"); assert.equal(result.server.port, 25565); }); test("create payload always carries the panel backup cap as resources.backupsMax", async () => { // adpanel:backup-cap-daemon-enforced — the panel-side count-then-create // checks (scheduler fire path, interactive relay) are a TOCTOU fast-fail; // the daemon's backupsMax (checked under the per-server op lock over an // untruncated ReadDir) is the authoritative bound. When the request does // not name one, the payload — and the committed entry mirroring it — carry // the resolved panel cap; the daemon (`if backupsMax > 0`) reads a missing // or non-positive value as "no cap", so the default must be positive. An // explicit request value (12, or 0 = the caller's deliberate "no daemon // cap") passes through untouched. const defaultDeps = makeDeps(); const defaultRun = createDashboardAssistantToolRunner(defaultDeps); const defaultResult = await defaultRun({ name: "create_server", args: createArgs(), userEmail: USER_EMAIL }); assert.equal(defaultResult.ok, true); assert.equal(defaultDeps.calls.createPayload.resources.backupsMax, resolvePanelBackupsCap()); assert.ok(defaultDeps.calls.createPayload.resources.backupsMax > 0, "the default must never be 0/undefined — either would disable the daemon cap"); assert.equal(defaultDeps.calls.committedEntry.resources.backupsMax, resolvePanelBackupsCap()); const explicitDeps = makeDeps(); const explicitRun = createDashboardAssistantToolRunner(explicitDeps); const explicitResult = await explicitRun({ name: "create_server", args: createArgs({ resources: { backupsMax: 12 } }), userEmail: USER_EMAIL, }); assert.equal(explicitResult.ok, true); assert.equal(explicitDeps.calls.createPayload.resources.backupsMax, 12); assert.equal(explicitDeps.calls.committedEntry.resources.backupsMax, 12); const zeroDeps = makeDeps(); const zeroRun = createDashboardAssistantToolRunner(zeroDeps); const zeroResult = await zeroRun({ name: "create_server", args: createArgs({ resources: { backupsMax: 0 } }), userEmail: USER_EMAIL, }); assert.equal(zeroResult.ok, true); assert.equal(zeroDeps.calls.createPayload.resources.backupsMax, 0, "explicit 0 stays the caller's deliberate no-daemon-cap choice"); assert.equal(zeroDeps.calls.committedEntry.resources.backupsMax, 0); // adpanel:backup-cap-parse-hardening — garbage/negative explicit values // degrade to the panel cap (the daemon's `if backupsMax > 0` reads both // as "no cap"), never to unlimited. This replaced the tool's former // post-hoc negative rejection with the same degrade-to-cap semantics // every other backupsMax transmission site uses. const garbageDeps = makeDeps(); const garbageRun = createDashboardAssistantToolRunner(garbageDeps); const garbageResult = await garbageRun({ name: "create_server", args: createArgs({ resources: { backupsMax: "abc" } }), userEmail: USER_EMAIL, }); assert.equal(garbageResult.ok, true); assert.equal(garbageDeps.calls.createPayload.resources.backupsMax, resolvePanelBackupsCap(), "garbage must degrade to the panel cap, never to unlimited"); assert.equal(garbageDeps.calls.committedEntry.resources.backupsMax, resolvePanelBackupsCap()); const negativeDeps = makeDeps(); const negativeRun = createDashboardAssistantToolRunner(negativeDeps); const negativeResult = await negativeRun({ name: "create_server", args: createArgs({ resources: { backupsMax: -5 } }), userEmail: USER_EMAIL, }); assert.equal(negativeResult.ok, true, "a negative degrades to the cap instead of erroring (consistent degrade-to-cap semantics)"); assert.equal(negativeDeps.calls.createPayload.resources.backupsMax, resolvePanelBackupsCap(), "a negative must degrade to the panel cap, never reach the daemon's 'no cap' branch"); assert.equal(negativeDeps.calls.committedEntry.resources.backupsMax, resolvePanelBackupsCap()); const stringDeps = makeDeps(); const stringRun = createDashboardAssistantToolRunner(stringDeps); const stringResult = await stringRun({ name: "create_server", args: createArgs({ resources: { backupsMax: "12" } }), userEmail: USER_EMAIL, }); assert.equal(stringResult.ok, true); assert.equal(stringDeps.calls.createPayload.resources.backupsMax, 12, "string shapes parse like numbers"); assert.equal(stringDeps.calls.committedEntry.resources.backupsMax, 12); }); test("failed background setup is committed as error status, not installing", async () => { const deps = makeDeps({ createResult: { ok: true, name: "newserver", meta: { setupStatus: "failed", setupMessage: "jar download failed" }, asyncSetup: true, }, }); const runTool = createDashboardAssistantToolRunner(deps); const result = await runTool({ name: "create_server", args: createArgs(), userEmail: USER_EMAIL }); assert.equal(result.ok, true); assert.equal(deps.calls.committedEntry.status, "error"); assert.equal(deps.calls.committedEntry.setupStatus, "failed"); // The daemon's sync prepare phase can report "failed" before its 200 (the // handler reloads meta after prepareMinecraft/CustomCreateSetup), so the // result must not claim the setup is still running in the background — // that would contradict the "error" row committed above. assert.equal(result.setupQueued, false); assert.equal(result.setupStatus, "failed"); assert.match(result.message, /failed before the background work/); assert.match(result.message, /jar download failed/); }); test("non-async 200 (older daemon) keeps the previous success shape and row shape", async () => { const deps = makeDeps({ createResult: { ok: true, name: "newserver" } }); const runTool = createDashboardAssistantToolRunner(deps); const result = await runTool({ name: "create_server", args: createArgs(), userEmail: USER_EMAIL }); assert.equal(result.ok, true); assert.equal(result.setupQueued, undefined); assert.equal(result.message, undefined); const entry = deps.calls.committedEntry; assert.equal(entry.status, undefined); assert.equal(entry.setupStatus, undefined); assert.equal(entry.setupMessage, undefined); });