"use strict"; // Tests for the store-install review pipeline (audit finding "The install UI // hides exactly the fields that matter"). // // The old flow let the browser POST the whole template JSON on install while // the store card showed only name/description/image, so an admin approved a // marketing summary while persisting whatever the page's JS sent (install // script, volumes, env, startup command). The remediation under test: // 1. Install requests carry a REFERENCE (category + file + sha256); the // panel resolves content from its own store cache and refuses a hash // mismatch, so persisted content == reviewed content. // 2. Both ingestion paths (manual create + store install) share // constructTemplateDefinition, so they enforce identical invariants. // 3. The review dialog's summarizeStoreTemplatePayload (frontend copy in // settings.js) mirrors that constructor field-for-field — the summary // the admin approves IS the object that gets persisted. // // index.js boots servers on require, so the constructor and its validator // closure are sliced out of the source and evaluated in a vm sandbox (same // technique as template-store-local-override.test.js and // runtime-process-command.test.js). 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 INDEX_JS = path.join(__dirname, "..", "index.js"); const SETTINGS_JS = path.join(__dirname, "..", "public", "js", "settings.js"); const payloadSanitizers = require("../utils/server-template-payload"); function endIndexOfFunction(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found`); const bodyStart = source.indexOf("{", start); let depth = 0; for (let i = bodyStart; i < source.length; i += 1) { if (source[i] === "{") depth += 1; else if (source[i] === "}") { depth -= 1; if (depth === 0) return i + 1; } } assert.fail(`unbalanced braces after marker ${startMarker}`); } function sliceFunction(source, startMarker) { const end = endIndexOfFunction(source, startMarker); return source.slice(source.indexOf(startMarker), end); } function buildPanelCode() { const source = fs.readFileSync(INDEX_JS, "utf8"); return [ // The image-registry allowlist constant constructTemplateDefinition reads // (declared next to the store constants in index.js; mirrored here). "const TEMPLATE_IMAGE_ALLOWLIST = resolveAllowedTemplateRegistries(process.env.ADPANEL_TEMPLATE_ALLOWED_REGISTRIES);", // validatePort + validatePortListInput. sliceFunction(source, "function validatePort(port)"), sliceFunction(source, "function validatePortListInput"), sliceFunction(source, "function normalizeTemplateId(tpl)"), // sanitizeTemplateImageUrl lives near the store routes. sliceFunction(source, "function sanitizeTemplateImageUrl"), // Command/console/startup validator closure (contiguous region). source.slice( source.indexOf("function sanitizeRuntimeCommandInput"), endIndexOfFunction(source, "function shouldAutoAlignBotDirVolume") ), sliceFunction(source, "function constructTemplateDefinition"), sliceFunction(source, "function slugifyTemplateDefinitionId"), ].join("\n"); } function buildConstructor() { const sandbox = { console: { log() { }, warn() { }, error() { } }, path, URL, preferBundledMediaUrl: require("../utils/branding").preferBundledMediaUrl, process: { env: {} }, sanitizeEnvPayload: payloadSanitizers.sanitizeEnvPayload, validateTemplateEnvPayload: payloadSanitizers.validateTemplateEnvPayload, sanitizeDockerInstallPayload: payloadSanitizers.sanitizeDockerInstallPayload, sanitizePortProtocolPayload: payloadSanitizers.sanitizePortProtocolPayload, validateTemplateVolumeListPayload: payloadSanitizers.validateTemplateVolumeListPayload, // The script-boundary validators live in utils/server-template-payload.js // (shared with the node agent's mirrors); constructTemplateDefinition calls // them for the fail-closed 400 on adpanelStartup / install.script. validateADPanelStartupScriptInput: payloadSanitizers.validateADPanelStartupScriptInput, validateTemplateInstallScriptInput: payloadSanitizers.validateTemplateInstallScriptInput, // constructTemplateDefinition now also enforces the image-registry // allowlist through utils/template-store-trust.js (mirrored by the node // agent); provide the same exports index.js requires. ...require("../utils/template-store-trust"), // adpanel:surrogate-safe-cut — the sliced contiguous region contains // sanitizeRuntimeCommandInput, which caps through the shared helper // (utils/safe-truncate.js); provide the real one so the isolated // evaluation exercises the production cut, like the other injected // shared modules above. safeTruncateUtf16: require("../utils/safe-truncate").safeTruncateUtf16, }; vm.createContext(sandbox); vm.runInContext(buildPanelCode(), sandbox); return { construct: vm.runInContext("constructTemplateDefinition", sandbox), slugify: vm.runInContext("slugifyTemplateDefinitionId", sandbox), }; } const { construct, slugify } = buildConstructor(); function buildClientSummary() { const source = fs.readFileSync(SETTINGS_JS, "utf8"); // adpanel:surrogate-safe-cut — summarizeStoreTemplatePayload normalizes the // reviewed command through the frontend's sanitizeRuntimeCommandInput twin // (settings.js inlines the trailing-lone-high drop, mirroring // utils/safe-truncate.js, because the browser bundle cannot require the // Node helper). Both twin functions are self-contained, so they are sliced // in alongside the summarizer — same technique as the panel closure above, // which instead receives the real helper injected. const slice = [ sliceFunction(source, "function isHighSurrogate"), sliceFunction(source, "function sanitizeRuntimeCommandInput"), sliceFunction(source, "function summarizeStoreTemplatePayload"), ].join("\n"); return new Function("window", `${slice}\nreturn summarizeStoreTemplatePayload;`)({ ADPanelTemplateVolumes: require("../public/js/template-volumes") }); } const summarize = buildClientSummary(); // The frontend's own id slugifier — the server-side slugify must agree with it. const clientSlugify = new Function( `${sliceFunction(fs.readFileSync(SETTINGS_JS, "utf8"), "function slugifyTemplateId")}\nreturn slugifyTemplateId;` )(); const FULL_STORE_PAYLOAD = { id: "review-test", name: "Review Test", description: "integration fixture", defaultPort: 25565, docker: { image: "eclipse-temurin", tag: "21-jre", ports: [25565], portProtocols: { 25565: ["tcp", "udp", "bogus"] }, volumes: ["{BOT_DIR}:/data"], workdir: "/data", // Every env entry must satisfy the fail-closed boundary (an invalid one // now rejects the whole install — see the boundary tests below), so the // fixture carries only well-formed keys. env: { EULA: "TRUE", MEMORY: "" }, command: "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui", install: { image: "ghcr.io/pterodactyl/installers:debian", script: "echo hello\ncurl -fsSL https://example.invalid/x.sh | sh", mountPath: "/mnt/server", runtimePath: "/home/container", timeoutSeconds: 900, env: { INSTALLER_TOKEN: "abc" }, }, }, }; test("constructor persists the full executable payload a store install carries", () => { const { tpl, error } = construct(FULL_STORE_PAYLOAD); assert.strictEqual(error, undefined); assert.strictEqual(tpl.id, "review-test"); assert.strictEqual(tpl.name, "Review Test"); assert.strictEqual(tpl.description, "integration fixture"); assert.strictEqual(tpl.defaultPort, 25565); assert.strictEqual(tpl.docker.image, "eclipse-temurin"); assert.strictEqual(tpl.docker.tag, "21-jre"); assert.deepEqual(tpl.docker.ports, [25565]); // Invalid protocols are dropped at ingestion, never stored. assert.deepEqual(tpl.docker.portProtocols, { 25565: ["tcp", "udp"] }); assert.deepEqual(tpl.docker.volumes, ["{BOT_DIR}:/data"]); assert.strictEqual(tpl.docker.workdir, "/data"); assert.deepEqual(tpl.docker.env, { EULA: "TRUE", MEMORY: "" }); assert.strictEqual(tpl.docker.command, "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui"); // The install script — the actual shell payload — is stored verbatim. That // is exactly why the review dialog must render it before approval. assert.strictEqual(tpl.docker.install.script, "echo hello\ncurl -fsSL https://example.invalid/x.sh | sh"); assert.strictEqual(tpl.docker.install.image, "ghcr.io/pterodactyl/installers:debian"); assert.strictEqual(tpl.docker.install.timeoutSeconds, 900); assert.deepEqual(tpl.docker.install.env, { INSTALLER_TOKEN: "abc" }); }); test("constructor rejects the dangerous and malformed shapes", () => { const cases = [ [{ id: "x1", name: "No Image" }, /missing docker image/], [{ id: "Bad Id!", name: "N", docker: { image: "img" } }, /invalid id/], [{ id: "x1", name: "N", docker: { image: "img" }, startup_command: "docker run -it alpine" }, /Raw Docker startup commands/], [{ id: "x1", name: "N", docker: { image: "img", workdir: "data" } }, /invalid workdir/], [{ id: "x1", name: "N", docker: { image: "img", ports: [99999] } }, /invalid ports/], [{ id: "x1", name: "N", docker: { image: "img", command: "node app.js;curl" } }, /[Ss]hell control operator/], [{ id: "x1", name: "N", docker: { image: "img", adpanelStartup: "cat /var/run/docker.sock" } }, /docker\.sock/], [{ id: "x1", name: "N", docker: { image: "img" }, template_image: "not a url" }, /invalid template image url/], [{ id: "x1", name: "N", docker: { image: "img" }, install: { script: " " } }, undefined], ]; for (const [input, expected] of cases) { const result = construct(input); if (expected) { assert.match(result.error, expected); assert.strictEqual(result.status, 400); } else { // An install payload whose script sanitizes to nothing persists without // an install job rather than failing. assert.strictEqual(result.error, undefined); assert.strictEqual(result.tpl.docker.install, undefined); } } }); test("constructor auto-adds the bot-dir volume for a workdir-only template", () => { const { tpl, error } = construct({ id: "workdir-only", name: "Workdir Only", docker: { image: "img", workdir: "/app" }, }); assert.strictEqual(error, undefined); assert.deepEqual(tpl.docker.volumes, ["{BOT_DIR}:/app"]); }); // --- Env boundary (audit finding: invalid/oversized env entries were // silently dropped with 200 OK, so the admin's "Template created!" produced // servers running without the env they reviewed — inconsistent with the // fail-closed volume boundary above). Ingestion must now answer 400 naming // the rejected entry instead of storing a partial env. test("constructor fails closed on env entries the panel refuses to persist", () => { const cases = [ [{ id: "e1", name: "E", docker: { image: "img", env: { "MY VAR": "x" } } }, /invalid env key "MY VAR"/], [{ id: "e2", name: "E", docker: { image: "img", env: { "PATH=/evil": "smuggled" } } }, /invalid env key/], [{ id: "e3", name: "E", docker: { image: "img", env: JSON.parse('{"__proto__":"{}"}') } }, /invalid env key/], [{ id: "e4", name: "E", docker: { image: "img", env: { BIG: "v".repeat(32769) } } }, /env value for "BIG" is too long/], [{ id: "e5", name: "E", docker: { image: "img", env: { OBJ: { nested: true } } } }, /invalid env value for "OBJ"/], // Top-level env (the manual create body shape) is boundary-checked too. [{ id: "e6", name: "E", docker: { image: "img" }, env: { "SP ACE": "x" } }, /invalid env key "SP ACE"/], ]; for (const [input, expected] of cases) { const result = construct(input); assert.match(result.error, expected, JSON.stringify(input)); assert.strictEqual(result.status, 400, JSON.stringify(input)); assert.strictEqual(result.tpl, undefined, JSON.stringify(input)); } // Entry cap: 129 entries reject the request instead of silently truncating. const bigEnv = {}; for (let i = 0; i < 129; i++) bigEnv[`K${String(i).padStart(3, "0")}`] = "v"; const capped = construct({ id: "e7", name: "E", docker: { image: "img", env: bigEnv } }); assert.match(capped.error, /too many env entries \(max 128\)/); assert.strictEqual(capped.status, 400); // Present-but-null env stays a valid "no variables" request (destructure // semantics: null does not fall through to docker.env). const noEnv = construct({ id: "e8", name: "E", docker: { image: "img", env: null } }); assert.strictEqual(noEnv.error, undefined); assert.deepEqual(noEnv.tpl.docker.env, {}); }); test("review summary flags env shapes the server now rejects", () => { const flagged = summarize({ id: "env-bad", name: "EB", docker: { image: "img", env: { "MY VAR": "x" } } }); assert.strictEqual(flagged.envInvalid, true); // Oversized and object-valued entries are boundary failures too. assert.strictEqual( summarize({ id: "env-big", name: "EB2", docker: { image: "img", env: { BIG: "v".repeat(32769) } } }).envInvalid, true ); assert.strictEqual( summarize({ id: "env-obj", name: "EB3", docker: { image: "img", env: { OBJ: {} } } }).envInvalid, true ); // Non-object env (a string leaked into the store JSON) rejects on both sides. assert.strictEqual(summarize({ id: "env-str", name: "EB4", docker: { image: "img", env: "FOO=bar" } }).envInvalid, true); const built = construct({ id: "env-str2", name: "EB5", docker: { image: "img", env: "FOO=bar" } }); assert.match(built.error, /expected an object/); const clean = summarize({ id: "env-ok", name: "EO", docker: { image: "img", env: { GOOD: "1" } } }); assert.strictEqual(clean.envInvalid, false); assert.deepEqual(clean.env, { GOOD: "1" }); // install.env stays on the silent normalizer mirror (not boundary-checked), // so the dialog shows exactly the entries that would persist. const installerEnv = summarize({ id: "env-inst", name: "EI", docker: { image: "img", install: { script: "echo hi", env: { "MY VAR": "x", OK: "1" } } }, }); assert.strictEqual(installerEnv.install.env.OK, "1"); assert.strictEqual(installerEnv.install.env["MY VAR"], undefined); }); // --- Install-script boundary (audit finding: docker.command is validated as // pure argv while the sibling install.script field ran with zero semantic // checks, making the "no shell semantics in templates" promise an illusion). // Install scripts are legitimately full shell scripts, so they get the managed // startup's boundary rule instead: no container-runtime sockets/CLIs, no // namespace tools, no host namespaces — fail closed at the ingestion boundary. test("constructor rejects install scripts that reach for the container boundary", () => { const cases = [ [{ id: "i1", name: "I", docker: { image: "img", install: { script: "docker run --privileged -v /:/host alpine" } } }, /Install scripts cannot reference/], [{ id: "i2", name: "I", docker: { image: "img", install: { script: "curl --unix-socket /var/run/docker.sock http://x/version" } } }, /docker\.sock/], [{ id: "i3", name: "I", docker: { image: "img", install: { script: "apt-get install -y docker.io" } } }, /Install scripts cannot reference "docker"/], [{ id: "i4", name: "I", docker: { image: "img", install: { script: "nsenter -t 1 -m -- /bin/sh" } } }, /nsenter/], [{ id: "i5", name: "I", docker: { image: "img", install: { script: "unshare --mount" } } }, /unshare/], [{ id: "i6", name: "I", docker: { image: "img", install: { script: "echo --network=host" } } }, /--network=host/], // One bad line rejects the whole request, like volumes. [{ id: "i7", name: "I", docker: { image: "img", install: { script: "apt-get update\npodman info" } } }, /podman/], ]; for (const [input, expected] of cases) { const result = construct(input); assert.match(result.error, expected, input.id); assert.strictEqual(result.status, 400, input.id); assert.strictEqual(result.tpl, undefined, input.id); } }); test("constructor still accepts the install scripts templates legitimately ship", () => { const { tpl, error } = construct({ id: "iok", name: "Installer OK", docker: { image: "img", install: { script: "#!/bin/bash\napt-get update && apt-get install -y curl\ncurl -fsSL https://example.invalid/x.sh | sh\ntar -xzf game.tar.gz -C /mnt/server", image: "ghcr.io/pterodactyl/installers:debian", }, }, }); assert.strictEqual(error, undefined); assert.ok(tpl.docker.install.script.includes("apt-get update")); }); test("review summary flags boundary-violating install scripts exactly when the server rejects them", () => { const bad = [ { id: "b1", name: "B", docker: { image: "img", install: { script: "docker exec -it x sh" } } }, { id: "b2", name: "B", docker: { image: "img", install: { script: "cat /run/podman.sock" } } }, ]; for (const payload of bad) { const result = construct(payload); assert.match(result.error, /Install scripts cannot reference/, payload.id); assert.strictEqual(result.status, 400, payload.id); const summary = summarize(payload); assert.strictEqual(summary.installScriptInvalid, true, payload.id); } const good = { id: "g1", name: "G", docker: { image: "img", install: { script: "curl -fsSL https://example.invalid/x.sh | sh" } } }; const built = construct(good); assert.strictEqual(built.error, undefined); const summary = summarize(good); assert.strictEqual(summary.installScriptInvalid, false); assert.ok(summary.install.script.includes("curl")); }); // --- Volumes at the create/store-install boundary (audit finding: trim-only // validation let hostile mount specs into templates.json; the only real gate // was the node agent's bind allowlist one layer downstream). The constructor // shared by both ingestion paths must now reject them with a 400. test("constructor rejects volume mounts that reference host filesystem paths", () => { const cases = [ [{ id: "v1", name: "V", docker: { image: "img", volumes: ["/etc:/host-etc"] } }], [{ id: "v2", name: "V", docker: { image: "img", volumes: ["/var/run/docker.sock:/var/run/docker.sock"] } }], [{ id: "v3", name: "V", docker: { image: "img", volumes: ["{BOT_DIR}/../..:/escape"] } }], // One poisoned spec among valid ones still rejects the whole request. [{ id: "v4", name: "V", docker: { image: "img", volumes: ["{BOT_DIR}:/data", "host:relative"] } }], // Single-string form, the other legacy request shape. [{ id: "v5", name: "V", docker: { image: "img", volumes: "/etc:/etc" } }], // Backslash smuggling a Windows-style host path as a "named volume". [{ id: "v6", name: "V", docker: { image: "img", volumes: ["\\etc\\passwd:/x"] } }], ]; for (const [input] of cases) { const result = construct(input); assert.match(result.error, /invalid volumes/, input.id); assert.strictEqual(result.status, 400, input.id); assert.strictEqual(result.tpl, undefined, input.id); } }); test("constructor persists the valid mount shapes the node agent allowlists", () => { const { tpl, error } = construct({ id: "vok", name: "Valid Mounts", docker: { image: "img", volumes: ["{BOT_DIR}:/data", "{BOT_DIR}/worlds:/data/worlds:ro", "{DATA_DIR}:/config"], }, }); assert.strictEqual(error, undefined); assert.deepStrictEqual(tpl.docker.volumes, [ "{BOT_DIR}:/data", "{BOT_DIR}/worlds:/data/worlds:ro", "{DATA_DIR}:/config", ]); }); test("review summary flags invalid volumes exactly when the server rejects them", () => { const bad = [ { id: "b1", name: "B", docker: { image: "img", volumes: ["/etc:/host"] } }, { id: "b2", name: "B", docker: { image: "img", volumes: ["{BOT_DIR}/..:/x"] } }, { id: "b3", name: "B", docker: { image: "img", volumes: "host:relative" } }, { id: "b4", name: "B", docker: { image: "img", volumes: ["\\etc\\passwd:/x"] } }, { id: "b5", name: "B", docker: { image: "img", volumes: ["mcdata:/data"] } }, { id: "b6", name: "B", docker: { image: "img", volumes: ["{BOT_DIR}:/data", "{BOT_DIR}:/data/"] } }, ]; for (const payload of bad) { const result = construct(payload); assert.match(result.error, /invalid volumes/, payload.id); const summary = summarize(payload); assert.strictEqual(summary.volumesInvalid, true, payload.id); assert.deepStrictEqual(summary.volumes, [], payload.id); } const good = { id: "g1", name: "G", docker: { image: "img", volumes: ["{BOT_DIR}:/data:ro", "{BOT_DIR}:/config"] } }; const built = construct(good); assert.strictEqual(built.error, undefined); const summary = summarize(good); assert.strictEqual(summary.volumesInvalid, false); assert.deepStrictEqual(summary.volumes, built.tpl.docker.volumes); }); test("server-side id slugify matches the frontend slugify the listing used", () => { const inputs = [ "Minecraft Java Server", " --weird__id-- ", "Valheim+Plus v2 (2024).json", "x".repeat(80), "", "Ünïcödé", ]; for (const input of inputs) { assert.strictEqual(slugify(input), clientSlugify(input), `slug mismatch for ${JSON.stringify(input)}`); } }); // The core invariant: the summary rendered in the review dialog is exactly the // object the panel persists. Any drift here means the admin approves X while // the panel stores Y. test("review summary equals the persisted template for a full store payload", () => { const summary = summarize(FULL_STORE_PAYLOAD); const { tpl, error } = construct(FULL_STORE_PAYLOAD); assert.strictEqual(error, undefined); assert.strictEqual(summary.image, tpl.docker.image); assert.strictEqual(summary.tag, tpl.docker.tag); assert.deepEqual(summary.ports, tpl.docker.ports); assert.deepEqual(summary.portProtocols, tpl.docker.portProtocols); assert.deepEqual(summary.volumes, tpl.docker.volumes); assert.deepEqual(summary.env, tpl.docker.env); assert.strictEqual(summary.command, tpl.docker.command); assert.strictEqual(summary.workdir, tpl.docker.workdir); assert.strictEqual(summary.defaultPort, tpl.defaultPort); assert.deepEqual(summary.install, { image: tpl.docker.install.image, script: tpl.docker.install.script, mountPath: tpl.docker.install.mountPath, runtimePath: tpl.docker.install.runtimePath, timeoutSeconds: tpl.docker.install.timeoutSeconds, minimumStorageMb: 0, allowEmpty: false, env: tpl.docker.install.env, }); // Nothing outside the summary is persisted: the persisted docker object // carries no keys the summary does not render. const rendered = new Set([ "image", "tag", "ports", "portProtocols", "volumes", "workdir", "env", "command", "install", "restart", "console", ]); for (const key of Object.keys(tpl.docker)) { assert.ok(rendered.has(key), `persisted key "${key}" is not covered by the review summary`); } }); test("review summary mirrors managed-startup and precedence handling", () => { // A managed startup script suppresses the plain argv command at persistence, // so the summary must not present one as if it will run. const withScript = summarize({ id: "precedence", name: "Precedence", docker: { image: "node", env: { FROM_DOCKER: "1" }, command: "fallback-command", adpanelStartup: "echo managed\r\nstart", }, }); const withScriptBuilt = construct(withScriptPayloadFixture()); assert.strictEqual(withScript.command, ""); assert.strictEqual(withScript.adpanelStartup, "echo managed\nstart"); assert.strictEqual(withScriptBuilt.tpl.docker.command, undefined); assert.strictEqual(withScriptBuilt.tpl.docker.adpanelStartup, "echo managed\nstart"); // env falls back to docker.env only when the top-level key is absent. assert.deepEqual(withScript.env, { FROM_DOCKER: "1" }); assert.deepEqual(withScriptBuilt.tpl.docker.env, { FROM_DOCKER: "1" }); // Without a managed script, the plain command persists and is shown as-is. const plain = summarize({ id: "plain", name: "P", docker: { image: "i", command: "java -jar app.jar" } }); const plainBuilt = construct({ id: "plain2", name: "P", docker: { image: "i", command: "java -jar app.jar" } }); assert.strictEqual(plain.command, "java -jar app.jar"); assert.strictEqual(plainBuilt.tpl.docker.command, "java -jar app.jar"); // hasBodyField('command') semantics: a top-level command key beats // docker.command. const override = summarize({ id: "c", name: "C", docker: { image: "i", command: "docker-command" }, command: "top-level-command" }); assert.strictEqual(override.command, "top-level-command"); }); // Kept as a function so both sides of the parity assertions above consume the // identical fixture object. function withScriptPayloadFixture() { return { id: "precedence", name: "Precedence", docker: { image: "node", env: { FROM_DOCKER: "1" }, command: "fallback-command", adpanelStartup: "echo managed\r\nstart", }, }; } test("review summary flags shapes the server will reject instead of hiding them", () => { const flagged = summarize({ id: "legacy", name: "Legacy", docker: { image: "img" }, startup_command: "docker run -it alpine" }); assert.match(flagged.legacyStartupCommand, /docker run/); const invalidPorts = summarize({ id: "bad-ports", name: "BP", docker: { image: "img", ports: ["abc"] } }); assert.strictEqual(invalidPorts.portsInvalid, true); const cleanPorts = summarize({ id: "ok-ports", name: "OP", docker: { image: "img", ports: ["25565", 7777] } }); assert.deepEqual(cleanPorts.ports, [25565, 7777]); assert.strictEqual(cleanPorts.portsInvalid, false); }); test("review summary mirrors install-job sanitization defaults", () => { const summary = summarize({ id: "defaults", name: "Defaults", docker: { image: "img", install: { script: "line1\r\nline2\0line3", mountPath: "relative/path", runtimePath: "/home/container///", timeoutSeconds: 5, minimumStorageMb: 999999999, }, }, }); const { tpl } = construct({ id: "defaults2", name: "Defaults2", docker: { image: "img", install: { script: "line1\r\nline2\0line3", mountPath: "relative/path", runtimePath: "/home/container///", timeoutSeconds: 5, minimumStorageMb: 999999999, }, }, }); assert.strictEqual(summary.install.script, tpl.docker.install.script); assert.strictEqual(summary.install.mountPath, tpl.docker.install.mountPath); assert.strictEqual(summary.install.runtimePath, tpl.docker.install.runtimePath); assert.strictEqual(summary.install.timeoutSeconds, tpl.docker.install.timeoutSeconds); assert.strictEqual(summary.install.minimumStorageMb, tpl.docker.install.minimumStorageMb); assert.strictEqual(summary.install.image, "ghcr.io/pterodactyl/installers:debian"); // NUL never survives ingestion on either side. assert.ok(!summary.install.script.includes("\0")); }); test("empty payloads summarize without throwing and match the server outcome", () => { const summary = summarize(null); assert.strictEqual(summary.image, ""); assert.strictEqual(summary.portsInvalid, false); assert.deepEqual(summary.ports, []); assert.deepEqual(summary.env, {}); assert.strictEqual(summary.install, null); const { tpl, error } = construct({}); assert.match(error, /invalid id/); assert.strictEqual(tpl, undefined); }); // --- Present-but-falsy parity matrix ------------------------------------------ // constructTemplateDefinition used to resolve several fields through // destructuring defaults, which fire only on `undefined`: a PRESENT-BUT-NULL // key suppressed the whole fallback chain while the review dialog's `||` chain // fell through to the next source. A store payload could therefore render a // benign docker.install script in the dialog while the panel persisted a // malicious installation script. The matrix below pins both resolvers to // identical results for every shape: (a) key absent + docker-level value, // (b) key present-but-null + docker-level value, (c) value at both levels — // the persisted template field must EQUAL the summary field the dialog // renders, and rejected shapes must reject (or banner) on both sides. const PARITY_BASE = { id: "parity", name: "Parity", docker: { image: "img" } }; function parityPayload(overrides) { const { docker, ...rest } = overrides || {}; return { ...PARITY_BASE, ...rest, docker: { ...PARITY_BASE.docker, ...docker }, }; } const INSTALL_BENIGN = { image: "ghcr.io/pterodactyl/installers:debian", script: "echo benign-setup" }; const INSTALL_DOCKER_BENIGN = { image: "ghcr.io/pterodactyl/installers:debian", script: "echo installer-level-benign" }; // Deliberately passes the container-boundary validators: the divergence under // test is resolution semantics, not script-content policy — the malicious // script must be eligible for persistence so a mismatch would be observable. const INSTALL_MALICIOUS = { image: "ghcr.io/pterodactyl/installers:debian", script: "echo owned > /mnt/server/.pwned-by-review-bypass" }; test("parity matrix: present-but-falsy keys resolve identically on both sides", () => { // Accepted cases: the persisted template field must equal the summary field // the dialog renders. `|| undefined` normalizes the dialog's "not rendered" // empty strings against the template's absent keys. const cases = [ // dockerImage { label: "dockerImage absent + docker.image", payload: parityPayload({}), get: s => s.image, tplGet: t => t.docker.image, expected: "img" }, { label: "dockerImage present-but-null + docker.image", payload: parityPayload({ dockerImage: null }), get: s => s.image, tplGet: t => t.docker.image, expected: "img" }, { label: "dockerImage present + docker.image", payload: parityPayload({ dockerImage: "top-img" }), get: s => s.image, tplGet: t => t.docker.image, expected: "top-img" }, // dockerTag { label: "dockerTag absent + docker.tag", payload: parityPayload({ docker: { tag: "docker-tag" } }), get: s => s.tag, tplGet: t => t.docker.tag, expected: "docker-tag" }, { label: "dockerTag present-but-null + docker.tag", payload: parityPayload({ dockerTag: null, docker: { tag: "docker-tag" } }), get: s => s.tag, tplGet: t => t.docker.tag, expected: "docker-tag" }, { label: "dockerTag present + docker.tag", payload: parityPayload({ dockerTag: "top-tag", docker: { tag: "docker-tag" } }), get: s => s.tag, tplGet: t => t.docker.tag, expected: "top-tag" }, // templateImage — icon/logo are card artwork only, neither side persists them { label: "templateImage absent + template_image", payload: parityPayload({ template_image: "https://example.invalid/a.png" }), get: s => s.templateImage, tplGet: t => t.templateImage, expected: "https://example.invalid/a.png" }, { label: "templateImage present-but-null + template_image", payload: parityPayload({ templateImage: null, template_image: "https://example.invalid/a.png" }), get: s => s.templateImage, tplGet: t => t.templateImage, expected: "https://example.invalid/a.png" }, { label: "templateImage present + template_image", payload: parityPayload({ templateImage: "https://example.invalid/top.png", template_image: "https://example.invalid/a.png" }), get: s => s.templateImage, tplGet: t => t.templateImage, expected: "https://example.invalid/top.png" }, { label: "icon alias resolves to nothing on both sides", payload: parityPayload({ icon: "https://example.invalid/icon.png" }), get: s => s.templateImage, tplGet: t => t.templateImage, expected: "" }, { label: "templateImage null does not fall through to icon", payload: parityPayload({ templateImage: null, icon: "https://example.invalid/icon.png" }), get: s => s.templateImage, tplGet: t => t.templateImage, expected: "" }, // adpanelStartup (+ pterodactyl aliases) { label: "adpanelStartup absent + docker.adpanelStartup", payload: parityPayload({ docker: { adpanelStartup: "echo from-docker" } }), get: s => s.adpanelStartup, tplGet: t => t.docker.adpanelStartup, expected: "echo from-docker" }, { label: "adpanelStartup present-but-null + docker.adpanelStartup", payload: parityPayload({ adpanelStartup: null, docker: { adpanelStartup: "echo from-docker" } }), get: s => s.adpanelStartup, tplGet: t => t.docker.adpanelStartup, expected: "echo from-docker" }, { label: "adpanelStartup present + docker.adpanelStartup", payload: parityPayload({ adpanelStartup: "echo from-top", docker: { adpanelStartup: "echo from-docker" } }), get: s => s.adpanelStartup, tplGet: t => t.docker.adpanelStartup, expected: "echo from-top" }, { label: "adpanelStartup null falls through to the adpanel_startup alias", payload: parityPayload({ adpanelStartup: null, adpanel_startup: "echo from-alias", docker: { adpanelStartup: "echo from-docker" } }), get: s => s.adpanelStartup, tplGet: t => t.docker.adpanelStartup, expected: "echo from-alias" }, // dockerWorkdir/workdir: the ?? chain must match on both sides { label: "dockerWorkdir absent + docker.workdir", payload: parityPayload({ docker: { workdir: "/data" } }), get: s => s.workdir, tplGet: t => t.docker.workdir, expected: "/data" }, { label: "dockerWorkdir present-but-null + docker.workdir", payload: parityPayload({ dockerWorkdir: null, docker: { workdir: "/data" } }), get: s => s.workdir, tplGet: t => t.docker.workdir, expected: "/data" }, { label: "dockerWorkdir null skips to docker.workdir, not body workdir", payload: parityPayload({ dockerWorkdir: null, workdir: "/top", docker: { workdir: "/docker" } }), get: s => s.workdir, tplGet: t => t.docker.workdir, expected: "/docker" }, { label: "dockerWorkdir present + docker.workdir", payload: parityPayload({ dockerWorkdir: "/top", docker: { workdir: "/docker" } }), get: s => s.workdir, tplGet: t => t.docker.workdir, expected: "/top" }, { label: "empty docker.workdir stops the ?? chain on both sides", payload: parityPayload({ docker: { workdir: "", workingDir: "/wd" } }), get: s => s.workdir, tplGet: t => t.docker.workdir, expected: "" }, // defaultPort / ports / env / volumes / command: undefined-only semantics // on BOTH sides (frontend ternaries, backend destructuring defaults). { label: "defaultPort present-but-null falls back to the first port", payload: parityPayload({ defaultPort: null, docker: { ports: [25565] } }), get: s => s.defaultPort, tplGet: t => t.defaultPort, expected: 25565 }, { label: "ports present-but-null resolves to no ports", payload: parityPayload({ ports: null }), get: s => s.ports, tplGet: t => t.docker.ports, expected: [] }, { label: "env present-but-null resolves to no env", payload: parityPayload({ env: null }), get: s => s.env, tplGet: t => t.docker.env, expected: {} }, { label: "volumes present-but-null falls back to the workdir volume", payload: parityPayload({ volumes: null, docker: { workdir: "/data" } }), get: s => s.volumes, tplGet: t => t.docker.volumes, expected: ["{BOT_DIR}:/data"] }, { label: "command absent falls back to docker.command", payload: parityPayload({ docker: { command: "java -jar app.jar" } }), get: s => s.command, tplGet: t => t.docker.command, expected: "java -jar app.jar" }, ]; for (const c of cases) { const summary = summarize(c.payload); const built = construct(c.payload); assert.strictEqual(built.error, undefined, c.label); // The two resolvers live in different realms (vm sandbox vs host), so // array/object fields must be compared by JSON: strict on types and // structure, immune to realm prototypes. "" normalizes to null to match // the template's absent keys (the dialog hides an empty value). const jsonOf = (value) => JSON.stringify(value === "" || value === undefined ? null : value); assert.strictEqual(jsonOf(c.get(summary)), jsonOf(c.tplGet(built.tpl)), c.label); assert.deepStrictEqual(c.get(summary), c.expected, c.label); } // Rejected shapes: the server must reject exactly where the dialog warns. const rejectedCases = [ { label: "startupCommand present-but-null falls through to startup_command on both sides", payload: parityPayload({ startupCommand: null, startup_command: "docker run -it alpine" }), rejects: /Raw Docker startup commands/, banner: (s) => /docker run/.test(s.legacyStartupCommand), }, { label: "dockerImage null with no docker.image rejects and the dialog shows it", payload: parityPayload({ dockerImage: null, docker: { image: null } }), rejects: /missing docker image/, banner: (s) => s.image === "", }, ]; for (const c of rejectedCases) { const built = construct(c.payload); assert.match(built.error, c.rejects, c.label); assert.strictEqual(built.status, 400, c.label); assert.strictEqual(c.banner(summarize(c.payload)), true, c.label); } }); test("review dialog and persisted template agree on install-script sources (audit exploit)", () => { // The auditor's exploit: a present-but-null body-level install key used to // suppress the docker-level fallback on the backend (destructuring defaults // fire only on `undefined`) while the dialog's `||` chain fell through — // the dialog showed the benign docker.install script while the panel // persisted the malicious installation script. Both resolvers must land on // the same object now, and the malicious script must appear nowhere in what // is persisted. const exploit = parityPayload({ install: null, installation: INSTALL_MALICIOUS, docker: { install: INSTALL_DOCKER_BENIGN }, }); const built = construct(exploit); assert.strictEqual(built.error, undefined); const summary = summarize(exploit); assert.strictEqual(summary.install.script, INSTALL_DOCKER_BENIGN.script); assert.strictEqual(built.tpl.docker.install.script, INSTALL_DOCKER_BENIGN.script); assert.ok(!JSON.stringify(built.tpl).includes("pwned-by-review-bypass")); // docker.installation variant of the same exploit. const dockerVariant = parityPayload({ install: null, docker: { install: INSTALL_DOCKER_BENIGN, installation: INSTALL_MALICIOUS }, }); const builtVariant = construct(dockerVariant); assert.strictEqual(builtVariant.error, undefined); assert.strictEqual(summarize(dockerVariant).install.script, INSTALL_DOCKER_BENIGN.script); assert.strictEqual(builtVariant.tpl.docker.install.script, INSTALL_DOCKER_BENIGN.script); assert.ok(!JSON.stringify(builtVariant.tpl).includes("pwned-by-review-bypass")); // Precedence sanity: a present install wins over every installation source, // and a body-level installation only applies when no install source exists. const bothLevels = parityPayload({ install: INSTALL_BENIGN, installation: INSTALL_MALICIOUS }); const builtBoth = construct(bothLevels); assert.strictEqual(builtBoth.error, undefined); assert.strictEqual(summarize(bothLevels).install.script, INSTALL_BENIGN.script); assert.strictEqual(builtBoth.tpl.docker.install.script, INSTALL_BENIGN.script); assert.ok(!JSON.stringify(builtBoth.tpl).includes("pwned-by-review-bypass")); const installationOnly = parityPayload({ installation: INSTALL_BENIGN }); const builtOnly = construct(installationOnly); assert.strictEqual(builtOnly.error, undefined); assert.strictEqual(summarize(installationOnly).install.script, INSTALL_BENIGN.script); assert.strictEqual(builtOnly.tpl.docker.install.script, INSTALL_BENIGN.script); // Null at every level resolves to "no install" on both sides. const allNull = parityPayload({ install: null, installation: null, docker: { install: null, installation: null } }); assert.strictEqual(summarize(allNull).install, null); const builtNull = construct(allNull); assert.strictEqual(builtNull.error, undefined); assert.strictEqual(builtNull.tpl.docker.install, undefined); }); // --- Store-install reference resolution (resolveStoreTemplateInstallEntry) ---- // The install request carries only {category, fileName, entryIndex, sha256}; // this is the function that turns that reference into template content — or // a fail-closed refusal. Sliced from index.js like the constructor above. const resolver = (() => { const source = fs.readFileSync(INDEX_JS, "utf8"); const slice = sliceFunction(source, "function resolveStoreTemplateInstallEntry"); return new Function(`${slice}\nreturn resolveStoreTemplateInstallEntry;`)(); })(); const HASH_A = "a".repeat(64); const HASH_B = "b".repeat(64); function storeListingWith(files) { return { files: files.map(f => ({ name: f.name, sha256: f.sha256, payload: f.payload, type: "file" })) }; } test("resolver pins installs to the reviewed file content and entry", () => { const single = storeListingWith([{ name: "single.json", sha256: HASH_A, payload: { id: "s", name: "S", docker: { image: "img" } } }]); assert.strictEqual(resolver(single, "single.json", HASH_A, 0).payload.id, "s"); // An object file has exactly one entry — index != 0 must not resolve. assert.strictEqual(resolver(single, "single.json", HASH_A, 1).status, 404); const bundle = storeListingWith([{ name: "bundle.json", sha256: HASH_A, payload: [ { id: "first", name: "First", docker: { image: "img" } }, { id: "second", name: "Second", docker: { image: "img2" } }, ], }]); assert.strictEqual(resolver(bundle, "bundle.json", HASH_A, 0).payload.id, "first"); assert.strictEqual(resolver(bundle, "bundle.json", HASH_A, 1).payload.id, "second"); assert.strictEqual(resolver(bundle, "bundle.json", HASH_A, 2).status, 404); }); test("resolver fails closed on drift, unknown files and non-object entries", () => { const store = storeListingWith([{ name: "t.json", sha256: HASH_A, payload: [{ id: "ok", name: "OK", docker: { image: "img" } }, "not-an-object"], }]); // Hash drift between review and install → 409 with the retryable code. const drifted = resolver(store, "t.json", HASH_B, 0); assert.strictEqual(drifted.status, 409); assert.strictEqual(drifted.code, "store-template-changed"); assert.match(drifted.error, /changed since it was reviewed/); // Unknown file. assert.strictEqual(resolver(store, "missing.json", HASH_A, 0).status, 404); // A non-object array entry can never resolve. assert.strictEqual(resolver(store, "t.json", HASH_A, 1).status, 404); // Missing listing at all. assert.strictEqual(resolver(null, "t.json", HASH_A, 0).status, 404); }); // --- Client item shape: the reference the page sends must name the card ------ const clientExtractEntries = (() => { const source = fs.readFileSync(SETTINGS_JS, "utf8"); const helpers = [ sliceFunction(source, "function sanitizeTemplateStoreAssetUrl"), sliceFunction(source, "function getStoreTemplateDockerImage"), sliceFunction(source, "function normalizeStoreTemplateEntry"), sliceFunction(source, "function extractStoreTemplateEntries"), sliceFunction(source, "function slugifyTemplateId"), ].join("\n"); const sandbox = { URL, templateStoreItemCache: new Map() }; vm.createContext(sandbox); vm.runInContext(helpers, sandbox); return vm.runInContext("extractStoreTemplateEntries", sandbox); })(); test("store cards carry the hash and array entry index the install reference needs", () => { const file = { name: "bundle.json", path: "games/bundle.json", sha256: HASH_A }; const category = { id: "games", label: "Games" }; const entries = clientExtractEntries( [{ id: "a", name: "A", docker: { image: "x" } }, { id: "b", name: "B" }], file, category ); assert.equal(entries.length, 2); assert.strictEqual(entries[0].sha256, HASH_A); assert.strictEqual(entries[0].payloadIndex, 0); assert.strictEqual(entries[1].sha256, HASH_A); assert.strictEqual(entries[1].payloadIndex, 1); assert.strictEqual(entries[1].fileName, "bundle.json"); }); test("catalog preview images are local without changing reviewed template content", async () => { const category = { id: "games", label: "Games" }; const payload = [ { id: "hytale", templateImage: "https://cdn.jsdelivr.net/gh/antonndev/ADCDn@main/hytale-logo.avif" }, { id: "cs2", image: "https://cdn.cloudflare.steamstatic.com/steam/apps/730/header.jpg" }, { id: "custom", icon: "https://example.invalid/custom.webp" }, ]; const file = { name: "bundle.json", path: "games/bundle.json", sha256: HASH_A, payload }; const source = fs.readFileSync(INDEX_JS, "utf8"); const route = 'app.get("/api/settings/template-store/:category",'; let list; vm.runInNewContext([ sliceFunction(source, "function sanitizeTemplateImageUrl"), `${sliceFunction(source, route)});`, ].join("\n"), { URL, preferBundledMediaUrl: require("../utils/branding").preferBundledMediaUrl, isAdmin: () => true, safeTemplateStoreCategoryId: value => value, readTemplateStoreCategoryFromCache: () => ({ category, files: [file] }), app: { get: (_path, handler) => { list = handler; } }, }); const response = await list({ params: { category: "games" } }, { json: value => value }); const listed = response.files[0]; assert.strictEqual(listed.payload, payload); assert.strictEqual(listed.sha256, HASH_A); assert.ok(!Object.hasOwn(file, "previewImages")); const cards = clientExtractEntries(listed.payload, listed, category); assert.deepStrictEqual(Array.from(cards, card => card.image), [ "/images/hytale-logo.avif", "/images/cs2.avif", "https://example.invalid/custom.webp", ]); cards.forEach((card, index) => { assert.strictEqual(card.payload, payload[index]); assert.strictEqual(card.payloadIndex, index); assert.strictEqual(card.sha256, HASH_A); }); });