"use strict"; // Pins the guard ordering on the /api/servers/:bot/versions* surface // (audit findings 3 and 4). // // index.js is a ~52k-line application bundle (module side effects, DB and // network at require time), so — matching the convention of // tests/preflight-guard-sweep.test.js — these regressions are pinned // structurally on well-anchored source windows. // // Finding 3: GET /versions and GET /versions/:providerId answered 404 // server-not-found BEFORE the ownership check, so any authenticated user // could distinguish "server exists but is not yours" (403) from "no such // server" (404) by name-guessing. Sibling routes on the same surface // (/files/list, versions/apply) check access first and answer 403 for both. // The fix moves the access check above the existence resolution; the 404 may // only fire after access was granted (admins and "all" ACL grants probing an // unknown name). // // Finding 4: versions/apply is store_access-gated while every sibling write // path demands files_upload/files_create, and its destPath accepted any // relative path (e.g. the bot's own entry script) with content from any // public URL. The shared validateStoreApplyDestPath now pins destPath to // server.jar or plugins|mods/, and must be evaluated BEFORE the // reinstall claim is taken so a hostile body never occupies the slot. The // validator's accepted surface itself is unit-tested in // utils/server-asset-apply-destpath.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 ROOT = path.join(__dirname, ".."); const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8"); const APPLY_UTIL_SRC = fs.readFileSync(path.join(ROOT, "utils", "server-asset-apply.js"), "utf8"); const REG_POSITIONS = (() => { const positions = []; const re = /^(?:app|router)\.(?:get|post|put|delete|patch|all|use)\s*\(/gm; let m; while ((m = re.exec(INDEX_SRC)) !== null) positions.push(m.index); return positions; })(); function routeWindow(regPrefix, label) { const start = INDEX_SRC.indexOf(regPrefix); assert.notStrictEqual(start, -1, `${label}: route anchor not found: ${regPrefix}`); let end = INDEX_SRC.length; for (const p of REG_POSITIONS) { if (p > start && p < end) end = p; } assert.ok(end > start, `${label}: empty window for ${regPrefix}`); return INDEX_SRC.slice(start, end); } function indexOf(window, needle, label, why) { const at = window.indexOf(needle); assert.notStrictEqual(at, -1, `${label}: expected source to contain: ${needle}${why ? ` (${why})` : ""}`); return at; } // The anti-enumeration contract: 401 auth → 403 access → existence → 404. // The access check must precede the existence resolution, and the 404 // server-not-found answer must only be reachable after the access check — // otherwise the route answers 404 for unknown names and 403 for existing // ones, leaking which server names exist. // // The admin short-circuit is pinned too: userHasAccessToServer must stay // behind `!isAdminUser &&` so an admin's existence probe keeps skipping the // ACL lookup (and admins legitimately keep getting the 404 for unknown // names). The needle is the FULL conjunctive form — dropping only the admin // conjunct (`if (!(await userHasAccessToServer(...)))`) is behavior-neutral // today (userHasAccessToServer self-grants admins) but still fails this pin, // so the guard cannot quietly lose its shape. function assertAccessBeforeExistence(window, label) { const authAt = indexOf(window, "await isAuthenticated(req)", label, "the 401 gate"); const accessNeedle = "!isAdminUser && !(await userHasAccessToServer("; const accessAt = indexOf(window, accessNeedle, label, "the admin-short-circuited access check"); const resolveNeedle = window.includes("await resolveTemplateForBot(safeBotName)") ? "await resolveTemplateForBot(safeBotName)" : "await findServer(raw)"; const resolveAt = indexOf(window, resolveNeedle, label, "the existence resolution"); const notFoundAt = indexOf(window, '"server-not-found"', label, "the enumeration-leaking 404"); assert.ok(authAt < accessAt, `${label}: the 401 gate must precede the access check`); assert.ok(accessAt < resolveAt, `${label}: the access check must precede the existence resolution — a 404 answered before the access check is a server-name enumeration oracle`); assert.ok(accessAt < notFoundAt, `${label}: the 404 server-not-found answer must only be reachable after the access check`); // The denial shares the sibling routes' body: same 403 for "not yours" and // "no such server", so the two cases stay indistinguishable. indexOf(window, '"no-access-to-server"', label, "the shared no-access 403 body"); // The store_access gate stays after existence resolution, keyed on the // canonical name, exactly as before. indexOf(window, 'permission: "store_access"', label, "the store_access gate"); } test("GET /api/servers/:bot/versions checks server access before resolving existence", () => { assertAccessBeforeExistence(routeWindow('app.get("/api/servers/:bot/versions"', "GET versions"), "GET versions"); }); test("GET /api/servers/:bot/versions/:providerId checks server access before resolving existence", () => { assertAccessBeforeExistence( routeWindow('app.get("/api/servers/:bot/versions/:providerId"', "GET versions/:providerId"), "GET versions/:providerId" ); }); test("POST /api/servers/:bot/template checks server access before resolving existence", () => { // Third instance of the same resolve-first pattern on this surface, found // during line-by-line verification of the versions fixes. The action-token // gate already blinds it to probers without a token (minting requires // store_access, which resolves false for unknown names), so the access // check here is uniformity with the rest of the surface — pinned so the // pattern cannot quietly return. const w = routeWindow('app.post("/api/servers/:bot/template"', "POST template"); const tokenAt = indexOf(w, "requireActionTokenOr403", "POST template", "the action-token gate"); assertAccessBeforeExistence(w, "POST template"); assert.ok( tokenAt < w.indexOf("!isAdminUser && !(await userHasAccessToServer("), "POST template: the action-token gate must stay ahead of the access check (401-shape ordering)" ); }); test("a remote store preference cannot change the installed template used for reinstall", async () => { const route = routeWindow('app.post("/api/servers/:bot/template"', "POST template"); for (const remote of [true, false]) { const entry = { name: "alpha", rowId: 7, nodeId: remote ? "remote-node" : null, template: "custom", status: "stopped", remote }; let handler, saved, response; vm.runInNewContext(route.slice(0, route.indexOf("\n});") + 4), { app: { post: (_path, routeHandler) => { handler = routeHandler; } }, isAuthenticated: async () => true, requireActionTokenOr403: async () => true, isAdmin: async () => false, userHasAccessToServer: async () => true, findServer: async () => entry, getEffectivePermsForUserOnServer: async () => ({ store_access: true }), normalizeTemplateId: (template) => template, serverOpGuard: { isGuardedServerStatus: () => false }, isRemoteEntry: (row) => row.remote, db: { query: async (sql, params) => { assert.match(sql, /^UPDATE servers SET template = \? WHERE id = \? AND node_id <=> \?/); saved = Array.from(params); return { affectedRows: 1 }; } }, invalidateServerIndexCache() {}, }); await handler({ params: { bot: "alpha" }, session: { user: "member@example.com" }, body: { template: "python" } }, { json: (body) => { response = body; } }, assert.ifError); assert.deepStrictEqual({ ...response }, remote ? { ok: true, preference: "python" } : { ok: true, template: "python" }); assert.equal(entry.template, "custom"); assert.deepEqual(saved, remote ? undefined : ["python", 7, null]); } }); test("POST /api/servers/:bot/versions/apply validates destPath before the install claim", () => { const w = routeWindow('app.post("/api/servers/:bot/versions/apply"', "POST versions/apply"); const destCheckAt = indexOf(w, "validateStoreApplyDestPath(rawDestPath)", "POST versions/apply", "the destPath constraint"); const claimAt = indexOf(w, "await claimReinstallOperation(bot)", "POST versions/apply", "the install claim"); assert.ok( destCheckAt < claimAt, "POST versions/apply: the destPath check must precede the install claim — a hostile body must not occupy the server's 'reinstalling' slot even briefly" ); // The route forwards the VALIDATED value (normalized default included), not // the raw body field. The destructure itself is the only legitimate // occurrence of the raw binding. indexOf(w, "destCheck.destPath", "POST versions/apply", "the validated destPath being used"); const rawBindingCount = w.split("destPath: rawDestPath").length - 1; assert.strictEqual( rawBindingCount, 1, "rawDestPath must only appear in the body destructure — forwarding it unvalidated would restore the arbitrary-write primitive" ); }); test("POST /api/servers/:bot/versions/apply keeps the store_access gate before server resolution", () => { const w = routeWindow('app.post("/api/servers/:bot/versions/apply"', "POST versions/apply"); const accessAt = indexOf(w, "await userHasAccessToServer(req.session.user, bot)", "POST versions/apply", "the access check"); const findServerAt = indexOf(w, "await findServer(bot)", "POST versions/apply", "the server lookup"); assert.ok( accessAt < findServerAt, "POST versions/apply: the access check must stay ahead of the server lookup (the reference sibling the GET routes were aligned with)" ); }); test("applyRemoteAssetToServer validates destPath before any lookup and exports the validator", () => { const validateAt = APPLY_UTIL_SRC.indexOf("const dest = validateStoreApplyDestPath(destPath)"); const firstLookupAt = APPLY_UTIL_SRC.indexOf("typeof deps.findServer"); assert.notStrictEqual(validateAt, -1, "the util must run the destPath validator"); assert.notStrictEqual(firstLookupAt, -1, "the util performs a server lookup"); assert.ok( validateAt >= 0 && validateAt < firstLookupAt, "the util must validate destPath before its first lookup or download" ); const exportBlock = APPLY_UTIL_SRC.slice(APPLY_UTIL_SRC.indexOf("module.exports")); assert.ok( exportBlock.includes("validateStoreApplyDestPath"), "the validator must be exported so the panel route and tests share one implementation" ); });