Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+541
View File
@@ -0,0 +1,541 @@
"use strict";
// Tests for environment payload sanitization in utils/server-template-payload.js,
// remediation of the audit finding "Env sanitization enforces almost no
// invariants". Run: npm test (node --test utils/*.test.js)
//
// Env payloads originate from untrusted template JSON and end up in container
// process environments through two sinks: the Docker Engine API "KEY=VALUE"
// Env list and `docker run -e KEY=VALUE` argv. Both split on the first "=",
// so the suites prove:
// 1. The sanitized key IS the env name the container sees: keys containing
// "=" (and whitespace / control characters / NUL that break KEY=VALUE,
// argv or env-file framing the same way) are dropped, so no key can be
// silently renamed past a key-based check downstream.
// 2. Keys are restricted to [A-Za-z0-9_][A-Za-z0-9_.-]* — the same charset
// the node's {{KEY}} startup-template tokenizer accepts, so every
// surviving key stays referenceable (non-identifier keys like "my-key"
// keep working via the node's quoted-splice path).
// 3. Prototype-pollution keys stay blocked and values are opaque bounded
// strings (NUL stripped, size caps, entry cap).
// 4. The invariants hold through every public entry point that accepts env
// (docker.env and docker.install.env).
const test = require("node:test");
const assert = require("node:assert");
const {
sanitizeEnvPayload,
validateTemplateEnvPayload,
sanitizeDockerTemplatePayload,
sanitizeDockerInstallPayload,
sanitizeVolumeSpec,
sanitizeTemplateVolumeList,
validateTemplateVolumeListPayload,
} = require("./server-template-payload");
test("sanitizeEnvPayload keeps well-formed keys and stringifies values", () => {
const out = sanitizeEnvPayload({
FOO: "bar",
A_1: 42,
FLAG: true,
EMPTY: null,
"my-key": "v",
"dot.ted": "v",
});
assert.deepStrictEqual(out, {
FOO: "bar",
A_1: "42",
FLAG: "true",
EMPTY: "",
"my-key": "v",
"dot.ted": "v",
});
});
test("sanitizeEnvPayload drops keys containing '=' (Engine/CLI split smuggling)", () => {
// If such a key survived, docker would split "PATH=/evil=x" into the env
// name "PATH" — a variable the template never declared — and any future
// key-based denylist could be bypassed the same way.
const out = sanitizeEnvPayload({
"PATH=/evil": "smuggled",
"LD_PRELOAD=/lib/x": "smuggled",
"GOOD=NAME": "also smuggled",
GOOD: "kept",
});
assert.deepStrictEqual(out, { GOOD: "kept" });
});
test("sanitizeEnvPayload drops whitespace, newline and control-character keys", () => {
const out = sanitizeEnvPayload({
"BAD KEY": "x",
"BAD\tKEY": "x",
"BAD\nKEY": "x",
"BAD\rKEY": "x",
"BAD\x00KEY": "x",
"BAD\x01KEY": "x",
" GOOD ": "trimmed and kept",
});
assert.deepStrictEqual(out, { GOOD: "trimmed and kept" });
});
test("sanitizeEnvPayload rejects flag-like and dot/underscore-only leading keys", () => {
const out = sanitizeEnvPayload({
"-FOO": "x",
"--rm": "x",
".FOO": "x",
FOO_: "kept",
});
assert.deepStrictEqual(out, { FOO_: "kept" });
});
test("sanitizeEnvPayload blocks prototype-pollution keys, including padded variants", () => {
const out = sanitizeEnvPayload({
__proto__: "{}",
constructor: "x",
prototype: "x",
" __proto__ ": "padded",
KEEP: "1",
});
assert.deepStrictEqual(out, { KEEP: "1" });
});
test("sanitizeEnvPayload strips NUL from values but keeps newlines (PEM/JSON blobs)", () => {
const out = sanitizeEnvPayload({
PEM: "line1\nline2\n\x00",
JSONBlob: '{"a":1}',
});
assert.deepStrictEqual(out, {
PEM: "line1\nline2\n",
JSONBlob: '{"a":1}',
});
});
test("sanitizeEnvPayload enforces key/value size caps", () => {
const longKey = "K".repeat(128);
const tooLongKey = "K".repeat(129);
const out = sanitizeEnvPayload({
[longKey]: "kept",
[tooLongKey]: "key too long",
BIG_OK: "v".repeat(32768),
BIG_BAD: "v".repeat(32769),
GOOD: "1",
});
assert.deepStrictEqual(out, {
[longKey]: "kept",
BIG_OK: "v".repeat(32768),
GOOD: "1",
});
});
test("sanitizeEnvPayload entry cap keeps insertion order", () => {
const env = {};
for (let i = 0; i < 130; i++) env[`K${String(i).padStart(3, "0")}`] = "v";
const out = sanitizeEnvPayload(env);
assert.strictEqual(Object.keys(out).length, 128);
assert.strictEqual(Object.keys(out)[0], "K000");
assert.strictEqual(Object.keys(out)[127], "K127");
assert.ok(!("K128" in out));
});
test("sanitizeEnvPayload rejects non-object input and empty results", () => {
for (const input of [null, undefined, 42, "x", [], { }]) {
assert.strictEqual(sanitizeEnvPayload(input), null, String(input));
}
});
// --- Fail-closed ingestion boundary (audit finding: invalid/oversized env
// entries were silently dropped with 200 OK, so the admin's "Template
// created!" stored a template whose servers ran without the env they
// reviewed — inconsistent with the same endpoint's fail-closed volume
// boundary). validateTemplateEnvPayload must accept exactly what
// sanitizeEnvPayload accepts (mirroring its output) and REJECT everything it
// would drop, naming the entry.
test("validateTemplateEnvPayload mirrors sanitizeEnvPayload for accepted input", () => {
const inputs = [
{ FOO: "bar", A_1: 42, FLAG: true, EMPTY: null, "my-key": "v", "dot.ted": "v" },
{ " PAD ": "trimmed key", PEM: "line1\nline2\n\x00" },
{ GOOD: "1" },
{},
];
for (const input of inputs) {
const result = validateTemplateEnvPayload(input);
assert.strictEqual(result.error, undefined, JSON.stringify(input));
// `|| {}` is how constructTemplateDefinition consumed the sanitizer, so
// that — not the raw null for empty objects — is the mirror target.
assert.deepStrictEqual(result.env, sanitizeEnvPayload(input) || {}, JSON.stringify(input));
}
});
test("validateTemplateEnvPayload treats missing and null env as no variables", () => {
assert.deepStrictEqual(validateTemplateEnvPayload(undefined), { env: {} });
assert.deepStrictEqual(validateTemplateEnvPayload(null), { env: {} });
});
test("validateTemplateEnvPayload fails closed on keys sanitizeEnvPayload drops", () => {
const cases = [
[{ "MY VAR": "x" }, /invalid env key "MY VAR"/],
[{ "PATH=/evil": "smuggled" }, /invalid env key/],
[{ "-FOO": "x" }, /invalid env key/],
[{ ".FOO": "x" }, /invalid env key/],
[{ "BAD\tKEY": "x" }, /invalid env key/],
[{ "BAD\nKEY": "x" }, /invalid env key/],
[{ ["K".repeat(129)]: "x" }, /invalid env key/],
// Prototype-pollution keys survive JSON.parse as own properties; the
// boundary must reject, never re-assign them.
[JSON.parse('{"__proto__":"{}"}'), /invalid env key/],
[JSON.parse('{"constructor":"x"}'), /invalid env key/],
[JSON.parse('{"prototype":"x"}'), /invalid env key/],
];
for (const [input, expected] of cases) {
const result = validateTemplateEnvPayload(input);
assert.match(result.error, expected, JSON.stringify(Object.keys(input)));
assert.strictEqual(result.env, undefined, JSON.stringify(Object.keys(input)));
}
});
test("validateTemplateEnvPayload fails closed on empty, oversized and object values", () => {
const emptyKey = validateTemplateEnvPayload({ "": "x" });
assert.match(emptyKey.error, /empty key/);
const paddedKey = validateTemplateEnvPayload({ " ": "x" });
assert.match(paddedKey.error, /empty key/);
const objectValue = validateTemplateEnvPayload({ FOO: { nested: true } });
assert.match(objectValue.error, /invalid env value for "FOO"/);
const arrayValue = validateTemplateEnvPayload({ FOO: ["a"] });
assert.match(arrayValue.error, /invalid env value for "FOO"/);
// null/undefined values stay legal (they sanitize to "").
assert.strictEqual(validateTemplateEnvPayload({ FOO: null }).error, undefined);
const longValue = validateTemplateEnvPayload({ BIG: "v".repeat(32769) });
assert.match(longValue.error, /env value for "BIG" is too long/);
// 32768 exactly stays under the cap (same boundary as the sanitizer).
assert.strictEqual(validateTemplateEnvPayload({ BIG: "v".repeat(32768) }).error, undefined);
});
test("validateTemplateEnvPayload rejects the entry cap and malformed shapes", () => {
const env = {};
for (let i = 0; i < 129; i++) env[`K${String(i).padStart(3, "0")}`] = "v";
assert.match(validateTemplateEnvPayload(env).error, /too many env entries \(max 128\)/);
// 128 exactly is accepted.
const maxEnv = {};
for (let i = 0; i < 128; i++) maxEnv[`K${String(i).padStart(3, "0")}`] = "v";
assert.strictEqual(validateTemplateEnvPayload(maxEnv).error, undefined);
for (const input of ["FOO=bar", 42, []]) {
const result = validateTemplateEnvPayload(input);
assert.match(result.error, /invalid env — expected an object/, String(input));
}
});
test("sanitizeDockerTemplatePayload applies the same invariants to docker.env", () => {
const payload = sanitizeDockerTemplatePayload({
image: "ghcr.io/example/game:latest",
env: {
SERVER_PORT: "27015",
"PATH=/evil": "smuggled",
"SP ACE": "x",
__proto__: "{}",
},
});
assert.deepStrictEqual(payload.env, { SERVER_PORT: "27015" });
});
test("sanitizeDockerTemplatePayload applies the same invariants to install.env", () => {
const payload = sanitizeDockerTemplatePayload({
image: "ghcr.io/example/game:latest",
install: {
script: "#!/bin/sh\necho hi",
env: {
GOOD: "1",
"A=B": "2",
"C D": "3",
},
},
});
assert.deepStrictEqual(payload.install.env, { GOOD: "1" });
});
test("sanitizeDockerInstallPayload applies the invariants standalone", () => {
const payload = sanitizeDockerInstallPayload({
script: "echo hi",
env: { OK: "1", "EVIL=KEY": "2", "\u0000NUL": "3" },
});
assert.deepStrictEqual(payload.env, { OK: "1" });
});
test("non-identifier keys stay supported (node's quoted-splice startup path)", () => {
// The node agent's startup renderer documents: "non-identifier keys
// (e.g. 'my-key') ... are spliced as a fully quoted single word". The
// charset here must keep accepting them.
const out = sanitizeEnvPayload({ "my-key": "a b; c" });
assert.deepStrictEqual(out, { "my-key": "a b; c" });
});
// --- Volumes (audit finding: "Volumes pass the create/update boundary with
// trim-only validation; host-path abuse is blocked only downstream in the
// agent"). The suites below prove the panel now rejects/normalizes hostile
// mount specs at the ingestion boundary instead of relying on the node
// agent's resolveStructuredBinds allowlist as the single defense layer.
test("sanitizeVolumeSpec keeps server-directory placeholder mounts", () => {
const kept = [
"{BOT_DIR}:/data",
"{BOT_DIR}:/data:ro",
"{BOT_DIR}/worlds:/data/worlds",
"{SERVER_DIR}/saves:/home/container/.config:rw,z",
"{DATA_DIR}:/app",
" {BOT_DIR}:/data ",
];
for (const spec of kept) {
assert.strictEqual(sanitizeVolumeSpec(spec), spec.trim(), spec);
}
for (const blank of ["", " ", null, undefined]) {
assert.strictEqual(sanitizeVolumeSpec(blank), "", String(blank));
}
});
test("sanitizeVolumeSpec rejects host-filesystem references and unsupported volume sources", () => {
const dropped = [
"mcdata:/data",
"{UNKNOWN_DIR}:/data",
"/etc:/host-etc",
"/:/host-root",
"/var/run/docker.sock:/var/run/docker.sock",
"//etc:/x",
"\\etc\\passwd:/x",
"C:\\data:/x",
];
for (const spec of dropped) {
assert.strictEqual(sanitizeVolumeSpec(spec), "", spec);
}
});
test("sanitizeVolumeSpec rejects traversal, malformed and oversized specs", () => {
const dropped = [
"{BOT_DIR}/../..:/escape",
"{BOT_DIR}/..:/escape",
"{BOT_DIR}:/data/..",
"./data:/x",
"foo/./bar:/x",
"foo/../bar:/x",
"a:b:c:d",
"host",
"host:relative",
"host:/data:bad mode",
"host:/da\nta", // mid-spec newline: trim() cannot remove it, so it must fail validation
"host:/data\x00", // NUL is not whitespace — trim() keeps it, validation must drop it
"ho st:/data",
"host:/da ta",
"\x00host:/data",
"x".repeat(513) + ":/data",
];
for (const spec of dropped) {
assert.strictEqual(sanitizeVolumeSpec(spec), "", JSON.stringify(spec));
}
});
test("sanitizeTemplateVolumeList drops unusable entries and bounds the list", () => {
assert.deepStrictEqual(
sanitizeTemplateVolumeList(["{BOT_DIR}:/data", "/etc:/x", " ", "{BOT_DIR}/worlds:/data/worlds:ro"]),
["{BOT_DIR}:/data", "{BOT_DIR}/worlds:/data/worlds:ro"]
);
assert.deepStrictEqual(sanitizeTemplateVolumeList("not-a-list"), []);
assert.deepStrictEqual(sanitizeTemplateVolumeList(null), []);
const many = Array.from({ length: 40 }, (_, i) => `{BOT_DIR}:/data/${i}`);
assert.deepStrictEqual(sanitizeTemplateVolumeList(many).length, 32);
});
test("validateTemplateVolumeListPayload accepts legacy request shapes", () => {
assert.deepStrictEqual(
validateTemplateVolumeListPayload(["{BOT_DIR}:/data", " "]),
{ volumes: ["{BOT_DIR}:/data"] }
);
assert.deepStrictEqual(validateTemplateVolumeListPayload("{BOT_DIR}:/app"), { volumes: ["{BOT_DIR}:/app"] });
assert.deepStrictEqual(validateTemplateVolumeListPayload(undefined), { volumes: [] });
assert.deepStrictEqual(validateTemplateVolumeListPayload([]), { volumes: [] });
// An object shape is NOT a legacy-accepted list — it 400s now (see the
// non-array, non-string test below).
const maxList = Array.from({ length: 32 }, (_, i) => `{BOT_DIR}:/data/${i}`);
assert.deepStrictEqual(validateTemplateVolumeListPayload(maxList), { volumes: maxList });
});
test("validateTemplateVolumeListPayload fails closed on mounts the panel must not persist", () => {
const hostile = [
["mcdata:/data"],
["/etc:/host-etc"],
["/var/run/docker.sock:/var/run/docker.sock"],
["{BOT_DIR}:/data", "{BOT_DIR}/../..:/escape"], // one bad spec rejects the whole request
["named:relative"], // relative container path is not a mountable target
["\x00host:/data"],
["a:b:c:d"],
];
for (const volumes of hostile) {
const result = validateTemplateVolumeListPayload(volumes);
assert.ok(result.error, JSON.stringify(volumes));
assert.match(result.error, /invalid volume mount/);
assert.strictEqual(result.volumes, undefined, JSON.stringify(volumes));
}
// Single-string form is validated too, not just arrays.
assert.match(validateTemplateVolumeListPayload("/etc:/etc").error, /invalid volume mount/);
// Bounded request size: more than 32 mounts is rejected outright.
assert.match(
validateTemplateVolumeListPayload(Array.from({ length: 33 }, () => "v:/d")).error,
/too many volume mounts/
);
});
test("validateTemplateVolumeListPayload rejects equivalent mount destinations", () => {
const result = validateTemplateVolumeListPayload(["{BOT_DIR}/world:/data", "{BOT_DIR}/config:/game/../data/"]);
assert.deepStrictEqual(result, { error: 'duplicate volume mount destination "/data"' });
});
test("validateTemplateVolumeListPayload fails closed on non-array, non-string shapes", () => {
// Converter tools commonly emit mounts as an index-keyed object
// ({"0": "{BOT_DIR}:/data"}); answering "no mounts" for those would store a
// template whose servers start without the volumes the admin reviewed —
// the reviewed-then-dropped loss this boundary exists to prevent.
const rejected = [
[{ 0: "{BOT_DIR}:/data" }, /not an object/],
[{}, /not an object/],
[42, /not a number/],
[true, /not a boolean/],
];
for (const [volumes, expected] of rejected) {
const result = validateTemplateVolumeListPayload(volumes);
assert.ok(result.error, JSON.stringify(volumes));
assert.match(result.error, /expected an array of "host:container" mount strings/, JSON.stringify(volumes));
assert.match(result.error, expected, JSON.stringify(volumes));
assert.strictEqual(result.volumes, undefined, JSON.stringify(volumes));
}
// The documented "no mounts" contracts survive: a missing or null list and
// a blank-only string are valid no-mount requests.
assert.deepStrictEqual(validateTemplateVolumeListPayload(undefined), { volumes: [] });
assert.deepStrictEqual(validateTemplateVolumeListPayload(null), { volumes: [] });
assert.deepStrictEqual(validateTemplateVolumeListPayload(" "), { volumes: [] });
// Regression guard: a valid array still round-trips unchanged.
assert.deepStrictEqual(
validateTemplateVolumeListPayload(["{BOT_DIR}:/data", "{BOT_DIR}/worlds:/worlds:ro"]),
{ volumes: ["{BOT_DIR}:/data", "{BOT_DIR}/worlds:/worlds:ro"] }
);
});
test("sanitizeDockerTemplatePayload applies the hardened volume rules to stored templates", () => {
const payload = sanitizeDockerTemplatePayload({
image: "ghcr.io/example/game:latest",
volumes: ["{BOT_DIR}:/data", "/etc:/host-etc", "{BOT_DIR}/../..:/escape"],
});
assert.deepStrictEqual(payload.volumes, ["{BOT_DIR}:/data"]);
});
// --- Container-boundary script policy (audit finding: "the strict command
// validator is bypassed by design via two sibling fields") --------------------
// docker.command is validated as pure argv, but adpanelStartup and
// install.script are full shell scripts. Both now share one boundary policy in
// this module: scripts must not reference container-runtime sockets/CLIs,
// namespace tools or host namespaces. install.script is additionally strict
// about the runtime tools as whole words, because the installer image is
// attacker-chosen and networked — a runtime reference there can only be an
// escape attempt. The node agent mirrors both validators in main.go.
const {
validateADPanelStartupScriptInput,
validateTemplateInstallScriptInput,
} = require("./server-template-payload");
test("validateADPanelStartupScriptInput accepts ordinary managed startup shell", () => {
const accepted = [
'cd /home/container && node index.js --port ${SERVER_PORT}',
"./start.sh\n",
'java -Xms128M -jar server.jar nogui',
"",
null,
undefined,
];
for (const script of accepted) {
assert.strictEqual(validateADPanelStartupScriptInput(script), null, JSON.stringify(script));
}
});
test("validateADPanelStartupScriptInput rejects container-escape references", () => {
const rejected = [
"cat /var/run/docker.sock",
"ls /run/podman.sock",
"curl --unix-socket /var/run/containerd.sock http://x",
"docker run --privileged -v /:/host alpine",
"docker exec -it x sh",
"nsenter -t 1 -m -- /bin/sh",
"unshare -m",
"nerdctl run -v /:/host alpine",
"sleep 1 --pid=host",
"busybox sh -c 'cat /proc/1/root/etc/shadow'",
];
for (const script of rejected) {
assert.match(validateADPanelStartupScriptInput(script), /cannot reference/, JSON.stringify(script));
}
assert.match(validateADPanelStartupScriptInput("x".repeat(32769)), /too long/);
});
test("validateTemplateInstallScriptInput accepts ordinary install scripts", () => {
const accepted = [
"#!/bin/bash\napt-get update && apt-get install -y curl\n",
"curl -fsSL https://example.invalid/x.sh | sh",
"echo downloading server\ntar -xzf server.tar.gz -C /mnt/server",
"git clone https://github.com/example/game.git /mnt/server",
"java -jar setup.jar --install",
"",
" ",
];
for (const script of accepted) {
assert.strictEqual(validateTemplateInstallScriptInput(script), null, JSON.stringify(script));
}
});
test("validateTemplateInstallScriptInput rejects runtime references and escape flags", () => {
const rejected = [
"docker run --privileged -v /:/host alpine",
"docker pull ghcr.io/example/image",
"/usr/bin/docker compose up",
"podman run -v /:/host alpine",
"nerdctl info",
"ctr images pull x",
"nsenter -t 1 -m -- /bin/sh",
"unshare --mount --pid --fork",
"curl --unix-socket /var/run/docker.sock http://localhost/version",
"apt-get install docker.io",
"echo --network=host",
"mkdir -p /proc/1/root/escape",
];
for (const script of rejected) {
assert.match(validateTemplateInstallScriptInput(script), /Install scripts cannot reference/, JSON.stringify(script));
}
});
test("sanitizeDockerTemplatePayload drops install scripts and startup scripts the boundary refuses", () => {
const payload = sanitizeDockerTemplatePayload({
image: "img",
install: { script: "apt-get update\nnsenter -t 1 -m -- /bin/sh" },
adpanelStartup: "docker exec -it x sh",
});
assert.strictEqual(payload.install, undefined);
assert.strictEqual(payload.adpanelStartup, undefined);
const clean = sanitizeDockerTemplatePayload({
image: "img",
install: { script: "apt-get update && tar -xzf files.tar.gz" },
adpanelStartup: "cd /home/container && ./start.sh",
});
assert.strictEqual(clean.install.script, "apt-get update && tar -xzf files.tar.gz");
assert.strictEqual(clean.adpanelStartup, "cd /home/container && ./start.sh");
});
test("sanitizeDockerInstallPayload alone stays pure normalization (boundary owns rejection)", () => {
// The 400 at create/store-install reads the sanitized script and calls
// validateTemplateInstallScriptInput itself; the sanitizer must not swallow
// the script or the boundary could not tell "no script" from "dropped".
const payload = sanitizeDockerInstallPayload({ script: "docker run alpine" });
assert.strictEqual(payload.script, "docker run alpine");
});