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

533 lines
21 KiB
JavaScript

"use strict";
const crypto = require("crypto");
const fs = require("fs");
const fsp = require("fs/promises");
const httpMod = require("http");
const https = require("https");
const os = require("os");
const path = require("path");
const { Transform } = require("stream");
const { pipeline } = require("stream/promises");
const FormData = require("form-data");
const { getTechnicalServerName } = require("./server-name");
const nodeHmac = require("./node-hmac");
const { unknownJsonFieldFromNodeResponse } = require("./daemon-protocol");
const nodeSsrfGuard = require("./node-ssrf-guard");
// adpanel:relay-helper-consolidation — safeJoinUnix is the shared
// services/node-fs-relay.js implementation (panel style), re-bound below. The
// former local copy (NUL-strip, "Path traversal detected" wording, no
// control-char check) was strictly looser; this module's single caller
// swallows every throw into a fixed 400 "invalid-destPath", so the shared
// union's stricter rejections are wire-invisible here.
const { safeJoinUnix } = require("../services/node-fs-relay");
const { nodeTlsAgent } = require("../services/node-http");
// safeJoinUnix: shared services/node-fs-relay.js copy, re-bound above.
async function uploadFileToNode({
node,
uploadUrl,
headers,
filePath,
filename,
targetDir,
serverName,
}) {
const form = new FormData();
// adpanel:fs-scope - send the server scope so the node contains the upload
// inside this server's directory (symlink-safe). The server field MUST
// precede dir: the node validates dir against the server value parsed so
// far. Omitted when unknown (back-compat with old nodes).
if (typeof serverName === "string" && serverName) {
form.append("server", serverName);
}
form.append("dir", targetDir);
form.append("file", fs.createReadStream(filePath), { filename });
const requestHeaders = Object.assign({}, headers);
delete requestHeaders["Content-Type"];
Object.assign(requestHeaders, form.getHeaders());
const parsedUrl = new URL(uploadUrl);
const lib = uploadUrl.startsWith("https:") ? https : httpMod;
// adpanel:node-ssrf — this dial carries the node's bearer credential, so it
// gets the same posture as every other node dial primitive: pre-flight
// host classification plus connect-time re-validation of resolved IPs. The
// URL is node-derived, so the guard never fires for legitimate flows; it
// exists so a crafted store/apply target cannot turn the upload into an
// SSRF probe against internal addresses.
const guardError = nodeSsrfGuard.assertNodeUrlHostAllowed(uploadUrl);
if (guardError) throw guardError;
await new Promise((resolve, reject) => {
const req = lib.request({
method: "POST",
hostname: parsedUrl.hostname,
port: parsedUrl.port || (uploadUrl.startsWith("https:") ? 443 : 80),
path: parsedUrl.pathname + parsedUrl.search,
headers: requestHeaders,
timeout: 600_000,
agent: nodeTlsAgent(uploadUrl),
lookup: nodeSsrfGuard.guardedNodeLookup,
}, (res) => {
const chunks = [];
let total = 0;
res.on("data", (chunk) => {
if (total < 65_536) {
chunks.push(chunk);
total += chunk.length;
}
});
res.on("end", () => {
if (res.statusCode === 200) {
resolve();
return;
}
const body = Buffer.concat(chunks).toString().slice(0, 2000);
const error = new Error(`Node upload failed: ${res.statusCode} ${body}`);
error.nodeStatusCode = res.statusCode;
error.nodeBody = body;
reject(error);
});
// adpanel:upload-response-error — a mid-response IncomingMessage
// 'error'/'aborted' with no listener is an uncaught exception that
// crashes the worker (the crash class behind three historical worker
// restarts), and without a settle the awaiting apply would hang until
// the request timeout. Reject like the req error path; a settled
// Promise ignores later resolve/reject, so a late event after 'end' is
// a no-op.
res.on("error", reject);
res.on("aborted", () => reject(new Error("Node upload response aborted")));
});
req.on("error", reject);
req.on("timeout", () => {
req.destroy();
reject(new Error("Upload request timed out"));
});
form.pipe(req);
});
}
// The store apply is gated by store_access — a browse-and-install permission,
// not a general file-write grant (every sibling write path additionally
// demands files_upload/files_create). The store's own callers only ever target
// the version core (server.jar) or a Modrinth plugin/mod build one level under
// plugins/ or mods/, so destPath is pinned to exactly that surface: a
// store-only role keeps every store flow but can no longer drop an arbitrary
// file — e.g. the bot's own entry script — anywhere under the server root,
// with content fetched from any URL. Traversal stays refused: the substring
// checks reject "..", "\" and NUL before the shape match, so encoded or
// Windows-style variants fail closed.
const STORE_APPLY_DEST_EXTENSIONS = new Set([".jar", ".litemod", ".zip"]);
function validateStoreApplyDestPath(rawDestPath) {
let destRel = String(rawDestPath ?? "").trim();
if (!destRel) return { ok: true, destPath: "server.jar" };
destRel = destRel.replace(/^\/+/, "");
if (destRel.includes("..") || destRel.includes("\\") || destRel.includes("\0")) {
return { ok: false, error: "invalid-destPath" };
}
if (destRel === "server.jar") return { ok: true, destPath: destRel };
const match = destRel.match(/^(plugins|mods)\/([^/]+)$/);
if (!match) return { ok: false, error: "invalid-destPath" };
const ext = path.posix.extname(match[2]).toLowerCase();
if (!ext || !STORE_APPLY_DEST_EXTENSIONS.has(ext)) {
return { ok: false, error: "invalid-destPath" };
}
return { ok: true, destPath: destRel };
}
// Proxy-download mode streams a tenant-supplied URL onto the panel before it
// is relayed to the node. The download itself no longer costs heap (it is
// piped straight into the temp file), but the temp file still occupies
// remoteApplyMaxBytes (default 1 GiB) of /tmp for as long as the
// download+upload pair runs, so the number of concurrent applies must not be
// traffic-determined. The gate below caps the panel-wide in-flight applies;
// an apply that cannot get a slot within the queue budget fails 503 instead
// of queueing unboundedly. The per-server 'reinstalling' claim (index.js)
// serializes one server; this gate bounds the sum across all of them.
const REMOTE_APPLY_MAX_CONCURRENT_DOWNLOADS = (() => {
const n = parseInt(process.env.REMOTE_APPLY_MAX_CONCURRENT_DOWNLOADS || "", 10);
return Number.isFinite(n) && n > 0 ? n : 3;
})();
const REMOTE_APPLY_DOWNLOAD_QUEUE_WAIT_MS = (() => {
const n = parseInt(process.env.REMOTE_APPLY_DOWNLOAD_QUEUE_WAIT_MS || "", 10);
return Number.isFinite(n) && n >= 0 ? n : 15000;
})();
class ApplyDownloadBusyError extends Error {
constructor(waitMs) {
super(`Too many store installs are already downloading on this panel; retry after ${waitMs} ms.`);
this.code = "apply-download-busy";
}
}
// Slot accounting: acquire hands out free slots immediately and parks the
// rest; release hands the freed slot to the longest-waiting waiter (active
// stays constant on a hand-off) or decrements it. A waiter whose budget
// expires is removed without touching the count, so timeouts can never leak
// or phantom-free a slot.
function createDownloadGate(limit, queueWaitMs) {
let active = 0;
const waiters = [];
const handOff = () => {
const next = waiters.shift();
if (!next) {
active -= 1;
return;
}
// Slot transfer: the released slot passes straight to the waiter, so the
// in-flight count never changes here.
clearTimeout(next.timer);
next.resolve();
};
return {
async acquire() {
if (active < limit) {
active += 1;
return;
}
await new Promise((resolve, reject) => {
const entry = {
resolve,
timer: setTimeout(() => {
const at = waiters.indexOf(entry);
if (at >= 0) waiters.splice(at, 1);
reject(new ApplyDownloadBusyError(queueWaitMs));
}, queueWaitMs),
};
if (entry.timer.unref) entry.timer.unref();
waiters.push(entry);
});
},
release() {
if (active > 0) handOff();
},
};
}
const defaultDownloadGate = createDownloadGate(REMOTE_APPLY_MAX_CONCURRENT_DOWNLOADS, REMOTE_APPLY_DOWNLOAD_QUEUE_WAIT_MS);
// The proxy path must never hold an artifact body in heap: httpGetRaw-style
// buffering accumulated the full body as chunks and then Buffer.concat'ed a
// second full copy — two remoteApplyMaxBytes-sized allocations per request,
// which a tenant could multiply into a worker OOM. The artifact is streamed
// into the temp file instead, with a counting Transform as a second byte cap
// so the util stays safe even if an injected (non-capping) stream source is
// supplied. "wx" refuses to follow a pre-planted temp-file symlink, and 0600
// keeps the artifact panel-private.
async function streamDownloadToFile(source, filePath, maxBytes) {
let total = 0;
await pipeline(
source,
new Transform({
transform(chunk, _enc, cb) {
total += chunk.length;
if (maxBytes > 0 && total > maxBytes) {
cb(new Error(`Download too large (limit ${maxBytes} bytes)`));
return;
}
cb(null, chunk);
},
}),
fs.createWriteStream(filePath, { flags: "wx", mode: 0o600 }),
);
}
async function applyRemoteAssetToServer(deps, { serverName, entry, url, destPath, providerId, versionId }) {
if (!deps || typeof deps !== "object") {
throw new Error("Asset apply dependencies are required.");
}
const bot = String(serverName || entry?.name || "").trim();
if (!bot) {
return { ok: false, statusCode: 400, error: "missing-bot" };
}
// destPath is validated before any lookup or download: a hostile path must
// never reach the server/node layer (the panel route re-checks even earlier,
// before its install claim is taken).
const dest = validateStoreApplyDestPath(destPath);
if (!dest.ok) {
return { ok: false, statusCode: 400, error: dest.error };
}
const destRel = dest.destPath;
const resolvedEntry = entry || (typeof deps.findServer === "function" ? await deps.findServer(bot) : null);
if (!resolvedEntry) {
return { ok: false, statusCode: 404, error: "server-not-found" };
}
if (!deps.isRemoteEntry(resolvedEntry)) {
return { ok: false, statusCode: 400, error: "server-not-on-node" };
}
const node = await deps.findNodeByIdOrName(resolvedEntry.nodeId);
if (!node) {
return { ok: false, statusCode: 400, error: "node-not-found" };
}
const underCloudflare = typeof deps.nodeUnderCloudflare === "function"
? deps.nodeUnderCloudflare(node)
: !!node.under_cloudflare;
const baseUrl = deps.buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, underCloudflare);
if (!baseUrl) {
return { ok: false, statusCode: 400, error: "invalid-node-address" };
}
const headers = deps.nodeAuthHeadersFor(node, true);
const technicalName = getTechnicalServerName(resolvedEntry, bot);
let safeUrl = String(url || "").trim();
if (!safeUrl) {
return { ok: false, statusCode: 400, error: "missing-url" };
}
try {
const validated = await deps.assertSafeRemoteUrl(safeUrl);
safeUrl = validated.toString();
} catch {
return { ok: false, statusCode: 400, error: "invalid-url" };
}
const destFile = path.posix.basename(destRel);
if (deps.remoteApplyProxyDownload) {
const ctx = await deps.resolveRemoteFsContext(bot);
if (!ctx.remote || !ctx.node) {
return { ok: false, statusCode: 404, error: "server-not-on-node" };
}
try {
const pingRes = await deps.nodeFsPost(ctx.node, "/v1/fs/list", { path: ctx.baseDir, depth: 0, server: ctx.serverName }, 5000);
if (pingRes.status === 401) {
return {
ok: false,
statusCode: 502,
error: "node-auth-failed",
detail: "Token mismatch. Re-deploy config.yml to the node.",
};
}
if (pingRes.status === 0) {
return {
ok: false,
statusCode: 502,
error: "node-unreachable",
detail: "Cannot connect to node agent.",
};
}
} catch {
}
// The gate spans download AND upload: the temp file lives for exactly that
// window, so bounding the pair is what bounds /tmp usage, not just
// bandwidth. A non-busy gate failure is a wiring/programming error and is
// rethrown into the route's own catch.
if (typeof deps.httpGetStream !== "function") {
throw new Error("remote-apply proxy download requires an httpGetStream dependency (SSRF-safe streaming GET)");
}
const gate = deps.remoteApplyDownloadGate || defaultDownloadGate;
try {
await gate.acquire();
} catch (err) {
if (err && err.code === "apply-download-busy") {
return { ok: false, statusCode: 503, error: "apply-download-busy", detail: err.message };
}
throw err;
}
const tmpFile = path.join(os.tmpdir(), `adpanel-apply-${crypto.randomBytes(8).toString("hex")}`);
try {
let fetched;
try {
fetched = await deps.httpGetStream(safeUrl, {
maxBytes: deps.remoteApplyMaxBytes,
timeoutMs: deps.remoteApplyTimeoutMs,
maxRedirects: deps.remoteFetchMaxRedirects,
});
} catch {
return { ok: false, statusCode: 400, error: "remote-download-failed" };
}
try {
await streamDownloadToFile(fetched.stream, tmpFile, deps.remoteApplyMaxBytes);
} catch {
return { ok: false, statusCode: 400, error: "remote-download-failed" };
}
let targetDir = ctx.baseDir;
try {
const destDirRel = path.posix.dirname(destRel);
targetDir = safeJoinUnix(ctx.baseDir, destDirRel === "." ? "" : destDirRel);
} catch {
return { ok: false, statusCode: 400, error: "invalid-destPath" };
}
const uploadUrl = `${baseUrl}/v1/fs/upload`;
await uploadFileToNode({
node: ctx.node,
uploadUrl,
headers,
filePath: tmpFile,
filename: destFile,
targetDir,
serverName: ctx.serverName,
});
return { ok: true, remote: true, msg: "downloaded-and-uploaded", destPath: destRel };
} catch (error) {
const detail = error.message || "stream-upload-failed";
if (error.nodeStatusCode === 507) {
try {
const nodeJson = JSON.parse(error.nodeBody);
if (nodeJson.error === "disk_limit_exceeded") {
return Object.assign({ ok: false, statusCode: 507 }, nodeJson);
}
} catch {
}
}
if (detail.includes("401")) {
return {
ok: false,
statusCode: 502,
error: "node-auth-failed",
detail: "Token mismatch. Re-deploy config.yml to the node.",
};
}
return { ok: false, statusCode: 502, error: "node_upload_failed", detail };
} finally {
// Unlink BEFORE releasing the slot: the slot must span exactly the
// window in which the temp file's disk footprint exists, so a queued
// apply never starts its download while dying temp files from the
// previous holder still occupy /tmp (the 2x-limit transient pile-up).
try {
await fsp.unlink(tmpFile);
} catch {
}
gate.release();
}
}
// Forward-to-node mode: the daemon dispatches /v1/servers/<name>/apply-version
// BEFORE bearer-token auth (ServeHTTP routes the path straight to
// handleApplyVersion), so the signed panel envelope is this endpoint's only
// authentication and the handler fails closed on a missing signature. The
// signature binds the provider/version the body carries, so the signed
// values are derived from the same body object — the HMAC can never drift
// from what is sent.
const requestedProviderId = String(providerId ?? "").trim();
const requestedVersionId = String(versionId ?? "").trim();
const forwardBody = { url: safeUrl, nodeId: resolvedEntry.nodeId, destPath: destRel };
if (requestedProviderId) forwardBody.providerId = requestedProviderId;
if (requestedVersionId) forwardBody.versionId = requestedVersionId;
const forwardUrl = `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/apply-version`;
const signingSecrets = typeof deps.nodeAdminSigningSecrets === "function"
? (deps.nodeAdminSigningSecrets(node) || [])
: [];
if (!signingSecrets.length) {
// The daemon rejects an unsigned apply-version unconditionally, so the
// forward can never succeed without PANEL_HMAC_SECRET. Fail here with the
// actual cause instead of relaying the daemon's 403, which reads as a
// node-token problem and sends operators re-deploying config.yml for
// nothing.
return {
ok: false,
statusCode: 500,
error: "admin-signing-not-configured",
detail: "PANEL_HMAC_SECRET is not set on the panel, so remote store installs cannot be signed. Set it on the panel (and re-deploy config.yml to the node) to install on remote nodes.",
};
}
// Signing ladder, mirroring the reinstall flow: the node's derived secret
// first, the fleet master second (nodes still on a pre-rotation config),
// then one nonce-less legacy attempt for daemons that predate
// nonce-authenticated signatures. Only a bad-signature rejection escalates
// the ladder — every other outcome is returned as-is. The forward is
// idempotent (a re-download replaces the same destination file), so the
// retries cannot double-apply.
const forwardAttempts = signingSecrets.map((secret) => ({ secret, legacy: false }));
forwardAttempts.push({ secret: signingSecrets[0], legacy: true });
const signedForwardOnce = async (includeProviderVersion) => {
const body = includeProviderVersion
? forwardBody
: { url: forwardBody.url, nodeId: forwardBody.nodeId, destPath: forwardBody.destPath };
const signedProviderId = String(body.providerId ?? "");
const signedVersionId = String(body.versionId ?? "");
let last = null;
for (const attempt of forwardAttempts) {
const signed = nodeHmac.signPanelApplyVersionRequest(
attempt.secret,
technicalName,
signedProviderId,
signedVersionId,
safeUrl,
{ legacy: attempt.legacy }
);
if (!signed) break;
const attemptHeaders = Object.assign({}, headers, signed.headers);
last = await deps.httpRequestJson(forwardUrl, "POST", attemptHeaders, body, 60_000);
if (!isBadSignatureRejection(last)) break;
}
return last;
};
let response = await signedForwardOnce(true);
// Back-compat: daemons decode bodies with DisallowUnknownFields, so a binary
// predating the providerId/versionId fields answers 400 "unknown field".
// Those fields only bind signature+audit context — prune both, re-sign over
// the empty bindings such a daemon itself verifies against, and resend.
const unknownField = unknownJsonFieldFromNodeResponse(response);
if ((unknownField === "providerId" || unknownField === "versionId") && (requestedProviderId || requestedVersionId)) {
response = await signedForwardOnce(false);
}
if (!response) {
return { ok: false, statusCode: 502, error: "node-forward-failed", detail: "apply-version request was not sent" };
}
if (response.status === 507 && response.json?.error === "disk_limit_exceeded") {
return Object.assign({ ok: false, statusCode: 507 }, response.json);
}
if (response.status !== 200 || !(response.json && response.json.ok)) {
const detail = response.json && (response.json.detail || response.json.error)
? (response.json.detail || response.json.error)
: `node-status-${response.status}`;
if (response.status === 401 || response.status === 403) {
return {
ok: false,
statusCode: 502,
error: "node-auth-failed",
// Surface the daemon's own rejection reason (bad-signature, expired,
// hmac-not-configured, unauthorized, ...) so the operator hint is not
// blindly "re-deploy the token" when the cause is e.g. clock skew.
detail: `Token or HMAC mismatch (${detail}). Re-deploy config.yml to the node.`,
};
}
return { ok: false, statusCode: 502, error: detail || `node-forward-failed-${response.status}` };
}
return { ok: true, remote: true, msg: "forwarded-to-node", destPath: destRel };
}
// Mirrors index.js isLegacySigningRejection: the daemon's signature rejections
// come back 401/403 with error "bad-signature". Any other outcome — including
// "missing-signature" (impossible once signed), "nonce-required" (the
// legacy rung against a modern daemon) and "expired" (clock skew) — must stop
// the ladder: re-signing cannot change those answers.
function isBadSignatureRejection(response) {
const status = Number(response && response.status);
return (status === 401 || status === 403) && !!(response.json && response.json.error === "bad-signature");
}
module.exports = {
applyRemoteAssetToServer,
validateStoreApplyDestPath,
// Exported for tests: gates must be injectable so suite-level concurrency
// never shares the module-default counter's state.
createDownloadGate,
};