Files
Kelx/utils/server-asset-apply.test.js
2026-11-30 16:32:37 +00:00

286 lines
11 KiB
JavaScript

"use strict";
// Regression tests for the dead "forward to node" apply path (remote store
// installs with REMOTE_APPLY_PROXY_DOWNLOAD=0).
//
// The daemon dispatches /v1/servers/<name>/apply-version BEFORE bearer-token
// auth and unconditionally requires the signed panel envelope; the forward
// used to send Bearer headers only, so every remote store install failed
// closed with 403 missing-signature and surfaced as a misleading 502
// node-auth-failed. The forward now signs the envelope (per-node derived
// secret first, fleet master second, one nonce-less legacy rung), binds the
// body's providerId/versionId into the signature, prunes+re-signs for
// daemons that predate those body fields, and answers admin-signing-
// not-configured instead of relaying an unsigned request that can only fail.
const test = require("node:test");
const assert = require("node:assert");
const crypto = require("crypto");
const { applyRemoteAssetToServer } = require("./server-asset-apply");
const { unknownJsonFieldFromNodeResponse } = require("./daemon-protocol");
const DERIVED_SECRET = "ab".repeat(32); // derived-secret-shaped (64 hex chars)
const MASTER_SECRET = "fleet-master-secret";
const NODE = {
id: "node-1",
uuid: "node-uuid-1",
address: "203.0.113.10",
api_port: 8080,
ssl_enabled: false,
};
const ENTRY = { name: "Test Server", bot: "test-server", nodeId: "node-1" };
const JAR_URL = "https://example.com/server.jar";
function hmacHex(secret, base) {
return crypto.createHmac("sha256", secret).update(base).digest("hex");
}
function makeDeps(overrides = {}) {
const calls = [];
const deps = {
findServer: async () => ENTRY,
isRemoteEntry: () => true,
findNodeByIdOrName: async () => NODE,
buildNodeBaseUrl: () => "http://203.0.113.10:8080",
nodeUnderCloudflare: () => false,
nodeAuthHeadersFor: () => ({
"Content-Type": "application/json",
Authorization: "Bearer node-token",
}),
nodeAdminSigningSecrets: () => [DERIVED_SECRET],
httpRequestJson: async (url, method, headers, body) => {
calls.push({ url, method, headers, body });
return { status: 200, json: { ok: true } };
},
assertSafeRemoteUrl: async (u) => new URL(u),
remoteApplyProxyDownload: false,
remoteApplyMaxBytes: 1024 * 1024 * 1024,
remoteApplyTimeoutMs: 300000,
remoteFetchMaxRedirects: 4,
...overrides,
};
return { deps, calls };
}
const BASE_PARAMS = {
serverName: "test-server",
entry: ENTRY,
url: JAR_URL,
destPath: "server.jar",
};
// Rebuilds the daemon-side base for a captured call and verifies the
// signature — the composition is written out here independently of
// utils/node-hmac.js so a drift on either side fails this test.
function verifySignature(call, secret, { providerId = "", versionId = "", legacy = false } = {}) {
const ts = call.headers["x-panel-ts"];
const nonce = call.headers["x-panel-nonce"] || "";
const base = `test-server|${providerId}|${versionId}|${JAR_URL}|${ts}${nonce ? `|${nonce}` : ""}`;
assert.strictEqual(call.headers["x-panel-sign"], hmacHex(secret, base));
if (legacy) {
assert.strictEqual(nonce, "", "legacy attempt must not carry a nonce");
} else {
assert.match(nonce, /^[0-9a-f]{32}$/);
}
return true;
}
test("forward signs the envelope and binds the body's provider/version", async () => {
const { deps, calls } = makeDeps();
const result = await applyRemoteAssetToServer(deps, {
...BASE_PARAMS,
providerId: "papermc",
versionId: "1.21.4",
});
assert.strictEqual(result.ok, true);
assert.strictEqual(result.msg, "forwarded-to-node");
assert.strictEqual(calls.length, 1);
const call = calls[0];
assert.strictEqual(call.url, "http://203.0.113.10:8080/v1/servers/test-server/apply-version");
assert.strictEqual(call.method, "POST");
assert.deepStrictEqual(call.body, {
url: JAR_URL,
nodeId: "node-1",
destPath: "server.jar",
providerId: "papermc",
versionId: "1.21.4",
});
// Bearer auth stays (the fs endpoints still want it) and the envelope rides
// on top.
assert.strictEqual(call.headers.Authorization, "Bearer node-token");
assert.strictEqual(verifySignature(call, DERIVED_SECRET, { providerId: "papermc", versionId: "1.21.4" }), true);
});
test("forward without provider/version omits the fields and signs empty bindings", async () => {
const { deps, calls } = makeDeps();
const result = await applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
assert.strictEqual(result.ok, true);
assert.strictEqual(calls.length, 1);
assert.ok(!("providerId" in calls[0].body));
assert.ok(!("versionId" in calls[0].body));
assert.strictEqual(verifySignature(calls[0], DERIVED_SECRET), true);
});
test("bad-signature rejection escalates to the fleet master secret", async () => {
const { deps, calls } = makeDeps({
nodeAdminSigningSecrets: () => [DERIVED_SECRET, MASTER_SECRET],
httpRequestJson: async (url, method, headers, body) => {
const n = calls.push({ url, method, headers, body });
// Rung 1 (derived secret) rejected; rung 2 (master) accepted.
return n === 1
? { status: 403, json: { ok: false, error: "bad-signature" } }
: { status: 200, json: { ok: true } };
},
});
const result = await applyRemoteAssetToServer(deps, {
...BASE_PARAMS,
providerId: "papermc",
versionId: "1.21.4",
});
assert.strictEqual(result.ok, true);
assert.strictEqual(calls.length, 2);
assert.strictEqual(verifySignature(calls[0], DERIVED_SECRET, { providerId: "papermc", versionId: "1.21.4" }), true);
assert.strictEqual(verifySignature(calls[1], MASTER_SECRET, { providerId: "papermc", versionId: "1.21.4" }), true);
});
test("all bad-signature rejections fall through to the nonce-less legacy rung", async () => {
const { deps, calls } = makeDeps({
nodeAdminSigningSecrets: () => [DERIVED_SECRET, MASTER_SECRET],
httpRequestJson: async (url, method, headers, body) => {
const n = calls.push({ url, method, headers, body });
return n < 3
? { status: 403, json: { ok: false, error: "bad-signature" } }
: { status: 200, json: { ok: true } };
},
});
const result = await applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
// Ladder: derived+nonce, master+nonce, then the legacy nonce-less attempt
// with the first secret.
assert.strictEqual(result.ok, true);
assert.strictEqual(calls.length, 3);
assert.strictEqual(verifySignature(calls[0], DERIVED_SECRET), true);
assert.strictEqual(verifySignature(calls[1], MASTER_SECRET), true);
assert.strictEqual(verifySignature(calls[2], DERIVED_SECRET, { legacy: true }), true);
});
test("non-bad-signature rejections stop the ladder and keep the node-auth mapping", async () => {
const { deps, calls } = makeDeps({
httpRequestJson: async (url, method, headers, body) => {
calls.push({ url, method, headers, body });
return { status: 401, json: { ok: false, error: "expired" } };
},
});
const result = await applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
// Clock skew ("expired") cannot be fixed by re-signing: exactly one
// attempt, and the daemon's own reason surfaces in the detail.
assert.strictEqual(calls.length, 1);
assert.strictEqual(result.ok, false);
assert.strictEqual(result.statusCode, 502);
assert.strictEqual(result.error, "node-auth-failed");
assert.match(result.detail, /\bexpired\b/);
});
test("nodeId mismatch (unauthorized) stops the ladder and reports the reason", async () => {
const { deps, calls } = makeDeps({
httpRequestJson: async (url, method, headers, body) => {
calls.push({ url, method, headers, body });
return { status: 401, json: { ok: false, error: "unauthorized" } };
},
});
const result = await applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
assert.strictEqual(calls.length, 1);
assert.strictEqual(result.error, "node-auth-failed");
assert.match(result.detail, /\bunauthorized\b/);
});
test("missing signing configuration fails closed panel-side without sending", async () => {
const { deps, calls } = makeDeps({ nodeAdminSigningSecrets: () => [] });
const result = await applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
assert.strictEqual(calls.length, 0, "an unsigned forward can never succeed — it must not be sent");
assert.strictEqual(result.ok, false);
assert.strictEqual(result.statusCode, 500);
assert.strictEqual(result.error, "admin-signing-not-configured");
});
test("unknown-field rejection prunes provider/version and re-signs the empty bindings", async () => {
const { deps, calls } = makeDeps({
httpRequestJson: async (url, method, headers, body) => {
calls.push({ url, method, headers, body });
return calls.length === 1
? { status: 400, json: { ok: false, error: "bad-json", detail: 'json: unknown field "providerId"' } }
: { status: 200, json: { ok: true } };
},
});
const result = await applyRemoteAssetToServer(deps, {
...BASE_PARAMS,
providerId: "papermc",
versionId: "1.21.4",
});
assert.strictEqual(result.ok, true);
assert.strictEqual(calls.length, 2);
// Retry body is pruned back to the legacy shape...
assert.deepStrictEqual(calls[1].body, { url: JAR_URL, nodeId: "node-1", destPath: "server.jar" });
// ...and signed over the empty provider/version bindings such a daemon
// itself binds for the absent fields.
assert.strictEqual(verifySignature(calls[1], DERIVED_SECRET), true);
});
test("disk-limit 507 mapping is preserved through the signed forward", async () => {
const { deps, calls } = makeDeps({
httpRequestJson: async (url, method, headers, body) => {
calls.push({ url, method, headers, body });
return { status: 507, json: { ok: false, error: "disk_limit_exceeded", used: 99, limit: 100 } };
},
});
const result = await applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
assert.strictEqual(calls.length, 1);
assert.strictEqual(result.ok, false);
assert.strictEqual(result.statusCode, 507);
assert.strictEqual(result.error, "disk_limit_exceeded");
});
test("proxy-download mode still bypasses the forward entirely", async () => {
const { deps, calls } = makeDeps({
remoteApplyProxyDownload: true,
resolveRemoteFsContext: async () => ({ remote: false, node: null }),
});
const result = await applyRemoteAssetToServer(deps, { ...BASE_PARAMS });
assert.strictEqual(calls.length, 0);
assert.strictEqual(result.ok, false);
assert.strictEqual(result.statusCode, 404);
assert.strictEqual(result.error, "server-not-on-node");
});
test("unknownJsonFieldFromNodeResponse matches only the daemon's decode-error shape", () => {
assert.strictEqual(unknownJsonFieldFromNodeResponse(null), "");
assert.strictEqual(unknownJsonFieldFromNodeResponse({ status: 403, json: { error: "bad-signature" } }), "");
assert.strictEqual(
unknownJsonFieldFromNodeResponse({ status: 400, json: { error: "bad-json", detail: 'json: unknown field "providerId"' } }),
"providerId"
);
assert.strictEqual(
unknownJsonFieldFromNodeResponse({ status: 400, json: { error: "bad-json", detail: 'json: unknown field "versionId"' } }),
"versionId"
);
});