"use strict"; // Regression tests for the scheduler worker's per-server backup count cap. // // Bug: every scheduled backup fire is a full server-directory copy on the // node, and the daemon's backupsMax quota is opt-in (usually unset = // unlimited). The recurrence floor (SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS, // see scheduler-backup-interval-floor.test.js) bounds how FAST backups can // be created, but not the TOTAL — recurring tasks created before that fix // (or at 5-minute intervals) kept stacking backups unboundedly until the // node's disk was exhausted. // // Fix (adpanel:backup-count-cap): before the create POST, the worker lists // the server's existing backups via nodes.js listServerBackupsForHygiene // (direct node GET — the performer itself needs a session req a queue worker // does not have; the helper retries the listing once on failure) and throws // once the count reaches SCHEDULER_MAX_BACKUPS_PER_SERVER, so the job lands // in failed state with a self-explanatory failedReason instead of consuming // disk. The listing fails OPEN (warn + proceed): a node listing outage must // not silently cancel scheduled backups — the create is still preceded by // the worker's execution-time backups_create re-check // (ensureScheduledJobStillAuthorized). // // index.js boots servers on require and cannot be loaded in-process, so — // same technique as scheduler-hardening / scheduler-backup-interval-floor — // the REAL backup case body, constant, and hygiene list helper are sliced // from source and evaluated with injected fakes. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); // The REAL shared 507 predicate (services/node-fs-relay.js one-true-home) the // worker backup case gates its quota pass-through on — the harness binds the // genuine helper, never a hand copy that could drift. const { isNodeQuota507 } = require("../services/node-fs-relay"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const NODES_JS = path.join(ROOT, "nodes.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const nodesSource = fs.readFileSync(NODES_JS, "utf8"); // Strip full-line comments so prose mentioning the markers cannot satisfy // the source-level assertions. function stripFullLineComments(src) { return src .split("\n") .filter((line) => !/^\s*\/\//.test(line)) .join("\n"); } const indexCode = stripFullLineComments(indexSource); function sliceFrom(source, startMarker, endMarker, label) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`); const end = source.indexOf(endMarker, start); assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`); return source.slice(start, end); } // --------------------------------------------------------------------------- // The REAL hygiene list helper (nodes.js listServerBackupsForHygiene), so the // harness stub of ./nodes.js exposes the genuine retry-once listing and // 200-ok (json.backups || []) semantics instead of a hand copy that could // drift from what the scheduler case actually calls. // --------------------------------------------------------------------------- const listServerBackupsForHygieneSrc = sliceFrom( nodesSource, "async function listServerBackupsForHygiene", "\nfunction relayPanelResult", "nodes.js hygiene list helper" ); const makeListServerBackupsForHygiene = new Function( "nodeUrl", "httpJson", "nodeHeaders", `"use strict"; ${listServerBackupsForHygieneSrc} return listServerBackupsForHygiene;` ); // --------------------------------------------------------------------------- // The real cap constant, evaluated from source (env-dependent, so built per // call like evalQuotaSlice in scheduler-hardening.test.js) // --------------------------------------------------------------------------- function evalCap() { return new Function( sliceFrom( indexSource, "const SCHEDULER_MAX_BACKUPS_PER_SERVER", "\nfunction scheduleToCron(", "backup count cap constant" ) + "\nreturn SCHEDULER_MAX_BACKUPS_PER_SERVER;" )(); } // --------------------------------------------------------------------------- // The real worker backup case, run in a switch harness with a stubbed // ./nodes.js — same technique as the console_command harness in // scheduler-hardening.test.js. // --------------------------------------------------------------------------- const backupCaseBody = sliceFrom( indexSource, 'case "backup": {', 'case "planner_next_to_agent": {', "worker backup case" ); const makeBackupRunner = new Function( "payload", "serverName", "userName", "userId", "require", "recordActivity", "getCanonicalServerName", "SCHEDULER_MAX_BACKUPS_PER_SERVER", // The case body gates its 507 pass-through on the shared isNodeQuota507 // predicate (a module-scope binding in index.js), so the harness binds the // REAL helper from services/node-fs-relay.js — same technique as the real // hygiene list helper above — never a hand copy that could drift. "isNodeQuota507", // adpanel:scheduler-server-identity-bind — the case re-checks its execution // resolution against the authorization row (and the stored serverId when // present); the REAL helper is sliced and bound below, and `job` is now a // case-scope binding (the helper reads job.data.serverId and owns the // disable+throw). "job", "schedulerAuthzServerEntry", "ensureSchedulerFireServerIdentity", `"use strict"; return async () => { const actionType = "backup"; switch (actionType) { ${backupCaseBody} } };` ); // The REAL fire-context identity check, sliced from source and bound to the // injected disable machinery (scheduler-hardening's technique). const makeBackupIdentityChecker = (disableImpl) => new Function( "disableRecurringScheduleForJob", sliceFrom( indexSource, "async function ensureSchedulerFireServerIdentity(", "\n// adpanel:planner-access-job-retract", "fire identity checker (backup case)" ) + "\nreturn ensureSchedulerFireServerIdentity;" )(disableImpl); function makeWorkerHarness({ listResponse, listThrows, listHelperThrows, cap, payload, createResponse }) { const httpCalls = []; const activities = []; const warnings = []; const errors = []; const disabled = []; const disableStub = async (job, reason) => { disabled.push({ jobId: job.id, reason }); return true; }; const stubNodes = { remoteContext: async () => ({ exists: true, remote: true, node: { baseUrl: "http://node.example:8081", token: "node-token" }, nodeServerName: "srv01", baseDir: "/vols/srv01", // adpanel:scheduler-server-identity-bind — matches the injected authz // row below, so the normal fire passes the shipped identity check. server: { id: 7, name: "srv01" }, }), httpJson: async (url, opts) => { httpCalls.push({ url, opts }); if (opts.method === "GET") { if (listThrows) throw listThrows; return listResponse; } return createResponse || { status: 200, json: { ok: true, backup: { id: "bk-new", name: "Scheduled Backup" } } }; }, nodeUrl: (node, p) => `${node.baseUrl}${p}`, nodeHeaders: (node) => ({ Authorization: `Bearer ${node.token}` }), }; // The scheduler case lists through the real nodes.js helper (retry-once) // over the stubbed transport; listHelperThrows simulates a crash outside // the helper's never-throws contract to cover the worker's catch branch. stubNodes.listServerBackupsForHygiene = listHelperThrows ? async () => { throw listHelperThrows; } : makeListServerBackupsForHygiene(stubNodes.nodeUrl, stubNodes.httpJson, stubNodes.nodeHeaders); const run = makeBackupRunner( payload || { backupName: "Nightly", description: "scheduled" }, "srv01", "creator@example.com", 42, (moduleName) => { assert.strictEqual(moduleName, "./nodes.js"); return stubNodes; }, (serverName, type, detail) => activities.push({ serverName, type, detail }), (server) => (server && server.name) || server, cap, isNodeQuota507, { id: "job-1", data: { serverName: "srv01" }, repeatJobKey: "repeat-key-1" }, { id: 7, name: "srv01" }, makeBackupIdentityChecker(disableStub) ); return { run: async () => { const originalWarn = console.warn; const originalError = console.error; console.warn = (...args) => warnings.push(args.join(" ")); console.error = (...args) => errors.push(args.join(" ")); try { return await run(); } finally { console.warn = originalWarn; console.error = originalError; } }, httpCalls, activities, warnings, errors, disabled, }; } const listOk = (count) => ({ status: 200, json: { ok: true, backups: Array.from({ length: count }, (_, i) => ({ id: `bk-${i}` })) }, }); // The shipped default cap, read from source — not a test-local copy. const REAL_CAP = evalCap(); test("the shipped default cap is 50 and only a finite integer > 0 overrides it via env", () => { delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER; assert.strictEqual(REAL_CAP, 50, "built-in default must be 50"); process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = "7"; assert.strictEqual(evalCap(), 7); delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER; // Zero, negatives, non-integers and garbage all keep the default — never // 0/unlimited and never a fractional cap. for (const bad of ["0", "-3", "3.5", "abc", ""]) { process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = bad; assert.strictEqual(evalCap(), 50, `env=${JSON.stringify(bad)} must fall back to 50`); } delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER; }); test("worker refuses the backup BEFORE the create once the server is at the cap", async () => { const { run, httpCalls } = makeWorkerHarness({ listResponse: listOk(REAL_CAP), cap: REAL_CAP }); // The throw is what lands the BullMQ job in failed state with this // failedReason — no disk is consumed on the node. await assert.rejects( () => run(), new RegExp(`Scheduled backup skipped: server already has ${REAL_CAP} backups \\(limit ${REAL_CAP}\\)`) ); assert.strictEqual(httpCalls.length, 1, "only the listing GET may leave the panel"); assert.strictEqual(httpCalls[0].opts.method, "GET"); assert.ok(httpCalls[0].url.endsWith("/v1/servers/srv01/backups"), httpCalls[0].url); }); test("at cap-1 the scheduled backup still proceeds (exactly one GET then one POST)", async () => { const { run, httpCalls, activities } = makeWorkerHarness({ listResponse: listOk(REAL_CAP - 1), cap: REAL_CAP }); const result = await run(); assert.deepStrictEqual(result, { success: true, action: "backup", backupId: "bk-new" }); assert.strictEqual(httpCalls.length, 2, "count check (GET) then create (POST)"); assert.strictEqual(httpCalls[0].opts.method, "GET"); assert.strictEqual(httpCalls[1].opts.method, "POST"); // adpanel:backup-cap-fallback — the fallback cap travels as a request // HEADER, never a JSON body field: the daemon's readJSON rejects unknown // body fields, so a body field would break the create on an older daemon // during a rolling upgrade (unknown headers are ignored instead). assert.strictEqual( httpCalls[1].opts.headers["X-ADPanel-Backups-Max"], String(REAL_CAP), "the create POST must carry the scheduler cap in the X-ADPanel-Backups-Max header" ); assert.ok(!("backupsMax" in httpCalls[1].opts.body), "the create body must not carry a backupsMax field (breaks older daemons)"); assert.strictEqual(activities.length, 1, "the successful create is still audited"); assert.strictEqual(activities[0].type, "backup_create"); }); test("a missing backups array on an ok listing counts as zero, not as unknown", async () => { const { run, httpCalls } = makeWorkerHarness({ listResponse: { status: 200, json: { ok: true } }, cap: 3 }); const result = await run(); assert.strictEqual(result.success, true, "json.backups || [] semantics, same as performPanelListBackups"); assert.strictEqual(httpCalls[1].opts.method, "POST"); }); test("listing failure fails OPEN: the create still runs, with a warning", async () => { // Non-200 listing (node returned an error status): the helper retries once, // then the worker warns and proceeds — two listing GETs, then the POST. const unavailable = makeWorkerHarness({ listResponse: { status: 502, json: { ok: false, error: "node_backup_list_failed" } }, cap: 3, }); assert.strictEqual((await unavailable.run()).success, true); assert.strictEqual(unavailable.httpCalls.length, 3, "listing GET, one retry, then the create POST"); assert.strictEqual(unavailable.httpCalls[2].opts.method, "POST", "create must proceed on a failed listing"); assert.ok( unavailable.warnings.some((w) => /Backup count check unavailable for srv01/.test(w)), "the fail-open path must warn" ); // Thrown listing error (network-level failure): the helper normalizes it // into { ok: false } after its retry, so it takes the same fail-open warn, // still carrying the underlying error. const thrown = makeWorkerHarness({ listThrows: new Error("node unreachable"), cap: 3, }); assert.strictEqual((await thrown.run()).success, true); assert.strictEqual(thrown.httpCalls.length, 3, "the retry burns the thrown attempt too"); assert.strictEqual(thrown.httpCalls[2].opts.method, "POST", "create must proceed when the listing throws"); assert.ok( thrown.warnings.some((w) => /Backup count check unavailable for srv01 \(node unreachable\)/.test(w)), "the fail-open path must warn with the underlying error" ); // A crash outside the helper's never-throws contract still must not abort // the backup: the worker's own catch warns and proceeds. const helperCrash = makeWorkerHarness({ listHelperThrows: new Error("helper exploded"), cap: 3, }); assert.strictEqual((await helperCrash.run()).success, true); assert.strictEqual(helperCrash.httpCalls[0].opts.method, "POST", "create must proceed when the count check itself throws"); assert.ok( helperCrash.warnings.some((w) => /Backup count check failed for srv01: helper exploded/.test(w)), "the worker's catch branch must warn and proceed" ); }); // --------------------------------------------------------------------------- // Source-level wiring: the guard is in the worker case, before the create // --------------------------------------------------------------------------- test("the worker backup case enforces the cap through the named constant before the create POST", () => { const caseCode = stripFullLineComments(backupCaseBody); assert.ok(caseCode.includes("SCHEDULER_MAX_BACKUPS_PER_SERVER"), "must reference the named constant, not a magic number"); assert.ok( caseCode.includes("Scheduled backup skipped: server already has ${existingBackupCount} backups"), "the refusal must carry a self-explanatory failedReason" ); // adpanel:backup-dial-canonical — the dial (and the count check) use the // resolved canonical storage name (ctx.nodeServerName), not the job's raw // serverName, so the endpoint pin tracks the canonical form. const listPos = caseCode.indexOf('`/v1/servers/${encodeURIComponent(ctx.nodeServerName)}/backups`'); const createPos = caseCode.indexOf("method: \"POST\""); assert.ok(listPos >= 0, "the case must list backups via the node backups endpoint"); assert.ok(createPos > listPos, "the count check must run BEFORE the create POST"); // The count check fails open: both warn paths must exist and the throw must // sit OUTSIDE the listing try/catch (so only the cap refusal propagates). assert.ok(caseCode.includes("Backup count check unavailable"), "non-200 listings warn and proceed"); assert.ok(caseCode.includes("Backup count check failed"), "thrown listing errors warn and proceed"); assert.ok( caseCode.includes("if (existingBackupCount !== null && existingBackupCount >= SCHEDULER_MAX_BACKUPS_PER_SERVER)"), "the cap refusal must only trigger on a successfully counted listing" ); }); // --------------------------------------------------------------------------- // adpanel:log-injection-backup-name — the fire path's clamp must strip C0/C1 // controls and collapse whitespace BEFORE the length cap (identical strip to // the interactive relay), because the name reaches console.log, // recordActivity → webhooks and the daemon verbatim. // --------------------------------------------------------------------------- test("the fire path strips control characters from the backup name/description before the daemon POST", async () => { const { run, httpCalls } = makeWorkerHarness({ listResponse: listOk(0), cap: 3, payload: { backupName: "Nightly\u0000Backup\nSecond\u001f", description: "line1\nline2\u007f\ttail" }, }); const result = await run(); assert.strictEqual(result.success, true); const post = httpCalls.find((c) => c.opts.method === "POST"); assert.ok(post, "the create POST must happen"); assert.strictEqual(post.opts.body.name, "Nightly Backup Second"); assert.strictEqual(post.opts.body.description, "line1 line2 tail"); }); test("a scheduler backup name that strips to empty falls back to the daemon default (Scheduled Backup )", async () => { const { run, httpCalls } = makeWorkerHarness({ listResponse: listOk(0), cap: 3, payload: { backupName: "\u0000\n\t\u001f", description: "" }, }); const result = await run(); assert.strictEqual(result.success, true); const post = httpCalls.find((c) => c.opts.method === "POST"); assert.strictEqual(post.opts.body.name.startsWith("Scheduled Backup "), true, post.opts.body.name); assert.strictEqual(post.opts.body.description, "Created by scheduler", "the case body's empty-description default must still engage"); }); // --------------------------------------------------------------------------- // adpanel:scheduler-backup-error-masking — the daemon's non-structured error // bodies can embed absolute node filesystem paths (copyDir's unrewrapped // os.PathError text), and the worker's throw lands verbatim in the BullMQ // failedReason that GET /api/scheduler/:serverName/tasks serves to the task // CREATOR. The scheduled branch must mirror the manual relay's disclosure // contract (nodes.js performPanelCreateBackup: 403/404 structured bodies and // the 507 quota body pass through; everything else is logged server-side // only and rethrown generic — "the node layout is never disclosed to end // users"), with the 507 arm gated on the SAME shared isNodeQuota507 // predicate as the manual relay (one-true-home in services/node-fs-relay.js), // so non-quota 507 bodies are masked too. Same path-free failedReason // doctrine as the scheduled file-write sibling (schedulerNodeFileWrite). // --------------------------------------------------------------------------- const PATHY_DAEMON_BODY = "failed to copy server files: open /var/adpanel/volumes/srv01/world/level.dat: permission denied"; test("a path-bearing daemon 500 is masked: the thrown failedReason is the generic string, the full body only reaches console.error", async () => { const { run, activities, errors } = makeWorkerHarness({ listResponse: listOk(0), cap: 3, createResponse: { status: 500, json: { error: PATHY_DAEMON_BODY } }, }); await assert.rejects( () => run(), (err) => { assert.strictEqual(err.message, "Backup create failed on node (status 500)"); assert.ok(!err.message.includes("/var/adpanel/volumes"), "the absolute node path must never reach the failedReason"); return true; } ); assert.ok( errors.some((e) => e.includes(`[scheduler] Backup create failed for srv01: node status 500, detail=${PATHY_DAEMON_BODY}`)), "the FULL daemon body must reach console.error (server-side log only)" ); // The failed run records no activity (recordActivity runs on success only); // whatever is ever recorded must stay path-free. for (const entry of activities) { assert.ok(!JSON.stringify(entry).includes("/var/adpanel/volumes"), "no node path may reach the activity record"); } assert.strictEqual(activities.length, 0, "a failed create is not recorded as backup_create"); }); test("a path-bearing daemon 500 with NO json body still masks (no-body detail), never disclosing the status text as a path", async () => { const { run, errors } = makeWorkerHarness({ listResponse: listOk(0), cap: 3, createResponse: { status: 502, json: null }, }); await assert.rejects( () => run(), (err) => { assert.strictEqual(err.message, "Backup create failed on node (status 502)"); return true; } ); assert.ok( errors.some((e) => e.includes("[scheduler] Backup create failed for srv01: node status 502, detail=no body")), "a missing body logs the no-body placeholder server-side" ); }); test("a non-JSON daemon error body reaches the server-side log via the raw-text fallback (never just 'no body')", async () => { const { run, errors } = makeWorkerHarness({ listResponse: listOk(0), cap: 3, // nodes.js httpJson resolves { status, json, text }: a plain-text panic // or proxy HTML body arrives with json=null and the raw bytes in text — // the same fallback shape the manual relay's log accepts (text can be // large; it must reach the server log, never the failedReason). createResponse: { status: 502, json: null, text: "panic: copyDir exploded at /var/adpanel/volumes/srv01" }, }); await assert.rejects( () => run(), (err) => { assert.strictEqual(err.message, "Backup create failed on node (status 502)", "the raw text must not reach the failedReason"); return true; } ); assert.ok( errors.some((e) => e.includes("detail=panic: copyDir exploded at /var/adpanel/volumes/srv01")), "the raw response text is logged server-side instead of the no-body placeholder" ); }); test("a structured daemon 403/404 body passes through UNMASKED (mirror of the manual relay's pass-through)", async () => { const limited = makeWorkerHarness({ listResponse: listOk(0), cap: 3, createResponse: { status: 403, json: { error: "backup_limit_reached", message: "backup limit reached", current: 5, max: 5 } }, }); await assert.rejects( () => limited.run(), (err) => { assert.strictEqual(err.message, "backup_limit_reached", "structured, path-free daemon bodies are not masked"); return true; } ); const notFound = makeWorkerHarness({ listResponse: listOk(0), cap: 3, createResponse: { status: 404, json: { error: "server not found" } }, }); await assert.rejects( () => notFound.run(), (err) => { assert.strictEqual(err.message, "server not found"); return true; } ); }); test("a daemon 507 passes through ONLY for the shared isNodeQuota507 quota codes; a non-quota 507 body is masked", async () => { // The shared predicate (services/node-fs-relay.js one-true-home, the same // gate as the manual relay) accepts exactly the daemon's two quota codes — // both pass through verbatim, user-actionable and path-free. for (const quotaCode of ["disk_limit_exceeded", "disk_capacity_exceeded"]) { const quota = makeWorkerHarness({ listResponse: listOk(0), cap: 3, createResponse: { status: 507, json: { error: quotaCode } }, }); await assert.rejects( () => quota.run(), (err) => { assert.strictEqual(err.message, quotaCode, "the quota body is user-actionable and path-free"); return true; } ); } // A non-quota 507 body from a misbehaving/older node is NOT echoed into // the failedReason: it falls to the generic masked arm, the full body // reaching console.error (server-side log) only. const nonQuota = makeWorkerHarness({ listResponse: listOk(0), cap: 3, createResponse: { status: 507, json: { error: "insufficient disk space" } }, }); await assert.rejects( () => nonQuota.run(), (err) => { assert.strictEqual(err.message, "Backup create failed on node (status 507)"); assert.ok(!err.message.includes("insufficient disk space"), "a non-quota 507 body must not reach the failedReason"); return true; } ); assert.ok( nonQuota.errors.some((e) => e.includes("[scheduler] Backup create failed for srv01: node status 507, detail=insufficient disk space")), "the non-quota 507 body reaches console.error (server-side log only)" ); }); test("the success path is untouched by the masking branches (200 ok still returns and audits)", async () => { const { run, activities, errors } = makeWorkerHarness({ listResponse: listOk(0), cap: 3, createResponse: { status: 200, json: { ok: true, backup: { id: "bk-new", name: "Scheduled Backup" } } }, }); const result = await run(); assert.deepStrictEqual(result, { success: true, action: "backup", backupId: "bk-new" }); assert.strictEqual(activities.length, 1, "the successful create is still audited"); assert.strictEqual(activities[0].type, "backup_create"); assert.strictEqual(errors.length, 0, "the masking branches must not log anything on success"); }); test("the worker backup case carries the masking contract: pass-throughs before the generic throw, full body to console.error only", () => { const caseCode = stripFullLineComments(backupCaseBody); const passThroughPos = caseCode.indexOf('result.status === 403 || result.status === 404'); const quotaPos = caseCode.indexOf("isNodeQuota507(result.status, result.json)"); const genericPos = caseCode.indexOf("Backup create failed on node (status ${result.status})"); assert.ok(passThroughPos >= 0, "structured 403/404 daemon bodies must pass through"); assert.ok(quotaPos >= 0, "the 507 arm must gate on the SAME shared isNodeQuota507 predicate as the manual relay (one-true-home)"); assert.ok(genericPos >= 0, "everything else must rethrow the generic, path-free string"); assert.ok(passThroughPos < genericPos && quotaPos < genericPos, "the pass-throughs must precede the generic throw"); assert.ok( caseCode.includes("console.error(`[scheduler] Backup create failed for ${serverName}: node status ${result.status}, detail=${String(result.json?.error || result.text || \"no body\")}`)"), "the FULL body (json.error, else the raw response text, else no body) must reach console.error (server-side only) before the generic throw" ); assert.ok(!caseCode.includes("`Backup failed: ${result.status}`"), "the old path-leaking throw must be gone"); });