"use strict"; // Structure pins for the revocation/deletion cleanup hardening: // // adpanel:scheduler-canonical-authz — the perm-change reauthorize predicate // (schedulerActionStillAuthorizedAfterPermChange) resolves the target server // through findServer exactly like the fire-time re-check // (ensureScheduledJobStillAuthorized) before applying the access/permission // layers: job data and legacy rows can carry a name that is not a fixed // point of sanitizeServerToken ("My Bot" vs "My-Bot") and the authorization // layers match the raw lowercase form only, so without the resolution a // revoke on a legacy-named server deleted schedules a fire would have kept. // // adpanel:scheduler-fleet-paginate — cancelSchedulesCreatedBy and // deleteServerSchedules scan the queue through the fleet-paginated helper // (fetchAllSchedulerJobsInStates) instead of fixed getJobs(state, 0, N) // windows, which silently missed jobs beyond the first page of the // fleet-wide queue: a revocation sweep or a server deletion must see the // whole fleet, same as the tasks list/quota paths. // // Account revocation must use the original creator ID and the occurrence's // exact repeat key, not infer ownership from a reusable email or task name. // // index.js is a ~56k-line application bundle (module side effects, DB and // network at require time — never require() it from a test), so these tests // pin the fixes structurally on well-anchored source windows, matching // tests/scheduler-redis-decouple.test.js and // tests/agent-job-suspension-gate.test.js. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const ROOT = path.join(__dirname, ".."); const INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8"); // Strip full-line comments so prose mentioning a marker can never satisfy a // source-level pin (mirrors stripFullLineComments in // tests/backup-create-cap-refusal.test.js). function stripFullLineComments(src) { return src .split("\n") .filter((line) => !/^\s*\/\//.test(line)) .join("\n"); } // The code view of a function: full-line comments stripped before matching. function functionWindow(src, anchor, label) { const start = src.indexOf(anchor); assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`); const end = src.indexOf("\n}", start); assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`); return stripFullLineComments(src.slice(start, end + 2)); } // Raw (comment-preserving) window of the same shape — for assertions ABOUT // the constraint comments themselves, which live on comment lines. function rawWindow(src, anchor, label) { const start = src.indexOf(anchor); assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`); const end = src.indexOf("\n}", start); assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`); return src.slice(start, end + 2); } // Window from an anchor to an explicit end anchor — deterministic slicing // that survives unrelated edits elsewhere in the bundle. function windowBetween(src, startAnchor, endAnchor, label) { const start = src.indexOf(startAnchor); assert.notStrictEqual(start, -1, `${label}: start anchor not found: ${startAnchor}`); const end = src.indexOf(endAnchor, start + startAnchor.length); assert.notStrictEqual(end, -1, `${label}: end anchor not found after start: ${endAnchor}`); return src.slice(start, end); } test("the perm-change reauthorize predicate resolves through findServer exactly like the fire-time re-check", () => { const body = functionWindow(INDEX_SRC, "async function schedulerActionStillAuthorizedAfterPermChange", "schedulerActionStillAuthorizedAfterPermChange"); // Resolve FIRST, with the twin's exact fail-closed construction. const resolveAt = body.indexOf("const serverEntry = await findServer(serverName).catch(() => null);"); const fallbackAt = body.indexOf('const accessServerName = String(serverEntry?.name || serverName || "").trim();'); const accessAt = body.indexOf("userHasAccessToServer(email, accessServerName)"); const permsAt = body.indexOf("getEffectivePermsForUserOnServer(email, accessServerName)"); assert.notStrictEqual(resolveAt, -1, "the predicate must resolve the server name through findServer (fail-closed catch) before the access check"); assert.notStrictEqual(fallbackAt, -1, "a findServer miss must fall back to the raw name — mirroring ensureScheduledJobStillAuthorized's posture (fail closed, never a privilege gain)"); assert.notStrictEqual(accessAt, -1, "the access layer must run against the resolved canonical name"); assert.notStrictEqual(permsAt, -1, "the permission layer must run against the resolved canonical name"); assert.ok( resolveAt < accessAt && resolveAt < permsAt, "the findServer resolution must precede both authorization layers — a perm-change revoke must decide with the same name a fire would" ); assert.ok( !body.includes("userHasAccessToServer(email, serverName)") && !body.includes("getEffectivePermsForUserOnServer(email, serverName)"), "no authorization layer may run against the raw job-data/param name anymore — that is the legacy-name fail-closed availability bug" ); // The ADPanel Agent layer is server-independent and stays untouched. assert.ok( body.includes("findUserByEmail(email)") && body.includes("userCanUseAdpanelAgent(u)"), "the server-independent ADPanel Agent capability layer must remain in the predicate" ); // The constraint note lives with the predicate, cross-referencing the twin. const comment = windowBetween( INDEX_SRC, "adpanel:planner-access-job-retract", "async function schedulerActionStillAuthorizedAfterPermChange", "reauthorize predicate comment" ); assert.ok( comment.includes("adpanel:scheduler-canonical-authz") && comment.includes("ensureScheduledJobStillAuthorized"), "the predicate's comment block must carry the adpanel:scheduler-canonical-authz note cross-referencing the fire-time re-check" ); // The ONE home — defined exactly once, signature unchanged. assert.strictEqual( INDEX_SRC.split("async function schedulerActionStillAuthorizedAfterPermChange").length - 1, 1, "the reauthorize predicate must be defined exactly once (callers resolve inside it — no per-caller fork)" ); }); test("revocation/deletion cleanups scan the whole fleet through fetchAllSchedulerJobsInStates, not fixed windows", () => { const cancelBody = functionWindow(INDEX_SRC, "async function cancelSchedulesCreatedBy", "cancelSchedulesCreatedBy"); const deleteBody = functionWindow(INDEX_SRC, "async function deleteServerSchedules", "deleteServerSchedules"); // Both cleanups route through the one fleet-paginated helper. assert.ok( cancelBody.includes('fetchAllSchedulerJobsInStates(["waiting", "active", "delayed", "paused"]).catch(() => [])'), "cancelSchedulesCreatedBy must scan the whole fleet, not the first 2000 per state" ); assert.ok( cancelBody.includes("await disableRecurringScheduleForJob(job, reason)"), "recurrence removal and failure-streak reset must use the shared helper" ); assert.ok( deleteBody.includes('fetchAllSchedulerJobsInStates(["waiting", "active", "delayed"]).catch(() => [])'), "deleteServerSchedules must scan the whole fleet across the three states instead of three first-page windows" ); // No fixed-window getJobs([state], 0, N) may remain in either function. assert.ok(!/getJobs\(\[/.test(cancelBody), "cancelSchedulesCreatedBy must not scan fixed getJobs windows anymore"); assert.ok(!/getJobs\(\[/.test(deleteBody), "deleteServerSchedules must not scan fixed getJobs windows anymore"); // Each site carries the constraint comment — checked against the RAW // window (the tag lives on a comment line, which functionWindow strips). for (const [label, anchor] of [["cancelSchedulesCreatedBy", "async function cancelSchedulesCreatedBy"], ["deleteServerSchedules", "async function deleteServerSchedules"]]) { assert.ok(rawWindow(INDEX_SRC, anchor, label).includes("adpanel:scheduler-fleet-paginate"), `${label} must reference the fleet-pagination constraint`); } // The helper is the ONE home, defined once as a hoisted top-level // declaration — both callers precede its definition in the file. assert.strictEqual( INDEX_SRC.split("async function fetchAllSchedulerJobsInStates(states)").length - 1, 1, "fetchAllSchedulerJobsInStates must be defined exactly once — the cleanup sites call it, never a forked copy" ); }); function cancellationHarness() { const creator = { id: 42, email: "user@example.test" }; const removedJobs = []; const removedKeys = []; const resetKeys = []; const scans = []; const makeJob = (id, userId, serverName, actionType, repeat) => ({ id, data: { userId, userName: creator.email, serverName, actionType, name: "same name" }, ...repeat, async remove() { removedJobs.push(id); }, }); const jobs = [ makeJob("one-time", 42, "first", "server_start"), makeJob("repeatable", 42, "first", "server_start", { repeatJobKey: "first-key", opts: { repeat: {} } }), makeJob("manual-key", 42, "first", "server_stop", { opts: { repeat: { key: "manual-key" } } }), makeJob("other-server", 42, "second", "server_start", { repeatJobKey: "other-key" }), makeJob("replacement", 43, "first", "server_start", { repeatJobKey: "replacement-key" }), makeJob("unknown-key", 42, "first", "server_start", { opts: { repeat: {} } }), ]; const queue = { async removeRepeatableByKey(key) { removedKeys.push(key); return true; }, async getRepeatableJobs() { assert.fail("must not fall back to name matching"); }, }; const cancel = new Function( "schedulerQueue", "schedulerStateRedis", "resetSchedulerFailureStreak", "fetchAllSchedulerJobsInStates", "schedulerActionStillAuthorizedAfterPermChange", "console", `${functionWindow(INDEX_SRC, "async function disableRecurringScheduleForJob", "repeatable cleanup")} ${functionWindow(INDEX_SRC, "async function cancelSchedulesCreatedBy", "account cleanup")} return cancelSchedulesCreatedBy;` )( queue, {}, async (_client, key) => resetKeys.push(key), async (states) => { scans.push(states); return jobs; }, async (_email, action) => action === "server_start", { log() {}, warn() {}, error() {} } ); return { cancel, creator, removedJobs, removedKeys, resetKeys, scans }; } test("deletion cancels the original creator's one-time jobs and exact repeat keys only", async () => { const state = cancellationHarness(); assert.deepStrictEqual(await state.cancel(state.creator, { reason: "account deleted" }), { removed: 4 }); assert.deepStrictEqual(state.removedJobs, ["one-time"]); assert.deepStrictEqual(state.removedKeys, ["first-key", "manual-key", "other-key"]); assert.deepStrictEqual(state.resetKeys, state.removedKeys); assert.deepStrictEqual(state.scans, [["waiting", "active", "delayed", "paused"]]); }); test("permission revocation keeps authorized schedules and schedules on other servers", async () => { const state = cancellationHarness(); assert.deepStrictEqual(await state.cancel(state.creator, { serverName: "first", reauthorize: true }), { removed: 1 }); assert.deepStrictEqual(state.removedJobs, []); assert.deepStrictEqual(state.removedKeys, ["manual-key"]); assert.deepStrictEqual(state.resetKeys, ["manual-key"]); });