"use strict"; // Behavioral tests for services/server-create.js — the shared server-creation // pipeline extracted from the POST /api/servers/create route (Wave 1 Step 1 of // the consolidation campaign). All deps are fakes: no DB, no network, no node // daemon. The extraction is behavior-preserving, so these tests pin the exact // wire contracts the route used to answer with — several of which (the // duplicate-409 / storage-collision-409 sentences, the ER_DUP_ENTRY mapping, // the compensating-delete withhold rules) had NO test coverage before the // extraction (see .campaign/spec-server-create.md section 6). const test = require("node:test"); const assert = require("node:assert"); const { createServerOnNode, serverNameGuardOutcome, duplicateServerNameOutcome, scanNodeStorageCollisions, commitCreatedServer, renderServerCreateOutcome, deleteOwnOrphanServerOnNodeForCreate, } = require("../services/server-create"); // adpanel:backup-cap-daemon-enforced — the payload pins below compare against // the SAME resolver the service 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 { createDeferredServerImport, isValidArchiveUrl } = require("../services/server-create-import"); const NODE = { id: "n1", uuid: "u1", name: "Node One", address: "203.0.113.5", token: "node-token", api_port: 8080, ssl_enabled: false, }; function makeDeps(overrides = {}) { const calls = { withTimeout: [], dbQuery: [], daemonPayloads: [], committedEntries: [], deleteServerOnNode: [], recordActivity: [], runDeferredServerImport: [], addAccessForEmail: [], }; const base = { // rows-only contract: db.query resolves to the row array. Dispatch on the // SQL shape so one fake serves the storage-collision scan (node_id legs) // and the ownership-guarded compensating-delete read (LOWER(name) legs). dbQuery: async (sql, params) => { calls.dbQuery.push({ sql, params }); if (sql.includes("LOWER(name) = ?")) return overrides.__ownershipRows || []; return overrides.__collisionRows || []; }, withTimeout: (promise, ms, label) => { calls.withTimeout.push({ ms, label }); return promise; }, findServer: async () => null, findTemplateById: () => ({ id: "minecraft", name: "My Template", defaultPort: 25565, docker: null }), normalizeTemplateId: () => "minecraft", loadNodes: async () => [NODE], findNodeByIdOrName: async () => NODE, getEffectiveNodeCapacity: async () => ({ ramMb: 0, cpuCores: 0, diskGb: 0 }), dockerTemplateHostPortRequirements: (docker, mainHostPort) => [{ hostPort: mainHostPort, protocols: ["tcp"] }], isPortInNodeAllocation: () => true, findServerUsingNodePort: async () => null, checkRemoteNodePortAvailability: async () => ({ verified: false, available: true, owner: null, reason: null }), createOnRemoteNode: async (node, payload) => { calls.daemonPayloads.push({ node, payload }); return { ok: true, asyncSetup: true, meta: { setupStatus: "queued", setupMessage: "queued on node" } }; }, insertServerIndexEntryGuarded: async (entry) => { calls.committedEntries.push(entry); return { ok: true, rowId: 71 }; }, deleteServerOnNode: async (node, name) => { calls.deleteServerOnNode.push({ node, name }); }, isValidArchiveUrl: () => false, assertSafeRemoteUrl: async () => {}, normalizeTemplateDockerForRuntime: () => ({ image: "eclipse-temurin", tag: "8-jre" }), dockerConfigForNodeRequest: (docker) => docker, collectResourcePerformanceOptions: () => ({}), collectResourceAntiAbuseOptions: () => ({}), normalizeMinecraftJavaVersionInput: (value) => { const v = String(value ?? "").trim(); return /^\d{1,3}$/.test(v) ? v : ""; }, minecraftJavaTag: (version) => `java-${version}`, DEFAULT_MINECRAFT_PROCESS_IMAGE: "eclipse-temurin", normalizeLegacyRuntimeProcessCommandInput: (templateId, value) => (value ? String(value).trim() : ""), validateRuntimeProcessCommandInput: (value) => (value && value.includes("rm -rf") ? "Command not allowed" : null), validatePort: (value) => { if (value === null || value === undefined) return null; const s = String(value).trim(); if (!/^[1-9]\d{0,4}$/.test(s)) return null; const p = parseInt(s, 10); return p >= 1 && p <= 65535 ? p : null; }, clampPort: (p) => Math.min(65535, Math.max(1, p)), httpRequestJson: async () => { throw new Error("unexpected HTTP call"); }, buildNodeBaseUrl: () => "http://203.0.113.5:8080", nodeUnderCloudflare: () => false, recordActivity: (serverName, action, details, userEmail, userIp) => { calls.recordActivity.push({ serverName, action, details, userEmail, userIp }); }, runDeferredServerImport: async (node, serverName, importUrl, rowId) => { calls.runDeferredServerImport.push({ node, serverName, importUrl, rowId }); }, addAccessForEmail: async (email, server) => { calls.addAccessForEmail.push({ email, server }); }, findUserByEmail: async () => ({ email: "admin@example.com", admin: true }), ...overrides, }; base.__calls = calls; return base; } test("deferred creation import waits for setup and safely stages the uploaded archive", async () => { const entry = { name: "test-srv", rowId: 71, status: "stopped", port: 25565 }; const url = "https://example.com/existing.TAR.GZ?download=1"; const success = { status: 200, json: { ok: true } }; const stream = {}; const scenarios = ["success", "eula required", "setup failed", "row replaced", "suspended", "node changed", "staging conflict", "extraction failed"]; for (const scenario of scenarios) { const events = []; let locked = false; let archiveName; const runImport = createDeferredServerImport({ waitForServerReady: async (_node, _name, { check }) => { events.push("wait"); assert.strictEqual(check({ setupStatus: "queued", isInstalling: true }), null); assert.strictEqual(check({ setupStatus: "starting" }), null); assert.strictEqual(check({ setupStatus: "failed" }), false); const ready = { setupStatus: "ready", status: "stopped", eulaRequired: scenario === "eula required" }; assert.strictEqual(check(ready), ready); return scenario === "setup failed" ? false : ready; }, withReinstallSuspensionLock: async (_name, _busy, operation) => { locked = true; try { return await operation(); } finally { locked = false; } }, findServer: async () => ({ ...entry, rowId: scenario === "row replaced" ? 72 : entry.rowId, suspended: scenario === "suspended" }), isServerSuspended: server => server.suspended, isGuardedServerStatus: () => false, resolveRemoteFsContext: async () => ({ remote: true, node: scenario === "node changed" ? { id: "other" } : NODE, baseDir: "/volumes/test-srv", serverName: entry.name, }), safeJoinUnix: base => base, maxBytes: 1024, ssrfPipedHttpGet: async (source, options) => { assert.strictEqual(locked, true); assert.strictEqual(source, url); assert.strictEqual(options.maxBytes, 1024); events.push("fetch"); return { stream }; }, streamPanelUploadToNode: async (_node, source, filename, directory, _bytes, _mb, name, createOnly) => { assert.strictEqual(source, stream); assert.strictEqual(directory, "/volumes/test-srv"); assert.strictEqual(name, entry.name); assert.strictEqual(createOnly, true); assert.match(filename, /^adpanel-import-[a-f0-9]{32}\.tar\.gz$/); archiveName = filename; events.push("upload"); return scenario === "staging conflict" ? { status: 409 } : success; }, nodeFsPost: async (_node, endpoint, target) => { assert.strictEqual(locked, true); assert.strictEqual(target.path, `/volumes/test-srv/${archiveName}`); assert.strictEqual(target.server, entry.name); events.push(endpoint); if (endpoint === "/v1/fs/extract") { assert.strictEqual(target.overwrite, true); if (scenario === "extraction failed") return { status: 422 }; } return success; }, startServerOnNode: async (_node, name, port) => { assert.strictEqual(locked, true); assert.strictEqual(name, entry.name); assert.strictEqual(port, entry.port); events.push("start"); }, }); assert.strictEqual(isValidArchiveUrl(url), true); await runImport(NODE, entry.name, url, entry.rowId); const expected = ["wait"]; if (["success", "eula required", "staging conflict", "extraction failed"].includes(scenario)) expected.push("fetch", "upload"); if (["success", "eula required", "extraction failed"].includes(scenario)) expected.push("/v1/fs/extract", "/v1/fs/delete"); if (scenario === "success") expected.push("start"); assert.deepStrictEqual(events, expected, scenario); } }); function baseInput(overrides = {}) { return { name: "test-srv", rawName: "test srv", displayNameInput: "", templateId: "minecraft", nodeId: "n1", body: {}, sessionUser: "admin@example.com", clientIp: "203.0.113.7", logTag: "[/api/servers/create]", lock: { release: () => {} }, ...overrides, }; } // --------------------------------------------------------------------------- // 1. Name guards (transport-neutral outcomes; the panel strings render below) // --------------------------------------------------------------------------- test("serverNameGuardOutcome: empty / no-storage-form / mismatch / pass", () => { assert.deepStrictEqual(serverNameGuardOutcome(null), { ok: false, code: "invalid_name_empty" }); assert.deepStrictEqual(serverNameGuardOutcome(""), { ok: false, code: "invalid_name_empty" }); // Token form keeps leading "_" (sanitizeServerToken only trims "-"), the Go // storage form strips it — "___" has no node-storable form at all. assert.deepStrictEqual(serverNameGuardOutcome("___"), { ok: false, code: "invalid_name_no_storage_form" }); assert.deepStrictEqual(serverNameGuardOutcome("_foo"), { ok: false, code: "invalid_name_storage_mismatch" }); assert.strictEqual(serverNameGuardOutcome("ok-name"), null); assert.strictEqual(serverNameGuardOutcome("ok.name_1"), null); }); // --------------------------------------------------------------------------- // 2. Duplicate-name pre-check (withTimeout label leaks into 500 details) // --------------------------------------------------------------------------- test("duplicateServerNameOutcome: 409 mapping keeps the '(on node X)' suffix", async () => { const deps = makeDeps({ findServer: async () => ({ name: "test-srv", nodeId: "n9" }) }); const outcome = await duplicateServerNameOutcome(deps, "test-srv"); assert.strictEqual(outcome.ok, false); assert.strictEqual(outcome.code, "server_name_exists"); assert.strictEqual(outcome.data.onNode, " (on node n9)"); const rendered = renderServerCreateOutcome(outcome, "panel"); assert.deepStrictEqual(rendered, { status: 409, body: { error: 'A server named "test-srv" already exists (on node n9). Choose a different name.', code: "server_name_exists", }, }); assert.deepStrictEqual(deps.__calls.withTimeout, [{ ms: 5000, label: "server-create-name-check-timeout" }]); }); test("duplicateServerNameOutcome: no suffix when the row carries no nodeId", async () => { const deps = makeDeps({ findServer: async () => ({ name: "test-srv" }) }); const outcome = await duplicateServerNameOutcome(deps, "test-srv"); assert.strictEqual(outcome.data.onNode, ""); const rendered = renderServerCreateOutcome(outcome, "panel"); assert.strictEqual( rendered.body.error, 'A server named "test-srv" already exists. Choose a different name.' ); }); test("duplicateServerNameOutcome: null when the name is free", async () => { const deps = makeDeps(); assert.strictEqual(await duplicateServerNameOutcome(deps, "test-srv"), null); }); // --------------------------------------------------------------------------- // 3. Same-node storage-collision scan (exact 3-way SQL, alias mapping) // --------------------------------------------------------------------------- test("storage-collision scan: triggers on a legacy_id alias, exact SQL + 409 body", async () => { const deps = makeDeps({ __collisionRows: [{ name: "other-srv", legacy_id: "test-srv", bot: null }], }); const outcome = await createServerOnNode(deps, baseInput()); assert.strictEqual(outcome.ok, false); assert.strictEqual(outcome.code, "server_name_storage_collision"); const rendered = renderServerCreateOutcome(outcome, "panel"); assert.deepStrictEqual(rendered, { status: 409, body: { error: 'A server named "other-srv" already exists on this node, and the name "test-srv" would collide with it at the node\'s storage layer. Choose a different name.', code: "server_name_exists", }, }); // The 3-way node identity has NO ip leg (unlike the proxy's 4-way scan). assert.deepStrictEqual(deps.__calls.dbQuery[0], { sql: "SELECT name, legacy_id, bot FROM servers WHERE node_id = ? OR node_id = ? OR LOWER(node_id) = ?", params: ["n1", "u1", "node one"], }); assert.deepStrictEqual( deps.__calls.withTimeout.map((t) => t.label), ["server-create-nodes-timeout", "server-create-node-lookup-timeout", "server-create-node-name-collision-timeout"] ); assert.strictEqual(deps.__calls.daemonPayloads.length, 0, "no provisioning after a collision"); }); test("storage-collision scan: same-name rows are skipped (already refused upstream)", async () => { const deps = makeDeps({ __collisionRows: [{ name: "Test-Srv", legacy_id: null, bot: null }], }); const outcome = await createServerOnNode(deps, baseInput()); assert.strictEqual(outcome.ok, true); assert.strictEqual(deps.__calls.daemonPayloads.length, 1); }); // --------------------------------------------------------------------------- // 4. Guarded-commit failure paths (compensating delete + exact 409 bodies) // --------------------------------------------------------------------------- test("guarded commit: template_deleted -> compensating delete + exact 409 body", async () => { const deps = makeDeps({ insertServerIndexEntryGuarded: async () => ({ ok: false, reason: "template_deleted" }) }); const outcome = await createServerOnNode(deps, baseInput()); assert.deepStrictEqual(renderServerCreateOutcome(outcome, "panel"), { status: 409, body: { error: 'Template "My Template" was deleted while the server was being created. Choose another template and retry.', code: "template_deleted_during_create", }, }); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 1); assert.strictEqual(deps.__calls.deleteServerOnNode[0].name, "test-srv"); assert.strictEqual(deps.__calls.recordActivity.length, 0, "no audit for failed creates"); assert.strictEqual(deps.__calls.runDeferredServerImport.length, 0); }); test("guarded commit: ER_DUP_ENTRY -> compensating delete + exact 409 body (no node suffix)", async () => { const deps = makeDeps({ insertServerIndexEntryGuarded: async () => { throw Object.assign(new Error('a server index entry named "test-srv" already exists'), { code: "ER_DUP_ENTRY" }); }, }); const outcome = await createServerOnNode(deps, baseInput()); assert.deepStrictEqual(renderServerCreateOutcome(outcome, "panel"), { status: 409, body: { error: 'A server named "test-srv" already exists. Choose a different name.', code: "server_name_exists", }, }); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 1); }); test("guarded commit: other errors rethrow to the caller's 500 catch", async () => { const deps = makeDeps({ insertServerIndexEntryGuarded: async () => { throw new Error("db exploded"); }, }); await assert.rejects(createServerOnNode(deps, baseInput()), /db exploded/); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 1, "compensation still runs"); }); // --------------------------------------------------------------------------- // 5. Compensating-delete ownership guard (withhold = never destroy another // writer's live server) // --------------------------------------------------------------------------- test("compensating delete withholds when a committed row claims the name on this node", async () => { // Row claims the node via uuid -> withheld, node untouched. const withheldDeps = makeDeps({ __ownershipRows: [{ name: "test-srv", node_id: "u1", ip: null }], }); const withheld = await deleteOwnOrphanServerOnNodeForCreate(withheldDeps, NODE, "test-srv"); assert.strictEqual(withheld.withheld, true); assert.ok(withheld.row); assert.strictEqual(withheldDeps.__calls.deleteServerOnNode.length, 0); // Row claims the node via the (lowercased) address -> withheld too. const ipDeps = makeDeps({ __ownershipRows: [{ name: "test-srv", node_id: "", ip: "203.0.113.5" }], }); const ipWithheld = await deleteOwnOrphanServerOnNodeForCreate(ipDeps, NODE, "test-srv"); assert.strictEqual(ipWithheld.withheld, true); assert.strictEqual(ipDeps.__calls.deleteServerOnNode.length, 0); // Unclaimed name -> the orphan is deleted. const freeDeps = makeDeps(); const deleted = await deleteOwnOrphanServerOnNodeForCreate(freeDeps, NODE, "test-srv"); assert.strictEqual(deleted.deleted, true); assert.strictEqual(freeDeps.__calls.deleteServerOnNode.length, 1); }); test("compensating delete withholds rows with no node_id and no ip (fail closed)", async () => { const deps = makeDeps({ __ownershipRows: [{ name: "test-srv", node_id: null, ip: null }], }); const comp = await deleteOwnOrphanServerOnNodeForCreate(deps, NODE, "test-srv"); assert.strictEqual(comp.withheld, true); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 0); }); test("compensating delete removes orphans claimed on a DIFFERENT node only", async () => { const deps = makeDeps({ __ownershipRows: [{ name: "test-srv", node_id: "other-node", ip: "198.51.100.9" }], }); const comp = await deleteOwnOrphanServerOnNodeForCreate(deps, NODE, "test-srv"); assert.strictEqual(comp.deleted, true); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 1); }); test("compensating delete: empty name errors without touching the DB or the node", async () => { const deps = makeDeps(); const comp = await deleteOwnOrphanServerOnNodeForCreate(deps, NODE, " "); assert.strictEqual(comp.deleted, false); assert.ok(comp.error); assert.strictEqual(deps.__calls.dbQuery.length, 0); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 0); }); test("compensating delete: dbQuery throw never throws out (callers must not mask)", async () => { const deps = makeDeps(); deps.dbQuery = async () => { throw new Error("db down"); }; const comp = await deleteOwnOrphanServerOnNodeForCreate(deps, NODE, "test-srv"); assert.strictEqual(comp.deleted, false); assert.match(String(comp.error), /db down/); }); // --------------------------------------------------------------------------- // 6. Success path (payload, entry shape, audit x2, deferred import, grants) // --------------------------------------------------------------------------- test("success: daemon result flows through; entry carries status/setupStatus/docker/runtime", async () => { const deps = makeDeps(); const outcome = await createServerOnNode(deps, baseInput()); assert.strictEqual(outcome.ok, true); assert.strictEqual(outcome.code, "success"); const { payload } = deps.__calls.daemonPayloads[0]; assert.strictEqual(payload.asyncSetup, true); assert.strictEqual(payload.autoStart, true); assert.strictEqual(payload.hostPort, 25565); // adpanel:backup-cap-daemon-enforced — updated consciously (was: resources // === null): the payload now ALWAYS carries resources.backupsMax so the // daemon's op-lock bound agrees with the panel's count-then-create checks; // a missing field reads as "no cap" daemon-side (`if backupsMax > 0`). assert.deepStrictEqual( payload.resources, { backupsMax: resolvePanelBackupsCap() }, "no resources requested -> cap-only resources (resolved panel backup cap)" ); assert.strictEqual(payload.templateId, "minecraft"); assert.strictEqual(payload.mcFork, "paper"); assert.strictEqual(payload.mcVersion, "1.21.8"); const entry = deps.__calls.committedEntries[0]; assert.strictEqual(entry.name, "test-srv"); assert.strictEqual(entry.displayName, "test srv"); assert.strictEqual(entry.template, "minecraft"); assert.strictEqual(entry.start, "server.jar"); assert.strictEqual(entry.nodeId, "u1"); assert.strictEqual(entry.ip, "203.0.113.5"); assert.strictEqual(entry.status, "installing"); assert.strictEqual(entry.setupStatus, "queued"); assert.strictEqual(entry.setupMessage, "queued on node"); assert.strictEqual(entry.port, 25565); // The node address is pinned into the docker config (bind_ip/host_ip) like // the original route did before the allowlist pass. assert.deepStrictEqual(entry.docker, { image: "eclipse-temurin", tag: "8-jre", bind_ip: "203.0.113.5", host_ip: "203.0.113.5", }); assert.strictEqual(entry.runtime.image, "eclipse-temurin"); assert.strictEqual(entry.runtime.tag, "8-jre"); assert.strictEqual(entry.runtime.runAsRoot, false); assert.strictEqual(entry.runtime.readonlyRootfs, false); // Success body: exactly the three wire fields the wizard relies on. const rendered = renderServerCreateOutcome(outcome, "panel"); assert.deepStrictEqual(rendered.json, { ok: true, name: "test-srv", displayName: "test srv" }); assert.deepStrictEqual(Object.keys(rendered.json).sort(), ["displayName", "name", "ok"]); }); test("create binds and records the address allocated to the chosen port", async () => { const ip = "203.0.113.20"; const node = { ...NODE, address: "node.example.test", under_cloudflare: true, ports: { mode: "list", allocations: [{ ip, port: 25565 }] } }; const deps = makeDeps({ loadNodes: async () => [node], findNodeByIdOrName: async () => node }); const outcome = await createServerOnNode(deps, baseInput()); assert.strictEqual(outcome.ok, true); assert.strictEqual(deps.__calls.daemonPayloads[0].payload.bind_ip, ip); assert.strictEqual(deps.__calls.committedEntries[0].ip, ip); }); test("create refuses to bind a game port to the Cloudflare management hostname", async () => { const address = "node.example.test"; const node = { ...NODE, address, under_cloudflare: true, ports: { mode: "list", allocations: [{ ip: address, port: 25565 }] } }; const deps = makeDeps({ loadNodes: async () => [node], findNodeByIdOrName: async () => node }); const outcome = await createServerOnNode(deps, baseInput()); assert.strictEqual(outcome.code, "port_bind_address_required"); assert.strictEqual(renderServerCreateOutcome(outcome, "panel").status, 400); assert.strictEqual(deps.__calls.daemonPayloads.length, 0); }); test("resources: explicit backupsMax passes through; the resolved cap is the default in payload and entry", async () => { // adpanel:backup-cap-daemon-enforced — the daemon treats a missing or // non-positive backupsMax as "no cap" (main.go `if backupsMax > 0`), so the // create payload's default must be the resolved positive panel cap, while // an explicit request value (12, or 0 = the caller's deliberate "no daemon // cap") passes through untouched. The committed entry mirrors the payload. const explicitDeps = makeDeps(); await createServerOnNode(explicitDeps, baseInput({ body: { resources: { backupsMax: 12 } } })); assert.strictEqual(explicitDeps.__calls.daemonPayloads[0].payload.resources.backupsMax, 12); assert.strictEqual(explicitDeps.__calls.committedEntries[0].resources.backupsMax, 12); const zeroDeps = makeDeps(); await createServerOnNode(zeroDeps, baseInput({ body: { resources: { backupsMax: 0 } } })); assert.strictEqual(zeroDeps.__calls.daemonPayloads[0].payload.resources.backupsMax, 0, "explicit 0 stays the caller's deliberate no-daemon-cap choice"); assert.strictEqual(zeroDeps.__calls.committedEntries[0].resources.backupsMax, 0); const defaultDeps = makeDeps(); await createServerOnNode(defaultDeps, baseInput()); assert.strictEqual(defaultDeps.__calls.daemonPayloads[0].payload.resources.backupsMax, resolvePanelBackupsCap()); assert.ok(defaultDeps.__calls.daemonPayloads[0].payload.resources.backupsMax > 0, "the default must never be 0/undefined — either would disable the daemon cap"); assert.strictEqual(defaultDeps.__calls.committedEntries[0].resources.backupsMax, resolvePanelBackupsCap()); // adpanel:backup-cap-parse-hardening — garbage/negative explicit values // must degrade to the panel cap (the daemon's `if backupsMax > 0` reads // both 0-from-"abc" and a negative as "no cap", so the old // parseInt(x, 10) || 0 silently removed the bound). Explicit 0 stays 0. const garbageDeps = makeDeps(); await createServerOnNode(garbageDeps, baseInput({ body: { resources: { backupsMax: "abc" } } })); assert.strictEqual(garbageDeps.__calls.daemonPayloads[0].payload.resources.backupsMax, resolvePanelBackupsCap(), "garbage must degrade to the panel cap, never to unlimited"); assert.strictEqual(garbageDeps.__calls.committedEntries[0].resources.backupsMax, resolvePanelBackupsCap()); const negativeDeps = makeDeps(); await createServerOnNode(negativeDeps, baseInput({ body: { resources: { backupsMax: -5 } } })); assert.strictEqual(negativeDeps.__calls.daemonPayloads[0].payload.resources.backupsMax, resolvePanelBackupsCap(), "a negative must degrade to the panel cap, never reach the daemon's 'no cap' branch"); assert.strictEqual(negativeDeps.__calls.committedEntries[0].resources.backupsMax, resolvePanelBackupsCap()); const stringDeps = makeDeps(); await createServerOnNode(stringDeps, baseInput({ body: { resources: { backupsMax: "12" } } })); assert.strictEqual(stringDeps.__calls.daemonPayloads[0].payload.resources.backupsMax, 12, "string shapes from form inputs parse like numbers"); assert.strictEqual(stringDeps.__calls.committedEntries[0].resources.backupsMax, 12); }); test("panel renderer: the three name-guard 400 bodies are byte-pinned", () => { // Pin-gap fix from the Wave 1 review: the guard OUTCOMES were pinned, but // the panel renderings of the three name-guard bodies were only exercised // transitively. The wizard surfaces j.detail || j.message || j.error, so // the detail strings are wire contracts. assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "invalid_name_empty" }, "panel"), { status: 400, body: { error: "invalid name" } } ); assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "invalid_name_no_storage_form" }, "panel"), { status: 400, body: { error: "invalid name", detail: "name has no node-storable form" } } ); assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "invalid_name_storage_mismatch" }, "panel"), { status: 400, body: { error: "invalid name", detail: "names with leading or trailing underscores/dots are stored under a different name on the node, which breaks the file manager - choose a name without them", }, } ); }); test("success: exactly two audit records (server + _system), then the deferred import", async () => { // Base deps reject the archive URL, so no import fires there: const deps = makeDeps(); await createServerOnNode(deps, baseInput({ body: { importUrl: "https://example.com/modpack.zip" } })); assert.strictEqual(deps.__calls.runDeferredServerImport.length, 0); const deps2 = makeDeps({ isValidArchiveUrl: () => true }); await createServerOnNode(deps2, baseInput({ body: { importUrl: "https://example.com/modpack.zip" } })); assert.strictEqual(deps2.__calls.runDeferredServerImport.length, 1); assert.strictEqual(deps2.__calls.runDeferredServerImport[0].importUrl, "https://example.com/modpack.zip"); assert.strictEqual(deps2.__calls.runDeferredServerImport[0].serverName, "test-srv"); assert.strictEqual(deps2.__calls.runDeferredServerImport[0].rowId, 71); assert.strictEqual(deps2.__calls.daemonPayloads[0].payload.autoStart, false); assert.strictEqual(deps2.__calls.recordActivity.length, 2); const [perServer, perSystem] = deps2.__calls.recordActivity; assert.strictEqual(perServer.serverName, "test-srv"); assert.strictEqual(perServer.action, "server_create"); assert.deepStrictEqual(perServer.details, { template: "My Template", node: "Node One", port: 25565, displayName: "test srv", }); assert.strictEqual(perServer.userEmail, "admin@example.com"); assert.strictEqual(perServer.userIp, "203.0.113.7"); assert.strictEqual(perSystem.serverName, "_system"); assert.strictEqual(perSystem.action, "server_create"); assert.deepStrictEqual(perSystem.details, { server: "test-srv", template: "My Template", node: "Node One", port: 25565, }); assert.strictEqual("displayName" in perSystem.details, false); }); test("success: no deferred import without importUrl; admin gets no access grant", async () => { const deps = makeDeps(); await createServerOnNode(deps, baseInput()); assert.strictEqual(deps.__calls.runDeferredServerImport.length, 0); assert.strictEqual(deps.__calls.addAccessForEmail.length, 0, "acting admin already has access"); }); test("success: non-admin actor receives the best-effort access grant", async () => { const deps = makeDeps({ findUserByEmail: async () => ({ email: "helper@example.com", admin: false }) }); await createServerOnNode(deps, baseInput({ sessionUser: "helper@example.com" })); assert.deepStrictEqual(deps.__calls.addAccessForEmail, [{ email: "helper@example.com", server: "test-srv" }]); }); test("success: node identity, savedPort fallbacks and body.port alias", async () => { const deps = makeDeps(); // body.port (legacy alias) overrides the template default. await createServerOnNode(deps, baseInput({ body: { port: "3000" } })); assert.strictEqual(deps.__calls.daemonPayloads[0].payload.hostPort, 3000); assert.strictEqual(deps.__calls.committedEntries[0].port, 3000); // No default port on the template -> minecraft falls back to 25565. const deps2 = makeDeps({ findTemplateById: () => ({ id: "minecraft", name: "T", defaultPort: null, docker: null }), }); await createServerOnNode(deps2, baseInput()); assert.strictEqual(deps2.__calls.daemonPayloads[0].payload.hostPort, 25565); assert.strictEqual(deps2.__calls.committedEntries[0].port, 25565); }); test("legacy template ports are checked against the node pool before provisioning", async () => { for (const [templateId, ports, hostPort] of [ ["minecraft", [], 25565], ["nodejs", [3000], 3000], ["nodejs", [], 8080], ]) { const template = { id: templateId, name: "Legacy", docker: { ports } }; const templateDeps = { findTemplateById: () => template, normalizeTemplateId: () => templateId, normalizeTemplateDockerForRuntime: () => ({ image: "fixture", ports }), }; const blockedDeps = makeDeps({ ...templateDeps, isPortInNodeAllocation: () => false }); const blocked = await createServerOnNode(blockedDeps, baseInput({ templateId })); assert.strictEqual(blocked.code, "port_not_in_allocation"); assert.strictEqual(blocked.data.port, hostPort); assert.strictEqual(blockedDeps.__calls.daemonPayloads.length, 0); assert.strictEqual(blockedDeps.__calls.committedEntries.length, 0); const allowedDeps = makeDeps({ ...templateDeps, isPortInNodeAllocation: (_node, port) => port === hostPort }); assert.strictEqual((await createServerOnNode(allowedDeps, baseInput({ templateId }))).ok, true); assert.strictEqual(allowedDeps.__calls.daemonPayloads[0].payload.hostPort, hostPort); assert.strictEqual(allowedDeps.__calls.committedEntries[0].port, hostPort); } }); test("mcFork/mcVersion strict validation (real resolver) and javaVersion pinning", async () => { const badFork = await createServerOnNode(makeDeps(), baseInput({ body: { mcFork: "evil;rm" } })); assert.strictEqual(badFork.code, "invalid_mc_fork"); const badVersion = await createServerOnNode(makeDeps(), baseInput({ body: { mcVersion: "not-a-version" } })); assert.strictEqual(badVersion.code, "invalid_mc_version"); assert.strictEqual( renderServerCreateOutcome(badVersion, "panel").body.error, "Invalid mcVersion (expected e.g. 1.21.8, 1.21.8-pre1, 24w14a)" ); const deps = makeDeps(); await createServerOnNode(deps, baseInput({ body: { javaVersion: "21" } })); const { payload } = deps.__calls.daemonPayloads[0]; assert.strictEqual(payload.javaVersion, "21"); assert.strictEqual(payload.docker.javaVersion, "21"); assert.strictEqual(payload.docker.image, "eclipse-temurin", "javaVersion pins the process image"); assert.strictEqual(payload.docker.tag, "java-21"); const nodejsDeps = makeDeps({ normalizeTemplateId: () => "nodejs" }); const nonMc = await createServerOnNode(nodejsDeps, baseInput({ templateId: "nodejs", body: { javaVersion: "21" } })); assert.strictEqual(nonMc.code, "java_version_non_minecraft"); assert.strictEqual( renderServerCreateOutcome(nonMc, "panel").body.error, "Java version selection is only available for Minecraft templates." ); const unsupported = await createServerOnNode(makeDeps(), baseInput({ body: { javaVersion: "banana" } })); assert.strictEqual(unsupported.code, "java_version_unsupported"); assert.strictEqual( renderServerCreateOutcome(unsupported, "panel").body.error, "Unsupported Minecraft Java version." ); }); test("resources: node caps and validator messages render byte-identical 400s", async () => { const caps = { ramMb: 1024, cpuCores: 2, diskGb: 10 }; const ram = await createServerOnNode( makeDeps({ getEffectiveNodeCapacity: async () => caps }), baseInput({ body: { resources: { ramMb: 2048 } } }) ); assert.deepStrictEqual(renderServerCreateOutcome(ram, "panel"), { status: 400, body: { error: "RAM limit cannot exceed node maximum (1024 MB)." }, }); const cpu = await createServerOnNode( makeDeps({ getEffectiveNodeCapacity: async () => caps }), baseInput({ body: { resources: { cpuCores: 3 } } }) ); assert.deepStrictEqual(renderServerCreateOutcome(cpu, "panel"), { status: 400, body: { error: "CPU cores cannot exceed node maximum (2 cores)." }, }); const storage = await createServerOnNode( makeDeps({ getEffectiveNodeCapacity: async () => caps }), baseInput({ body: { resources: { storageGb: 11 } } }) ); assert.deepStrictEqual(renderServerCreateOutcome(storage, "panel"), { status: 400, body: { error: "Storage limit cannot exceed node maximum (10240 MB)." }, }); const options = await createServerOnNode( makeDeps({ collectResourcePerformanceOptions: () => { throw new Error("ioWeight must be a number between 1 and 1000"); }, }), baseInput() ); assert.deepStrictEqual(renderServerCreateOutcome(options, "panel"), { status: 400, body: { error: "ioWeight must be a number between 1 and 1000" }, }); }); test("diskId: unknown disk 400s, transport failure 502s, valid disk proceeds", async () => { const diskUrls = []; const diskHttp = async (url) => { diskUrls.push(url); return { status: 200, json: { ok: true, disks: [{ id: "disk-1" }] } }; }; const notOnNode = await createServerOnNode( makeDeps({ httpRequestJson: diskHttp }), baseInput({ body: { diskId: "disk-2" } }) ); assert.deepStrictEqual(renderServerCreateOutcome(notOnNode, "panel"), { status: 400, body: { error: "Target disk does not belong to this node." }, }); const transport = await createServerOnNode( makeDeps({ httpRequestJson: async () => { throw new Error("connect EHOSTUNREACH"); }, }), baseInput({ body: { diskId: "disk-1" } }) ); assert.deepStrictEqual(renderServerCreateOutcome(transport, "panel"), { status: 502, body: { error: "Failed to verify target disk on node." }, }); const deps = makeDeps({ httpRequestJson: diskHttp }); await createServerOnNode(deps, baseInput({ body: { diskId: "disk-1" } })); assert.strictEqual(deps.__calls.daemonPayloads[0].payload.diskId, "disk-1"); // The verify hits the node's /v1/disks endpoint (8s budget is pinned by the // withTimeout-less direct call contract of httpRequestJson in index.js). assert.ok(diskUrls.every((u) => u.endsWith("/v1/disks")), `disk verify URL must end in /v1/disks, got ${diskUrls[0]}`); }); test("port checks: allocation, panel conflict, live bind test, duplicate mapping", async () => { const notAllocated = await createServerOnNode( makeDeps({ isPortInNodeAllocation: () => false }), baseInput() ); assert.deepStrictEqual(renderServerCreateOutcome(notAllocated, "panel"), { status: 400, body: { error: "Port 25565 is not in this node's allocated ports (none). Choose ports within the node's allocation." }, }); const rangeNode = { ...NODE, ports: { mode: "range", start: 2000, count: 100 } }; const rangeMiss = await createServerOnNode( makeDeps({ isPortInNodeAllocation: () => false, findNodeByIdOrName: async () => rangeNode }), baseInput() ); assert.strictEqual( renderServerCreateOutcome(rangeMiss, "panel").body.error, "Port 25565 is not in this node's allocated ports (range 2000–2099). Choose ports within the node's allocation." ); const conflict = await createServerOnNode( makeDeps({ findServerUsingNodePort: async () => ({ name: "old-srv", displayName: "Old Server", bot: null }) }), baseInput() ); assert.deepStrictEqual(renderServerCreateOutcome(conflict, "panel"), { status: 409, body: { error: 'Port 25565 is already assigned to server "Old Server" on this node.', code: "port_in_use", port: 25565, server: "old-srv", }, }); const live = await createServerOnNode( makeDeps({ checkRemoteNodePortAvailability: async () => ({ verified: true, available: false, owner: "system-nginx", reason: "in use" }), }), baseInput() ); assert.deepStrictEqual(renderServerCreateOutcome(live, "panel"), { status: 409, body: { error: "Port 25565 is already in use on the node by system-nginx.", code: "port_in_use", port: 25565, owner: "system-nginx", reason: "in use", }, }); const liveNoOwner = await createServerOnNode( makeDeps({ checkRemoteNodePortAvailability: async () => ({ verified: true, available: false, owner: null, reason: null }), }), baseInput() ); const liveBody = renderServerCreateOutcome(liveNoOwner, "panel").body; assert.strictEqual(liveBody.error, "Port 25565 is already in use on the node."); assert.strictEqual(liveBody.owner, null); assert.strictEqual(liveBody.reason, null); const dupMapping = await createServerOnNode( makeDeps({ dockerTemplateHostPortRequirements: () => [{ hostPort: 25565, protocols: ["tcp"] }, { hostPort: 25565, protocols: ["udp"] }], }), baseInput() ); assert.deepStrictEqual(renderServerCreateOutcome(dupMapping, "panel"), { status: 400, body: { error: "Port 25565 would be used by more than one mapping. Choose a different main port or adjust the template ports." }, }); const badPort = await createServerOnNode(makeDeps(), baseInput({ body: { hostPort: "70000" } })); assert.deepStrictEqual(renderServerCreateOutcome(badPort, "panel"), { status: 400, body: { error: "Invalid port. Choose a value between 1 and 65535." }, }); }); test("startupCommand and command validation keep their exact 400s", async () => { const startup = await createServerOnNode(makeDeps(), baseInput({ body: { startupCommand: "docker run -d x" } })); assert.deepStrictEqual(renderServerCreateOutcome(startup, "panel"), { status: 400, body: { error: "Raw Docker startup commands are no longer supported. Server containers are now created from structured template settings only." }, }); const badCommand = await createServerOnNode(makeDeps(), baseInput({ body: { command: "rm -rf /" } })); assert.deepStrictEqual(renderServerCreateOutcome(badCommand, "panel"), { status: 400, body: { error: "Command not allowed" }, }); const deps = makeDeps(); await createServerOnNode(deps, baseInput({ body: { command: "java -Xmx1G -jar server.jar" } })); assert.strictEqual(deps.__calls.daemonPayloads[0].payload.docker.command, "java -Xmx1G -jar server.jar"); }); test("node deleted under the keyed lock: 410 before and after the daemon call", async () => { // Gone when the lock re-reads the node (before provisioning): the // resolution lookup still succeeds, the freshNode re-read under the // node-ports lock does not. let beforeLookups = 0; const beforeDeps = makeDeps({ findNodeByIdOrName: async () => { beforeLookups += 1; return beforeLookups === 1 ? NODE : null; }, }); const before = await createServerOnNode(beforeDeps, baseInput()); assert.strictEqual(beforeLookups, 2, "resolution + locked re-read"); assert.deepStrictEqual(renderServerCreateOutcome(before, "panel"), { status: 410, body: { error: "node deleted during create" }, }); assert.strictEqual(beforeDeps.__calls.daemonPayloads.length, 0, "no provisioning on a dead node"); // Gone while the daemon call is in flight: compensating delete runs, then 410. let daemonCalls = 0; let lookups = 0; const afterDeps = makeDeps({ findNodeByIdOrName: async () => { lookups += 1; return lookups <= 2 ? NODE : null; // resolution, freshNode, then gone post-daemon }, createOnRemoteNode: async (node, payload) => { daemonCalls += 1; return { ok: true, asyncSetup: true, meta: {} }; }, }); const after = await createServerOnNode(afterDeps, baseInput()); assert.strictEqual(daemonCalls, 1, "the daemon call itself succeeded"); // Wave-1 verification gap fix: the 410 path must have run the // ownership-guarded compensating delete before answering (the default fake // claim-row read returns no rows, so the guard proceeds to the delete). assert.strictEqual(afterDeps.__calls.deleteServerOnNode.length, 1, "the just-created daemon server is compensated before the 410"); assert.deepStrictEqual(renderServerCreateOutcome(after, "panel"), { status: 410, body: { error: "node deleted during create" }, }); }); test("early 400s: missing templateId, unknown template, nodeId required, no nodes, node not found", async () => { const noTemplate = await createServerOnNode(makeDeps(), baseInput({ templateId: "" })); assert.deepStrictEqual(renderServerCreateOutcome(noTemplate, "panel"), { status: 400, body: { error: "missing templateId" } }); const unknown = await createServerOnNode(makeDeps({ findTemplateById: () => null }), baseInput()); assert.deepStrictEqual(renderServerCreateOutcome(unknown, "panel"), { status: 400, body: { error: "unknown template" } }); const noNode = await createServerOnNode(makeDeps(), baseInput({ nodeId: "local" })); assert.deepStrictEqual(renderServerCreateOutcome(noNode, "panel"), { status: 400, body: { error: "nodeId required" } }); const emptyNode = await createServerOnNode(makeDeps(), baseInput({ nodeId: " " })); assert.strictEqual(emptyNode.code, "node_id_required"); const noNodes = await createServerOnNode(makeDeps({ loadNodes: async () => [] }), baseInput()); assert.deepStrictEqual(renderServerCreateOutcome(noNodes, "panel"), { status: 400, body: { error: "No nodes configured. Add a node before creating servers." }, }); const notFound = await createServerOnNode( makeDeps({ findNodeByIdOrName: async () => null }), baseInput() ); assert.deepStrictEqual(renderServerCreateOutcome(notFound, "panel"), { status: 400, body: { error: "node not found" } }); }); test("importUrl validation: archive grammar and SSRF guard 400s", async () => { const invalid = await createServerOnNode(makeDeps({ isValidArchiveUrl: () => false }), baseInput({ body: { importUrl: "https://example.com/x.txt" } })); assert.deepStrictEqual(renderServerCreateOutcome(invalid, "panel"), { status: 400, body: { error: "Invalid importUrl (must be http(s) and a supported archive extension)" }, }); const unsafe = await createServerOnNode( makeDeps({ isValidArchiveUrl: () => true, assertSafeRemoteUrl: async () => { throw new Error("blocked by policy"); }, }), baseInput({ body: { importUrl: "https://example.com/x.zip" } }) ); assert.deepStrictEqual(renderServerCreateOutcome(unsafe, "panel"), { status: 400, body: { error: "Unsafe importUrl: blocked by policy" }, }); }); // --------------------------------------------------------------------------- // 7. Lock contract (fail-closed) // --------------------------------------------------------------------------- test("missing lock refuses to run before any provisioning work", async () => { for (const lock of [undefined, null, {}, { release: "not-a-function" }]) { const deps = makeDeps(); await assert.rejects( createServerOnNode(deps, baseInput({ lock })), /lock\.release is required/, `lock = ${JSON.stringify(lock)} must be refused` ); assert.strictEqual(deps.__calls.dbQuery.length, 0, "no DB work without the lock"); assert.strictEqual(deps.__calls.daemonPayloads.length, 0, "no daemon work without the lock"); assert.strictEqual(deps.__calls.committedEntries.length, 0, "no commit without the lock"); } }); // --------------------------------------------------------------------------- // Renderer contract pins (variants are per-entry-point; "panel" is reference) // --------------------------------------------------------------------------- test("renderServerCreateOutcome: fails loudly on unknown codes and variants", () => { assert.throws(() => renderServerCreateOutcome({ ok: false, code: "totally_unknown" }, "panel"), /unmapped outcome code/); // Variants that have not joined the service yet must refuse to render — // "tool" (dashboard-assistant) joined in campaign step 2b, so a // hypothetical new entry point stands in for the un-joined case here. assert.throws(() => renderServerCreateOutcome({ ok: false, code: "invalid_name_empty" }, "route"), /unknown variant/); // The proxy renders its success body itself (the daemon JSON verbatim), so a // success outcome must never be routed through the panel's 3-field shape. assert.throws( () => renderServerCreateOutcome({ ok: true, code: "success", data: { name: "x", displayName: "y" } }, "proxy"), /success body itself/ ); // index_commit_failed is proxy-only: the panel rethrows non-dup commit // failures into its route's 500 catch instead of rendering this body. assert.throws( () => renderServerCreateOutcome({ ok: false, code: "index_commit_failed", data: { detail: "boom" } }, "panel"), /unmapped outcome code/ ); }); // --------------------------------------------------------------------------- // 8. Proxy variant (node proxy, POST /api/nodes/:id/servers/create) — the // shared outcome codes render the proxy's own byte-exact tokens/sentences // --------------------------------------------------------------------------- test("renderServerCreateOutcome proxy: name guards keep missing_name / invalid_name tokens", () => { assert.deepStrictEqual(renderServerCreateOutcome({ ok: false, code: "invalid_name_empty" }, "proxy"), { status: 400, body: { error: "missing_name" }, }); assert.deepStrictEqual(renderServerCreateOutcome({ ok: false, code: "invalid_name_no_storage_form" }, "proxy"), { status: 400, body: { error: "invalid_name", detail: "name has no node-storable form" }, }); assert.deepStrictEqual(renderServerCreateOutcome({ ok: false, code: "invalid_name_storage_mismatch" }, "proxy"), { status: 400, body: { error: "invalid_name", detail: "names with leading or trailing underscores/dots are stored under a different name on the node, which breaks the file manager - choose a name without them" }, }); }); test("renderServerCreateOutcome proxy: duplicate 409 drops the '(on node X)' suffix", () => { const rendered = renderServerCreateOutcome( { ok: false, code: "server_name_exists", data: { name: "test-srv", onNode: " (on node n9)" } }, "proxy" ); assert.deepStrictEqual(rendered, { status: 409, body: { error: 'A server named "test-srv" already exists. Choose a different name.', code: "server_name_exists", }, }); }); test("renderServerCreateOutcome proxy: storage-collision body is identical to panel's", () => { const outcome = { ok: false, code: "server_name_storage_collision", data: { collidingName: "other-srv", name: "test-srv" } }; assert.deepStrictEqual(renderServerCreateOutcome(outcome, "proxy"), renderServerCreateOutcome(outcome, "panel")); }); test("renderServerCreateOutcome proxy: template-deleted uses the 'not available on the panel' sentence with the raw id", () => { assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "template_deleted_during_create", data: { templateName: "custom-mc" } }, "proxy"), { status: 409, body: { error: 'Template "custom-mc" is not available on the panel (it may have been deleted while the server was being created). Choose another template and retry.', code: "template_deleted_during_create", }, } ); // Panel renders the SAME code with its own sentence (display name). assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "template_deleted_during_create", data: { templateName: "custom-mc" } }, "panel").body.error, 'Template "custom-mc" was deleted while the server was being created. Choose another template and retry.' ); }); test("renderServerCreateOutcome proxy: index_commit_failed carries the detail", () => { assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "index_commit_failed", data: { detail: "db exploded" } }, "proxy"), { status: 500, body: { error: "index_commit_failed", detail: "db exploded" } } ); }); // --------------------------------------------------------------------------- // 9. Shared storage-collision scan, proxy wiring (4-way identity + uuid->id) // --------------------------------------------------------------------------- test("scanNodeStorageCollisions proxy: exact 4-way SQL (ip leg, uuid falls back to id) and alias trigger", async () => { const deps = makeDeps({ __collisionRows: [{ name: "other-srv", legacy_id: "test-srv", bot: null }] }); const outcome = await scanNodeStorageCollisions(deps, NODE, "test-srv", { includeIpLeg: true, uuidFallbackId: true }); assert.strictEqual(outcome.ok, false); assert.strictEqual(outcome.code, "server_name_storage_collision"); assert.deepStrictEqual(outcome.data, { collidingName: "other-srv", name: "test-srv" }); assert.deepStrictEqual(deps.__calls.dbQuery[0], { sql: "SELECT name, legacy_id, bot FROM servers WHERE node_id = ? OR node_id = ? OR LOWER(node_id) = ? OR ip = ?", params: ["n1", "u1", "node one", "203.0.113.5"], }); }); test("scanNodeStorageCollisions proxy: uuid-less node falls back to the id in the second leg", async () => { const deps = makeDeps(); const uuidLessNode = { ...NODE, uuid: "" }; await scanNodeStorageCollisions(deps, uuidLessNode, "test-srv", { includeIpLeg: true, uuidFallbackId: true }); assert.deepStrictEqual(deps.__calls.dbQuery[0].params, ["n1", "n1", "node one", "203.0.113.5"]); }); test("scanNodeStorageCollisions panel: 3-way SQL without the ip leg and bare uuid param", async () => { const deps = makeDeps(); const outcome = await scanNodeStorageCollisions(deps, NODE, "test-srv", {}); assert.strictEqual(outcome, null); assert.deepStrictEqual(deps.__calls.dbQuery[0], { sql: "SELECT name, legacy_id, bot FROM servers WHERE node_id = ? OR node_id = ? OR LOWER(node_id) = ?", params: ["n1", "u1", "node one"], }); }); test("scanNodeStorageCollisions: collision via bot alias; same-name rows skipped", async () => { const botDeps = makeDeps({ __collisionRows: [{ name: "other-srv", legacy_id: null, bot: "test-srv" }] }); const botOutcome = await scanNodeStorageCollisions(botDeps, NODE, "test-srv", { includeIpLeg: true, uuidFallbackId: true }); assert.strictEqual(botOutcome.code, "server_name_storage_collision"); assert.strictEqual(botOutcome.data.collidingName, "other-srv"); const sameNameDeps = makeDeps({ __collisionRows: [{ name: "Test-Srv", legacy_id: null, bot: null }] }); assert.strictEqual(await scanNodeStorageCollisions(sameNameDeps, NODE, "test-srv", { includeIpLeg: true, uuidFallbackId: true }), null); // A DB throw propagates to the caller (panel: withTimeout catch; proxy: // route wrapper 500) — the scan never swallows it. const throwingDeps = makeDeps(); throwingDeps.dbQuery = async () => { throw new Error("db down"); }; await assert.rejects( scanNodeStorageCollisions(throwingDeps, NODE, "test-srv", { includeIpLeg: true, uuidFallbackId: true }), /db down/ ); }); // --------------------------------------------------------------------------- // 10. duplicateServerNameOutcome under proxy wiring (no withTimeout injected) // --------------------------------------------------------------------------- test("duplicateServerNameOutcome: without withTimeout it awaits findServer directly (proxy liveness contract)", async () => { const deps = makeDeps({ findServer: async () => ({ name: "test-srv", nodeId: "n9" }) }); delete deps.withTimeout; const outcome = await duplicateServerNameOutcome(deps, "test-srv"); assert.strictEqual(outcome.code, "server_name_exists"); assert.strictEqual(deps.__calls.withTimeout.length, 0, "no bound was added"); const rendered = renderServerCreateOutcome(outcome, "proxy"); assert.strictEqual(rendered.body.error, 'A server named "test-srv" already exists. Choose a different name.'); assert.ok(!rendered.body.error.includes("(on node"), "proxy renders no node suffix"); // Still null when the name is free. const freeDeps = makeDeps(); delete freeDeps.withTimeout; assert.strictEqual(await duplicateServerNameOutcome(freeDeps, "test-srv"), null); }); // --------------------------------------------------------------------------- // 11. commitCreatedServer — the shared guarded-commit choreography // --------------------------------------------------------------------------- function proxyCommitLog() { // The proxy's per-caller strings live in nodes.js (PROXY_COMMIT_LOG); tests // pass an equivalent shape and exercise the builders' dispatch path. The // nodes.js strings themselves are log-only (not wire contracts) and are // deliberately not duplicated here, so their byte content is unpinned. return { tag: "[node-proxy-create]", level: "error", notWiredWithheld: (name) => `index writer missing and compensating delete of "${name}" was WITHHELD — the committed index row claims this name on this node, so the daemon server may belong to another worker's live create; it was left intact`, notWiredError: (name) => `index writer missing and ownership-guarded compensating delete of "${name}" failed — server may be orphaned on the node:`, templateDeletedWithheld: (name) => `template deleted during create and compensating delete of "${name}" was WITHHELD — the committed index row claims this name on this node, so the daemon server may belong to another worker's live create; it was left intact`, templateDeletedError: (name) => `template deleted during create and compensating delete of "${name}" failed — server is orphaned on the node:`, commitWithheld: (name) => `index commit failed and compensating delete of "${name}" was WITHHELD — the committed index row claims this name on this node, so the daemon server belongs to another writer's live create; winner left intact`, commitError: (name) => `index commit failed and ownership-guarded compensating delete of "${name}" failed — server may be orphaned on the node:`, }; } test("commitCreatedServer proxy: template_deleted outcome renders the proxy 409 after compensation", async () => { const deps = makeDeps({ insertServerIndexEntryGuarded: async () => ({ ok: false, reason: "template_deleted" }) }); const outcome = await commitCreatedServer(deps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "custom-mc", notWiredDetail: "server index writer not wired", rethrowNonDup: false, log: proxyCommitLog(), }); assert.deepStrictEqual(outcome, { ok: false, code: "template_deleted_during_create", data: { templateName: "custom-mc" } }); assert.deepStrictEqual(renderServerCreateOutcome(outcome, "proxy").body, { error: 'Template "custom-mc" is not available on the panel (it may have been deleted while the server was being created). Choose another template and retry.', code: "template_deleted_during_create", }); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 1, "compensating delete ran"); }); test("commitCreatedServer proxy: ER_DUP_ENTRY -> plain 409; non-dup -> index_commit_failed (no rethrow)", async () => { const dupDeps = makeDeps({ insertServerIndexEntryGuarded: async () => { throw Object.assign(new Error('a server index entry named "test-srv" already exists'), { code: "ER_DUP_ENTRY" }); }, }); const dup = await commitCreatedServer(dupDeps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "minecraft", rethrowNonDup: false, log: proxyCommitLog(), }); assert.deepStrictEqual(dup, { ok: false, code: "server_name_exists", data: { name: "test-srv", onNode: "" } }); assert.deepStrictEqual(renderServerCreateOutcome(dup, "proxy"), { status: 409, body: { error: 'A server named "test-srv" already exists. Choose a different name.', code: "server_name_exists" }, }); assert.strictEqual(dupDeps.__calls.deleteServerOnNode.length, 1); const otherDeps = makeDeps({ insertServerIndexEntryGuarded: async () => { throw new Error("db exploded"); }, }); const other = await commitCreatedServer(otherDeps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "minecraft", rethrowNonDup: false, log: proxyCommitLog(), }); assert.deepStrictEqual(other, { ok: false, code: "index_commit_failed", data: { detail: "db exploded" } }); assert.deepStrictEqual(renderServerCreateOutcome(other, "proxy"), { status: 500, body: { error: "index_commit_failed", detail: "db exploded" }, }); assert.strictEqual(otherDeps.__calls.deleteServerOnNode.length, 1); }); test("commitCreatedServer panel: non-dup commit errors rethrow into the route's 500 catch", async () => { const deps = makeDeps({ insertServerIndexEntryGuarded: async () => { throw new Error("db exploded"); }, }); await assert.rejects( commitCreatedServer(deps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "My Template", logTag: "[/api/servers/create]", rethrowNonDup: true, }), /db exploded/ ); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 1, "compensation still runs before the rethrow"); }); test("commitCreatedServer proxy: missing guarded writer fails closed with the not-wired detail", async () => { const deps = makeDeps({ insertServerIndexEntryGuarded: null }); const outcome = await commitCreatedServer(deps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "minecraft", notWiredDetail: "server index writer not wired", rethrowNonDup: false, log: proxyCommitLog(), }); assert.deepStrictEqual(outcome, { ok: false, code: "index_commit_failed", data: { detail: "server index writer not wired" } }); assert.deepStrictEqual(renderServerCreateOutcome(outcome, "proxy"), { status: 500, body: { error: "index_commit_failed", detail: "server index writer not wired" }, }); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 1, "the created daemon server is compensated away"); assert.strictEqual(deps.__calls.committedEntries.length, 0); }); test("commitCreatedServer: success returns null and commits nothing else", async () => { const deps = makeDeps(); const outcome = await commitCreatedServer(deps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "minecraft", rethrowNonDup: true, }); assert.strictEqual(outcome, null); assert.deepStrictEqual(deps.__calls.committedEntries, [{ name: "test-srv" }]); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 0); }); test("commitCreatedServer: compensation withhold leaves the delete to the ownership guard", async () => { const deps = makeDeps({ insertServerIndexEntryGuarded: async () => ({ ok: false, reason: "template_deleted" }), __ownershipRows: [{ name: "test-srv", node_id: "u1", ip: null }], }); const outcome = await commitCreatedServer(deps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "minecraft", rethrowNonDup: false, log: proxyCommitLog(), }); assert.strictEqual(outcome.code, "template_deleted_during_create"); assert.strictEqual(deps.__calls.deleteServerOnNode.length, 0, "a row claiming the name on this node is never deleted"); }); // --------------------------------------------------------------------------- // 12. Tool variant (dashboard-assistant create_server, campaign step 2b) — // prose envelopes rendered from the shared outcome codes // --------------------------------------------------------------------------- test("renderServerCreateOutcome tool: name guards render the tool's prose invalid_name envelopes", () => { // Byte-identical to the former inline buildMaskedError strings in // utils/dashboard-assistant-tools.js (spec section 3.3). assert.deepStrictEqual(renderServerCreateOutcome({ ok: false, code: "invalid_name_no_storage_form" }, "tool"), { envelope: { ok: false, error: "That name has no node-storable form. Choose a name made of letters, numbers, dots, dashes or underscores.", code: "invalid_name", }, }); assert.deepStrictEqual(renderServerCreateOutcome({ ok: false, code: "invalid_name_storage_mismatch" }, "tool"), { envelope: { ok: false, error: "Names with leading or trailing underscores/dots are stored under a different name on the node, which breaks the file manager - choose a name without them.", code: "invalid_name", }, }); }); test("renderServerCreateOutcome tool: commit outcomes render byte-identical tool envelopes", () => { // ER_DUP_ENTRY outcome (data.onNode is the panel-only suffix; ignored here). assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "server_name_exists", data: { name: "test-srv", onNode: "" } }, "tool"), { envelope: { ok: false, error: 'A server named "test-srv" already exists. Choose a different name.', code: "server_name_exists", }, } ); // The tool uses the PANEL's template-deleted sentence. assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "template_deleted_during_create", data: { templateName: "Vanilla" } }, "tool"), { envelope: { ok: false, error: 'Template "Vanilla" was deleted while the server was being created. Choose another template and retry.', code: "template_deleted_during_create", }, } ); // Non-dup commit failure: the tool's prose envelope with the detail. assert.deepStrictEqual( renderServerCreateOutcome({ ok: false, code: "index_commit_failed", data: { detail: "db exploded" } }, "tool"), { envelope: { ok: false, error: "Failed to create that server.", detail: "db exploded" } } ); }); test("renderServerCreateOutcome tool: collision envelope is byte-identical to the HTTP body; other codes refuse", () => { const outcome = { ok: false, code: "server_name_storage_collision", data: { collidingName: "other-srv", name: "test-srv" } }; assert.deepStrictEqual(renderServerCreateOutcome(outcome, "tool").envelope, { ok: false, ...renderServerCreateOutcome(outcome, "panel").body, }); // The tool variant renders ONLY the codes its shared steps and its // collision outcome can produce — an HTTP-only code must not silently leak // a { status, body } shape into a tool envelope. assert.throws( () => renderServerCreateOutcome({ ok: false, code: "missing_template_id" }, "tool"), /unmapped outcome code .* for variant "tool"/ ); assert.throws(() => renderServerCreateOutcome({ ok: false, code: "totally_unknown" }, "tool"), /unmapped outcome code/); // The tool builds its success envelope itself (buildSuccess), like the proxy. assert.throws( () => renderServerCreateOutcome({ ok: true, code: "success", data: { name: "x", displayName: "y" } }, "tool"), /success body itself/ ); }); // --------------------------------------------------------------------------- // 13. Ownership guard with a caller-owned claim-row read (tool wiring) — // the tool feeds deleteOwnOrphanServerOnNodeForCreate from its injected // servers-index readers instead of the canonical SQL read // --------------------------------------------------------------------------- test("deleteOwnOrphanServerOnNodeForCreate: readClaimRows replaces the SQL read and keeps the withhold rules", async () => { const scenarios = [ { rows: [{ name: "test-srv", node_id: "u1", ip: null }], expect: "withheld", reason: "claims via uuid" }, { rows: [{ name: "test-srv", node_id: "", ip: "203.0.113.5" }], expect: "withheld", reason: "claims via address" }, { rows: [{ name: "test-srv", node_id: null, ip: null }], expect: "withheld", reason: "no node_id/ip (fail closed)" }, { rows: [{ name: "test-srv", node_id: "other-node", ip: "198.51.100.9" }], expect: "deleted", reason: "claimed on a DIFFERENT node" }, { rows: [], expect: "deleted", reason: "unclaimed name" }, ]; for (const scenario of scenarios) { const deleted = []; const deps = { readClaimRows: async (name) => { assert.strictEqual(name, "test-srv", "the guard passes the raw name to the caller-owned read"); return scenario.rows; }, deleteServerOnNode: async (node, name) => { deleted.push({ node, name }); }, }; const outcome = await deleteOwnOrphanServerOnNodeForCreate(deps, NODE, "test-srv"); if (scenario.expect === "withheld") { assert.strictEqual(outcome.withheld, true, scenario.reason); assert.strictEqual(deleted.length, 0, scenario.reason); } else { assert.strictEqual(outcome.deleted, true, scenario.reason); assert.deepStrictEqual(deleted, [{ node: NODE, name: "test-srv" }], scenario.reason); } } }); test("deleteOwnOrphanServerOnNodeForCreate: readClaimRows throw is a read failure that never deletes (phase marked)", async () => { const deps = { readClaimRows: async () => { // Tagged wiring-gap error (the assistant tool tags its "no reader dep" // case): the guard must pass the error object through untouched so the // caller's log router can branch on the tag. const unwired = new Error("no servers-index reader dep is wired"); unwired.noServersIndexReaderDep = true; throw unwired; }, deleteServerOnNode: async () => { throw new Error("must not be reached"); }, }; const outcome = await deleteOwnOrphanServerOnNodeForCreate(deps, NODE, "test-srv"); assert.strictEqual(outcome.deleted, false); assert.match(String(outcome.error), /no servers-index reader dep is wired/); assert.strictEqual(outcome.error.noServersIndexReaderDep, true, "tag survives for the caller's log router"); assert.strictEqual(outcome.phase, "read", "mode-aware callers route the read-failure line off this"); }); test("deleteOwnOrphanServerOnNodeForCreate: readClaimRows without dbQuery deletes via the caller-owned leg only", async () => { // No dbQuery in deps at all: with readClaimRows wired the canonical SQL // read must not even be attempted (the tool has no dbQuery). let readCalls = 0; const deps = { readClaimRows: async () => { readCalls += 1; return []; }, deleteServerOnNode: async () => {}, }; const outcome = await deleteOwnOrphanServerOnNodeForCreate(deps, NODE, "test-srv"); assert.strictEqual(outcome.deleted, true); assert.strictEqual(readCalls, 1); assert.strictEqual("dbQuery" in deps, false); }); test("deleteOwnOrphanServerOnNodeForCreate: delete-phase failure carries phase delete (read succeeded)", async () => { const deps = { readClaimRows: async () => [], deleteServerOnNode: async () => { throw new Error("daemon gone"); }, }; const outcome = await deleteOwnOrphanServerOnNodeForCreate(deps, NODE, "test-srv"); assert.strictEqual(outcome.deleted, false); assert.match(String(outcome.error), /daemon gone/); assert.strictEqual(outcome.phase, "delete"); }); // --------------------------------------------------------------------------- // 14. commitCreatedServer ctx.compensate (tool wiring) — the caller-owned // compensation hook replaces the built-in guard call AND its logCfg // emission; the failure outcome choreography is unchanged // --------------------------------------------------------------------------- test("commitCreatedServer: ctx.compensate owns compensation and outcomes stay byte-identical", async () => { const kinds = []; const compensate = (kind) => { kinds.push(kind); }; // template_deleted path const tplDeps = makeDeps({ insertServerIndexEntryGuarded: async () => ({ ok: false, reason: "template_deleted" }) }); const tplOutcome = await commitCreatedServer(tplDeps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "My Template", rethrowNonDup: false, logTag: "[dashboard-assistant create_server]", compensate, }); assert.deepStrictEqual(kinds, ["template_deleted"]); assert.deepStrictEqual(tplOutcome, { ok: false, code: "template_deleted_during_create", data: { templateName: "My Template" } }); assert.strictEqual(tplDeps.__calls.deleteServerOnNode.length, 0, "the built-in canonical guard is bypassed"); // commit-failed paths: ER_DUP_ENTRY and non-dup const dupDeps = makeDeps({ insertServerIndexEntryGuarded: async () => { throw Object.assign(new Error('a server index entry named "test-srv" already exists'), { code: "ER_DUP_ENTRY" }); }, }); const dupOutcome = await commitCreatedServer(dupDeps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "minecraft", rethrowNonDup: false, logTag: "[dashboard-assistant create_server]", compensate, }); assert.deepStrictEqual(kinds, ["template_deleted", "commit_failed"]); assert.deepStrictEqual(dupOutcome, { ok: false, code: "server_name_exists", data: { name: "test-srv", onNode: "" } }); // The tool renderer ignores the panel-only onNode suffix data. assert.deepStrictEqual(renderServerCreateOutcome(dupOutcome, "tool").envelope, { ok: false, error: 'A server named "test-srv" already exists. Choose a different name.', code: "server_name_exists", }); const otherDeps = makeDeps({ insertServerIndexEntryGuarded: async () => { throw new Error("db exploded"); }, }); const otherOutcome = await commitCreatedServer(otherDeps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "minecraft", rethrowNonDup: false, logTag: "[dashboard-assistant create_server]", compensate, }); assert.deepStrictEqual(kinds, ["template_deleted", "commit_failed", "commit_failed"]); assert.deepStrictEqual(otherOutcome, { ok: false, code: "index_commit_failed", data: { detail: "db exploded" } }); assert.deepStrictEqual(renderServerCreateOutcome(otherOutcome, "tool").envelope, { ok: false, error: "Failed to create that server.", detail: "db exploded", }); // Success: compensate is never called, outcome null. kinds.length = 0; const okDeps = makeDeps(); const okOutcome = await commitCreatedServer(okDeps, { entry: { name: "test-srv" }, name: "test-srv", node: NODE, templateName: "minecraft", rethrowNonDup: false, logTag: "[dashboard-assistant create_server]", compensate, }); assert.strictEqual(okOutcome, null); assert.deepStrictEqual(kinds, []); assert.deepStrictEqual(okDeps.__calls.committedEntries, [{ name: "test-srv" }]); }); test("the tool's compensation reader chain keeps the protective order (spec correction 11)", () => { // Structural pin for Wave 1's one deliberate behavior delta: the reader // chain in the tool's createServerCreateCompensationDeps must lead with the // fresh deleting-inclusive reader (closing the stale-cache destroy window) // and keep deleting-inclusive ahead of deleting-exclusive behind it. A // revert would re-open that window silently — this pin makes it loud. const fs = require("node:fs"); const nodePath = require("node:path"); const src = fs.readFileSync(nodePath.join(__dirname, "..", "utils", "dashboard-assistant-tools.js"), "utf8"); const fresh = src.indexOf('deps.loadServersIndexForSubscribeFresh === "function"'); const cached = src.indexOf('deps.loadServersIndexForSubscribe === "function"'); const live = src.indexOf('deps.loadServersIndexFresh === "function"'); const base = src.indexOf('deps.loadServersIndex === "function"'); assert.ok(fresh !== -1 && cached !== -1 && live !== -1 && base !== -1, "expected the four-reader chain in createServerCreateCompensationDeps"); assert.ok(fresh < cached && cached < live && live < base, "reader order drifted: the fresh deleting-inclusive reader must lead, and deleting-inclusive must stay ahead of deleting-exclusive"); });