Files
Kelx/tests/template-listing-sanitization.test.js
T
2026-11-30 16:32:37 +00:00

347 lines
15 KiB
JavaScript

"use strict";
// Tests for the GET /api/templates listing sanitization (audit finding: the
// route leaked full template definitions to every non-admin user).
//
// GET /api/templates was the ONLY template endpoint any registered user could
// read, and it returned loadTemplatesFile() verbatim: each definition embeds
// docker.env with the real secret values an admin entered (stock templates
// ship STEAM_PASS, RCON_PASSWORD, SERVER_KEY), the installer script
// (docker.install.script), launch commands (docker.command /
// docker.adpanelStartup), host-facing volumes and port protocols. Every other
// template read/write route is admin-gated (GET/POST/PUT/DELETE
// /api/settings/templates, POST /api/templates/startup-command), so the fix
// keeps the full payload admin-only and hands non-admins a projection of
// exactly the fields the two non-admin consumers actually read:
// - public/js/dashboard.js renderTemplates(): t.id / t.name / t.description;
// getDefaultPortForTemplate(): defaultPort || default_port (||
// docker.ports[0] — a docker internal that deliberately does NOT cross
// the projection, the client falls back to its per-id defaults);
// resolveStartupCommandForSelection(): docker.image / docker.tag, and
// startupHidden (docker.command / adpanelStartup are withheld, so the
// client must yield the no-command state instead of guessing an override).
// - public/js/create-server-wizard.js renderTemplates(): t.id / t.name;
// getDefaultPortForTemplate(): defaultPort || default_port; plus the same
// startupHidden handling in its startup resolver and submit path.
// The response envelope stays `{ templates: [...] }`, so the clients need no
// changes.
//
// index.js boots servers on require, so the projection function is sliced out
// of the source and evaluated standalone (same technique as
// template-store-install-review.test.js), and the route wiring itself is
// pinned by source inspection (same technique as
// destructive-route-guards.test.js).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const INDEX_JS = path.join(__dirname, "..", "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
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 extractRoute(source, routeMarker, nextRouteMarker) {
const start = source.indexOf(routeMarker);
assert.ok(start >= 0, `route marker not found: ${routeMarker}`);
const end = source.indexOf(nextRouteMarker, start);
assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`);
return source.slice(start, end);
}
const sanitizeTemplateForList = new Function(
`${sliceFunction(indexSource, "function sanitizeTemplateForList")}\nreturn sanitizeTemplateForList;`
)();
// A template carrying every secret-bearing field the listing used to leak.
const SECRET_ENV = {
EULA: "TRUE",
STEAM_PASS: "steam-password-s3cret",
RCON_PASSWORD: "rcon-password-s3cret",
SERVER_KEY: "server-key-s3cret",
};
const INSTALL_SCRIPT = "#!/bin/bash\ncurl -fsSL https://example.invalid/payload.sh | sh";
const LEAKY_TEMPLATE = {
id: "leak-fixture",
name: "Leak Fixture",
description: "proves the non-admin projection drops secret-bearing fields",
defaultPort: 27015,
templateImage: "https://example.invalid/card.png",
documentation: "https://example.invalid/docs",
requirements: { memoryMb: 1024 },
docker: {
image: "ghcr.io/example/game:latest",
tag: "latest",
ports: [27015],
portProtocols: { "27015": ["tcp", "udp"] },
volumes: ["/var/run/docker.sock:/var/run/docker.sock"],
workdir: "/data",
env: SECRET_ENV,
command: "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui",
adpanelStartup: "echo owned > /mnt/server/.pwned-by-listing-leak",
startupDisplay: "java -jar /data/server.jar",
install: {
image: "ghcr.io/pterodactyl/installers:debian",
script: INSTALL_SCRIPT,
env: { INSTALLER_TOKEN: "installer-token-s3cret" },
},
restart: "on-failure",
readonlyRootfs: false,
runAsRoot: true,
console: "interactive",
javaVersion: "21",
},
};
// Every key the projection is allowed to emit, at any depth.
const ALLOWED_KEYS = new Set([
"id", "name", "description", "templateImage", "defaultPort", "default_port",
"docker", "image", "tag", "startupHidden",
]);
// The secret-bearing / docker-internal keys that must never survive.
const FORBIDDEN_KEYS = [
"env", "install", "command", "adpanelStartup", "adpanel_startup",
"startupDisplay", "startup_display", "pterodactylStartup",
"imageDefaultStartup", "volumes", "portProtocols", "ports", "workdir",
"restart", "console", "javaVersion", "readonlyRootfs", "runAsRoot",
"documentation", "requirements", "start",
];
// Secret VALUES that must never survive, verbatim.
const FORBIDDEN_VALUES = [
SECRET_ENV.STEAM_PASS,
SECRET_ENV.RCON_PASSWORD,
SECRET_ENV.SERVER_KEY,
"INSTALLER_TOKEN",
"installer-token-s3cret",
"payload.sh",
"pwned-by-listing-leak",
"docker.sock",
"/mnt/server",
"-Xmx{RAM_MB}M",
"ghcr.io/pterodactyl/installers",
"on-failure",
"/data",
];
function collectKeys(value, into) {
if (!value || typeof value !== "object") return into;
for (const key of Object.keys(value)) {
into.add(key);
collectKeys(value[key], into);
}
return into;
}
test("non-admin projection drops every secret-bearing template field", () => {
const projected = sanitizeTemplateForList(LEAKY_TEMPLATE);
assert.ok(projected && typeof projected === "object");
// Key level: nothing outside the allowlist survives, at any depth.
const keys = collectKeys(projected, new Set());
for (const key of keys) {
assert.ok(ALLOWED_KEYS.has(key), `forbidden key "${key}" survived the projection`);
}
// Belt and braces: the explicit forbidden list is checked by name too, so a
// future editor who widens ALLOWED_KEYS has to confront this list.
for (const key of FORBIDDEN_KEYS) {
assert.ok(!keys.has(key), `forbidden key "${key}" survived the projection`);
}
// Value level: no secret value from docker.env / install.script / volumes /
// command / adpanelStartup appears anywhere in the serialized projection.
const serialized = JSON.stringify(projected);
for (const secret of FORBIDDEN_VALUES) {
assert.ok(!serialized.includes(secret), `secret value ${JSON.stringify(secret)} survived the projection`);
}
// The env object shape itself is gone, not just its values.
assert.strictEqual(projected.docker.env, undefined);
assert.strictEqual(projected.docker.install, undefined);
assert.strictEqual(projected.docker.command, undefined);
assert.strictEqual(projected.docker.volumes, undefined);
assert.strictEqual(projected.docker.portProtocols, undefined);
});
test("projection keeps exactly the fields the two consumers read", () => {
const projected = sanitizeTemplateForList(LEAKY_TEMPLATE);
// dashboard.js reads id/name/description + docker.image/tag;
// both consumers read defaultPort/default_port for the port prefill;
// templateImage is the card artwork; startupHidden marks the withheld
// launch command (see the startupHidden test below). Nothing else is
// emitted.
assert.deepStrictEqual(projected, {
id: "leak-fixture",
name: "Leak Fixture",
description: "proves the non-admin projection drops secret-bearing fields",
templateImage: "https://example.invalid/card.png",
defaultPort: 27015,
docker: { image: "ghcr.io/example/game:latest", tag: "latest" },
startupHidden: true,
});
// Optional fields are omitted (not coerced to undefined) when absent, so
// the payload stays minimal for hand-rolled legacy templates. startupHidden
// is the one uniform marker: it is always present on projections.
const minimal = sanitizeTemplateForList({ id: "m", name: "M", description: "D" });
assert.deepStrictEqual(Object.keys(minimal).sort(), ["description", "id", "name", "startupHidden"]);
// Degenerate inputs pass through rather than throwing: the listing route
// maps over whatever loadTemplatesFile() returns.
assert.strictEqual(sanitizeTemplateForList(null), null);
assert.strictEqual(sanitizeTemplateForList(undefined), undefined);
assert.strictEqual(sanitizeTemplateForList("legacy-string"), "legacy-string");
});
test("projection marks the launch command as hidden so clients never submit a guessed override", () => {
// docker.command / adpanelStartup are withheld from non-admins, but the
// create modals' startup resolvers fall back to a per-id GUESS when the
// fields are merely absent — and that guess is submitted as payload.command,
// which the create endpoint applies OVER the template's own command. The
// startupHidden marker tells them the command was hidden (not missing), so
// they must yield the no-command state and omit the override entirely.
assert.strictEqual(sanitizeTemplateForList(LEAKY_TEMPLATE).startupHidden, true);
assert.strictEqual(sanitizeTemplateForList({ id: "m", name: "M", description: "D" }).startupHidden, true);
// Passthrough degenerate inputs carry no marker (they never reach the
// create modals as template objects).
assert.strictEqual(sanitizeTemplateForList(null), null);
});
test("clients honor startupHidden in their startup resolution and submit paths", () => {
const wizardSource = fs.readFileSync(path.join(__dirname, "..", "public", "js", "create-server-wizard.js"), "utf8");
// The create UI — and with it buildDefaultStartupCommandForTemplate /
// resolveStartupCommandForSelection — lives in create-server-wizard.js;
// dashboard.js carries no startup resolution at all, so the contract runs
// against the wizard only. The negative pin keeps a parallel guesser from
// reappearing in dashboard.js outside this contract.
assert.doesNotMatch(
fs.readFileSync(path.join(__dirname, "..", "public", "js", "dashboard.js"), "utf8"),
/buildDefaultStartupCommandForTemplate/,
"dashboard.js must not grow a parallel startup-command guesser outside the startupHidden contract"
);
for (const [label, source] of [["create-server-wizard.js", wizardSource]]) {
// Resolution: the hidden branch must exist and must never fabricate a
// command for a hidden template (the per-id guess builder bails out).
assert.ok(
/if \(template\.startupHidden\) return '';/m.test(source),
`${label}: buildDefaultStartupCommandForTemplate must not guess a command for a hidden template`
);
assert.ok(
source.includes("if (template.startupHidden) {"),
`${label}: resolveStartupCommandForSelection must handle the startupHidden state`
);
assert.ok(
source.includes("selectedStartupCommandMode = 'template-managed';"),
`${label}: the hidden state must resolve to the template-managed (no-command) mode`
);
// Submit: the managed mode must be excluded from the payload override,
// exactly like the pre-existing adpanel-startup / image-default modes.
assert.ok(
source.includes("selectedStartupCommandMode !== 'template-managed'"),
`${label}: the submit path must not send a command override for the template-managed mode`
);
// ...and every payload.command assignment must source the user-edited
// startup field — never a fabricated per-id guess.
const assignments = source.match(/payload\.command = [^\n]+/g) || [];
assert.ok(assignments.length >= 1, `${label}: a deliberate user override must still be submittable`);
for (const line of assignments) {
assert.ok(
/^payload\.command = (selectedStartupCommand|cmd);$/.test(line.trim()),
`${label}: payload.command may only be assigned from the user-edited startup field, never fabricated: ${line}`
);
}
}
});
test("projection never mutates or aliases the cached template object", () => {
// loadTemplatesFile() returns a shared 30s cache; the projection must build
// fresh objects so an admin response can never be tainted and the cache is
// never mutated through the projected copy.
const snapshot = JSON.stringify(LEAKY_TEMPLATE);
const projected = sanitizeTemplateForList(LEAKY_TEMPLATE);
assert.notStrictEqual(projected, LEAKY_TEMPLATE);
assert.notStrictEqual(projected.docker, LEAKY_TEMPLATE.docker);
projected.docker.image = "mutated";
projected.name = "mutated";
assert.strictEqual(JSON.stringify(LEAKY_TEMPLATE), snapshot);
});
test("route wiring: admins get the full file, non-admins only the projection", () => {
const route = extractRoute(
indexSource,
'app.get("/api/templates"',
'app.post("/api/templates/startup-command"'
);
// Auth gate unchanged: 401 before any data leaves.
assert.match(
route,
/if \(!\(await isAuthenticated\(req\)\)\) return res\.status\(401\)\.json\(\{ error: "not authenticated" \}\);/,
"route must keep the isAuthenticated gate"
);
// Admin branch returns the full, unchanged loadTemplatesFile() payload.
assert.match(
route,
/if \(await isAdmin\(req\)\) return res\.json\(\{ templates: loadTemplatesFile\(\) \}\);/,
"admins must still receive the full loadTemplatesFile() definitions"
);
// Non-admin branch maps every template through the sanitizer; the raw file
// is never returned on that path.
assert.match(
route,
/return res\.json\(\{ templates: \(loadTemplatesFile\(\) \|\| \[\]\)\.map\(sanitizeTemplateForList\) \}\);/,
"non-admins must receive the sanitized projection"
);
const rawReturns = route.match(/res\.json\(\{ templates: loadTemplatesFile\(\) \}\)/g) || [];
assert.strictEqual(
rawReturns.length,
1,
"exactly one raw loadTemplatesFile() response may exist, and it must be the admin-gated branch"
);
assert.match(
route,
/if \(await isAdmin\(req\)\) return res\.json\(\{ templates: loadTemplatesFile\(\) \}\);/,
"the raw response must sit behind the isAdmin gate"
);
// The sanitizer is a single shared definition and the envelope shape is
// identical on both branches.
assert.strictEqual(
(indexSource.match(/function sanitizeTemplateForList\(/g) || []).length,
1,
"sanitizeTemplateForList must be defined exactly once"
);
assert.strictEqual(
(route.match(/res\.json\(\{ templates:/g) || []).length,
2,
"both branches must keep the { templates: [...] } envelope"
);
});