1624 lines
82 KiB
JavaScript
1624 lines
82 KiB
JavaScript
"use strict";
|
|
|
|
// Regression tests for the 2026-10 scheduler hardening pass (four review
|
|
// findings against POST/GET /api/scheduler/:server/tasks and the BullMQ
|
|
// worker in index.js).
|
|
//
|
|
// Finding 1 (scheduled console commands bypassed sanitizeConsoleCommand):
|
|
// The interactive console relay enforces ≤512 chars / single line / no
|
|
// control characters (nodes.js sanitizeConsoleCommand, enforced in
|
|
// performPanelConsoleCommand). The scheduler path only checked the command
|
|
// was truthy at creation and sent payload.command raw to the node at
|
|
// execution — and the daemon writes the whole string to the container's
|
|
// stdin (stdinConn.sendCommand appends "\n"), so a stored multi-line blob
|
|
// fired a BATCH of console commands on every tick of a recurring task.
|
|
// Fix: the create route validates through the very same exported
|
|
// sanitizer and stores the sanitized command; the worker re-runs the
|
|
// contract on the STORED command (recurring jobs created before the gate
|
|
// persist in Redis) and disables a recurring schedule whose payload can
|
|
// never pass validation instead of failing on every tick forever.
|
|
//
|
|
// Finding 2 (maxSchedules had no default): the quota was only applied when
|
|
// an admin had configured resources/docker maxSchedules; unset meant
|
|
// unlimited recurring tasks. Fix: resolveSchedulerMaxSchedules degrades
|
|
// undefined/0/negative to SCHEDULER_DEFAULT_MAX_SCHEDULES (50, overridable
|
|
// via env) — never to "unlimited".
|
|
//
|
|
// Finding 3 (create-time permission asymmetry): only the backup action was
|
|
// permission-gated at creation; console_command / server_start /
|
|
// server_stop / create_file / modify_file were not, so a user with only
|
|
// scheduler_create got "Task created successfully!" for a job that then
|
|
// failed on every run at the execution-time re-check. Fix: the create
|
|
// route gates every action through the SAME schedulerRequiredPermissionForAction
|
|
// mapping the worker re-verifies with. Task names are also clamped to 100
|
|
// chars server-side (bot.ejs maxlength="100").
|
|
//
|
|
// Finding 4 (GET /tasks leaked payloads): the task list returned
|
|
// job.data.payload (other users' console command text, file-write
|
|
// contents, agent prompts) and job.returnvalue (which echoes the executed
|
|
// console command) to any scheduler_access user. Fix: both fields are
|
|
// stripped; the shipped UI (bot.js renderSchedulerTasks) only renders
|
|
// id/name/actionType/status/time.
|
|
//
|
|
// index.js boots servers on require and cannot be loaded in-process, so —
|
|
// same technique as scheduler-interval-floor / scheduler-file-actions — the
|
|
// REAL functions are sliced from source and evaluated with injected fakes.
|
|
// nodes.js IS requirable (see node-relay-cors tests), so the real shipped
|
|
// sanitizeConsoleCommand export is used directly.
|
|
|
|
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_JS = path.join(ROOT, "index.js");
|
|
const indexSource = fs.readFileSync(INDEX_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, shipped sanitizer (the exact function the interactive console
|
|
// relay gates on — the scheduler must not have a private divergent copy).
|
|
const nodesModule = require("../nodes.js");
|
|
const realSanitize = nodesModule.sanitizeConsoleCommand;
|
|
const realStreak = require("../utils/scheduler-failure-streak");
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 1 — the shared command contract itself (real export)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("the shared sanitizer rejects multi-line command blobs (the batching vector)", () => {
|
|
const check = realSanitize("say hi\nstop\nsay bye");
|
|
assert.strictEqual(check.ok, false);
|
|
assert.strictEqual(check.error, "multiline_command_not_allowed");
|
|
});
|
|
|
|
test("the shared sanitizer rejects control characters", () => {
|
|
for (const bad of ["say\x07", "say\x1b[2J", "say\x7f", "say\x0bhi", "say\x0chi"]) {
|
|
const check = realSanitize(bad);
|
|
assert.strictEqual(check.ok, false, JSON.stringify(bad));
|
|
assert.strictEqual(check.error, "invalid_command_characters");
|
|
}
|
|
});
|
|
|
|
test("the shared sanitizer rejects commands over 512 characters", () => {
|
|
const check = realSanitize("a".repeat(513));
|
|
assert.strictEqual(check.ok, false);
|
|
assert.strictEqual(check.error, "command_too_long");
|
|
assert.strictEqual(realSanitize("a".repeat(512)).ok, true, "exactly 512 must pass");
|
|
});
|
|
|
|
test("the shared sanitizer rejects empty/whitespace commands and strips NULs", () => {
|
|
assert.strictEqual(realSanitize("").ok, false);
|
|
assert.strictEqual(realSanitize(" ").ok, false);
|
|
assert.strictEqual(realSanitize(null).ok, false);
|
|
assert.strictEqual(realSanitize(undefined).ok, false);
|
|
// NUL bytes are stripped BEFORE the emptiness check, not treated as content.
|
|
assert.deepStrictEqual(realSanitize("\0\0"), { ok: false, error: "empty_command" });
|
|
});
|
|
|
|
test("the shared sanitizer trims and passes legitimate single-line commands", () => {
|
|
assert.deepStrictEqual(realSanitize(" say hello world "), { ok: true, command: "say hello world" });
|
|
assert.deepStrictEqual(realSanitize("stop"), { ok: true, command: "stop" });
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 1 — create route wiring (source-level)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function createRouteSlice(source) {
|
|
return sliceFrom(
|
|
source,
|
|
'app.post("/api/scheduler/:serverName/tasks"',
|
|
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
|
|
"scheduler create route"
|
|
);
|
|
}
|
|
|
|
test("create route validates console commands through the shared sanitizer and fails closed", () => {
|
|
const route = createRouteSlice(indexCode);
|
|
assert.ok(
|
|
route.includes("typeof nodesRouter.sanitizeConsoleCommand === \"function\""),
|
|
"the create route must guard on the sanitizer being exported (fail-closed), like the AI console path"
|
|
);
|
|
assert.ok(
|
|
route.includes("nodesRouter.sanitizeConsoleCommand(payload?.command)"),
|
|
"the create route must run payload.command through the shared sanitizer"
|
|
);
|
|
assert.ok(
|
|
route.includes("payload.command = commandCheck.command;"),
|
|
"the SANITIZED command is what gets stored in the job payload"
|
|
);
|
|
assert.ok(
|
|
!route.includes("actionType === \"console_command\" && !payload?.command"),
|
|
"the old truthy-only check must be gone"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 1 — worker wiring (behavioral against the real sanitizer)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Slice the real console_command case body out of the BullMQ worker and run
|
|
// it inside a switch harness with injected dependencies. The fake
|
|
// ./nodes.js carries the REAL sanitizeConsoleCommand export, so this proves
|
|
// the shipped contract gates the execution path.
|
|
const consoleCaseBody = sliceFrom(
|
|
indexSource,
|
|
'case "console_command": {',
|
|
'case "server_start": {',
|
|
"worker console_command case"
|
|
);
|
|
|
|
const makeConsoleRunner = new Function(
|
|
"payload", "serverName", "job", "userName", "userId",
|
|
"require", "recordActivity", "disableRecurringScheduleForJob",
|
|
// adpanel:scheduler-server-identity-bind — the case re-checks its execution
|
|
// resolution against the authorization row (and the stored serverId); the
|
|
// REAL helper is sliced below and bound to the same disable recorder, so
|
|
// these tests drive the shipped check, not a mimic.
|
|
"schedulerAuthzServerEntry", "ensureSchedulerFireServerIdentity",
|
|
`"use strict";
|
|
return async () => {
|
|
const actionType = "console_command";
|
|
switch (actionType) {
|
|
${consoleCaseBody}
|
|
}
|
|
};`
|
|
);
|
|
|
|
// The REAL fire-context identity check (adpanel:scheduler-server-identity-bind),
|
|
// sliced from source and bound to the injected disable machinery.
|
|
const makeIdentityChecker = (disableImpl) => new Function(
|
|
"disableRecurringScheduleForJob",
|
|
sliceFrom(
|
|
indexSource,
|
|
"async function ensureSchedulerFireServerIdentity(",
|
|
"\n// adpanel:planner-access-job-retract",
|
|
"fire identity checker"
|
|
) + "\nreturn ensureSchedulerFireServerIdentity;"
|
|
)(disableImpl);
|
|
|
|
function makeWorkerHarness({ payload, jobData = { serverName: "srv01" }, ctxServer = { id: 7, name: "srv01" }, authzServerEntry = { id: 7, name: "srv01" } }) {
|
|
const httpCalls = [];
|
|
const disabled = [];
|
|
const activities = [];
|
|
const disableStub = async (job, reason) => disabled.push({ jobId: job.id, reason });
|
|
const stubNodes = {
|
|
// THE REAL SHIPPED SANITIZER — parity is by construction.
|
|
sanitizeConsoleCommand: realSanitize,
|
|
remoteContext: async () => ({
|
|
exists: true,
|
|
remote: true,
|
|
node: { baseUrl: "http://node.example:8081", token: "node-token" },
|
|
nodeServerName: "srv01",
|
|
baseDir: "/vols/srv01",
|
|
server: ctxServer,
|
|
}),
|
|
httpJson: async (url, opts) => {
|
|
httpCalls.push({ url, opts });
|
|
return { status: 200, json: { ok: true } };
|
|
},
|
|
nodeUrl: (node, p) => `${node.baseUrl}${p}`,
|
|
nodeHeaders: (node) => ({ Authorization: `Bearer ${node.token}` }),
|
|
};
|
|
const run = makeConsoleRunner(
|
|
payload,
|
|
"srv01",
|
|
{ id: "job-1", data: jobData, repeatJobKey: "repeat-key-1" },
|
|
"creator@example.com",
|
|
42,
|
|
(moduleName) => {
|
|
assert.strictEqual(moduleName, "./nodes.js");
|
|
return stubNodes;
|
|
},
|
|
(serverName, type, detail) => activities.push({ serverName, type, detail }),
|
|
disableStub,
|
|
authzServerEntry,
|
|
makeIdentityChecker(disableStub),
|
|
);
|
|
return { run, httpCalls, disabled, activities };
|
|
}
|
|
|
|
test("worker rejects a stored multi-line command before any node call and disables the recurring schedule", async () => {
|
|
const { run, httpCalls, disabled } = makeWorkerHarness({ payload: { command: "say hi\nstop\nsay bye" } });
|
|
await assert.rejects(() => run(), /Invalid stored console command/);
|
|
assert.strictEqual(httpCalls.length, 0, "no HTTP call may leave the panel for a multi-line stored command");
|
|
assert.strictEqual(disabled.length, 1, "the recurring schedule must be disabled, not retried forever");
|
|
assert.match(disabled[0].reason, /invalid stored console command/);
|
|
assert.strictEqual(disabled[0].jobId, "job-1");
|
|
});
|
|
|
|
test("worker rejects a stored control-character command and an over-long command", async () => {
|
|
for (const command of ["say\x07hi", "a".repeat(600), "", null, undefined]) {
|
|
const { run, httpCalls, disabled } = makeWorkerHarness({ payload: { command } });
|
|
await assert.rejects(() => run(), /Invalid stored console command/, JSON.stringify(command));
|
|
assert.strictEqual(httpCalls.length, 0, JSON.stringify(command));
|
|
assert.strictEqual(disabled.length, 1, JSON.stringify(command));
|
|
}
|
|
});
|
|
|
|
test("worker sends the sanitized command in exactly one node call for a valid stored payload", async () => {
|
|
const { run, httpCalls, activities } = makeWorkerHarness({ payload: { command: " say hello " } });
|
|
const result = await run();
|
|
assert.deepStrictEqual(result, { success: true, action: "console_command", command: "say hello" });
|
|
assert.strictEqual(httpCalls.length, 1);
|
|
const { url, opts } = httpCalls[0];
|
|
assert.strictEqual(url, "http://node.example:8081/v1/servers/srv01/command");
|
|
assert.strictEqual(opts.method, "POST");
|
|
assert.deepStrictEqual(opts.body, { command: "say hello" });
|
|
assert.strictEqual(activities.length, 1);
|
|
assert.strictEqual(activities[0].type, "console_command");
|
|
assert.deepStrictEqual(activities[0].detail, { command: "say hello", source: "scheduler" });
|
|
});
|
|
|
|
test("worker sanitizes through the nodes.js export, not a private copy (source parity)", () => {
|
|
const caseCode = stripFullLineComments(consoleCaseBody);
|
|
assert.ok(
|
|
caseCode.includes("typeof nodesModule.sanitizeConsoleCommand === \"function\""),
|
|
"the worker must fail closed when the sanitizer is not exported"
|
|
);
|
|
assert.ok(
|
|
caseCode.includes("nodesModule.sanitizeConsoleCommand(payload?.command)"),
|
|
"the worker must run the STORED command through the shared sanitizer"
|
|
);
|
|
assert.ok(
|
|
caseCode.includes("disableRecurringScheduleForJob(job, reason)"),
|
|
"an invalid stored payload must disable the recurring schedule"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// adpanel:scheduler-server-identity-bind — the dial cases re-resolve the
|
|
// server through remoteContext (an independent DB lookup), so a delete+recreate
|
|
// landing between the authorization lookup and a case's own resolution could
|
|
// execute the stored payload ONCE on a DIFFERENT owner's recreated server.
|
|
// Every dial case re-checks its resolution against the authorization row (and
|
|
// the stored serverId when present) via the REAL sliced helper; a mismatch
|
|
// takes the SAME unauthorized consequence as the re-auth failure (the one
|
|
// disable machinery + the throw). The agent/planner cases need no call — they
|
|
// dial no daemon here; their enqueue gates enforce the SAME stored-serverId +
|
|
// authz-row comparison instead (adpanel:scheduler-agent-enqueue-identity,
|
|
// driven behaviorally in its own section below).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("fire aborts with the unauthorized consequence when the dial resolves a different row than authorized (one-shot window closed)", async () => {
|
|
// Legacy job (no stored serverId): the authz-row arm alone must fire.
|
|
const { run, httpCalls, disabled } = makeWorkerHarness({
|
|
payload: { command: "say hi" },
|
|
jobData: { serverName: "srv01" },
|
|
ctxServer: { id: 8, name: "srv01" }, // the name now answers to a NEW row
|
|
authzServerEntry: { id: 7, name: "srv01" }, // the row authorization decided on
|
|
});
|
|
await assert.rejects(() => run(), /different server row/);
|
|
assert.strictEqual(httpCalls.length, 0, "no dial may reach the recreated server's node");
|
|
assert.strictEqual(disabled.length, 1, "the recurring schedule must be disabled through the ONE disable machinery");
|
|
assert.match(disabled[0].reason, /identity mismatch/);
|
|
assert.strictEqual(disabled[0].jobId, "job-1");
|
|
});
|
|
|
|
test("fire aborts when the dial row differs from the STORED serverId even with no authz row (recreate before the authz lookup)", async () => {
|
|
const { run, httpCalls, disabled } = makeWorkerHarness({
|
|
payload: { command: "say hi" },
|
|
jobData: { serverName: "srv01", serverId: 7 },
|
|
ctxServer: { id: 8, name: "srv01" },
|
|
authzServerEntry: null, // authorization lookup missed/failed — not proof of a mismatch
|
|
});
|
|
await assert.rejects(() => run(), /different server row/);
|
|
assert.strictEqual(httpCalls.length, 0);
|
|
assert.strictEqual(disabled.length, 1);
|
|
});
|
|
|
|
test("a matching dial row (and a null authz row with no stored serverId) never blocks the fire", async () => {
|
|
// Matching row: the normal path is untouched.
|
|
const ok = makeWorkerHarness({ payload: { command: "say hi" } });
|
|
assert.deepStrictEqual(await ok.run(), { success: true, action: "console_command", command: "say hi" });
|
|
assert.strictEqual(ok.httpCalls.length, 1);
|
|
assert.strictEqual(ok.disabled.length, 0);
|
|
// Null authz row + no stored serverId: nothing proves a mismatch, so the
|
|
// check must not disable (transient-lookup doctrine).
|
|
const nullAuthz = makeWorkerHarness({ payload: { command: "say hi" }, authzServerEntry: null });
|
|
assert.deepStrictEqual(await nullAuthz.run(), { success: true, action: "console_command", command: "say hi" });
|
|
assert.strictEqual(nullAuthz.disabled.length, 0);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// adpanel:scheduler-server-identity-bind — same-row legacy_id backfill vs
|
|
// same-name recreate at the dial. Panel-created rows are born legacy_id =
|
|
// NULL (the guarded insert carries no id field) and the routine index writers
|
|
// backfill legacy_id = String(the row's OWN composed id) onto the SAME living
|
|
// row (ON DUPLICATE KEY UPDATE legacy_id = VALUES(legacy_id)) on ordinary
|
|
// lifecycle writes — so the composed id flips from the number N to the string
|
|
// "N" under a healthy schedule. The identity check therefore coerces both
|
|
// sides to String; these tests pin that a same-row backfill authorizes (both
|
|
// arms), a backfill landing between the two resolutions authorizes, and a
|
|
// true recreate (different AUTO_INCREMENT id, whose composed form is "M")
|
|
// still takes the mismatch outcome.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("fire proceeds when the SAME row's legacy_id backfill lands after the stored write (stored numeric id, dial resolves the composed string id)", async () => {
|
|
// The exact regression: the schedule stored the composed id as the NUMBER 7
|
|
// (row born legacy_id = NULL), then an ordinary lifecycle write (e.g. a
|
|
// status label on the first start) backfilled legacy_id = "7" onto the same
|
|
// living row. A strict compare read "7" !== 7 as a same-name recreate and
|
|
// permanently disabled the healthy schedule.
|
|
const { run, httpCalls, disabled } = makeWorkerHarness({
|
|
payload: { command: "say hi" },
|
|
jobData: { serverName: "srv01", serverId: 7 },
|
|
ctxServer: { id: 7, legacy_id: "7", name: "srv01" }, // post-backfill: composed id is now the STRING "7"
|
|
authzServerEntry: { id: "7", legacy_id: "7", name: "srv01" }, // authz resolved after the same backfill
|
|
});
|
|
assert.deepStrictEqual(await run(), { success: true, action: "console_command", command: "say hi" });
|
|
assert.strictEqual(httpCalls.length, 1);
|
|
assert.strictEqual(disabled.length, 0, "a same-row legacy_id backfill must never disable a healthy schedule");
|
|
});
|
|
|
|
test("fire proceeds on the ctx-vs-authz arm when the backfill lands between the two resolutions (numeric authz id, string ctx identity)", async () => {
|
|
// Legacy job (no stored serverId): only the authz-row arm runs. The authz
|
|
// lookup resolved the row BEFORE its backfill (numeric composed id), the
|
|
// dial resolved it AFTER (composed string id) — the same row either way.
|
|
const { run, httpCalls, disabled } = makeWorkerHarness({
|
|
payload: { command: "say hi" },
|
|
jobData: { serverName: "srv01" },
|
|
ctxServer: { id: 7, legacy_id: "7", name: "srv01" },
|
|
authzServerEntry: { id: 7, name: "srv01" },
|
|
});
|
|
assert.deepStrictEqual(await run(), { success: true, action: "console_command", command: "say hi" });
|
|
assert.strictEqual(httpCalls.length, 1);
|
|
assert.strictEqual(disabled.length, 0);
|
|
});
|
|
|
|
test("fire still aborts on a TRUE recreate whose composed id is the new row's backfilled string (stored 7 vs composed \"8\")", async () => {
|
|
// The recreate got AUTO_INCREMENT id 8; after its own first lifecycle write
|
|
// the new row's composed id is the string "8" — a DIFFERENT string from the
|
|
// stored "7", so the coercion must not mask the recreate.
|
|
const { run, httpCalls, disabled } = makeWorkerHarness({
|
|
payload: { command: "say hi" },
|
|
jobData: { serverName: "srv01", serverId: 7 },
|
|
ctxServer: { id: 8, legacy_id: "8", name: "srv01" },
|
|
authzServerEntry: null,
|
|
});
|
|
await assert.rejects(() => run(), /different server row/);
|
|
assert.strictEqual(httpCalls.length, 0);
|
|
assert.strictEqual(disabled.length, 1);
|
|
assert.match(disabled[0].reason, /identity mismatch/);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// adpanel:scheduler-server-identity-bind — the re-auth function itself:
|
|
// a stored serverId that no longer matches the resolved row takes the EXACT
|
|
// "creator no longer has access" outcome. This is the admin-authored residual
|
|
// fix: userHasAccessToServer returns true unconditionally for admins, so
|
|
// without the binding an admin schedule never failed re-auth on ANY server.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// The REAL re-auth function, sliced from source with its dependency surface
|
|
// injected (the REAL required-permission mapping from the slice above).
|
|
const makeStillAuthorized = ({ findServerImpl, accessNames = [], perms = {}, user = { admin: true, suspended: false }, disableImpl }) => {
|
|
const disabled = [];
|
|
const ensureScheduledJobStillAuthorized = new Function(
|
|
"findUserByEmail", "findServer", "userHasAccessToServer",
|
|
"getEffectivePermsForUserOnServer", "schedulerRequiredPermissionForAction",
|
|
"userCanUseAdpanelAgent", "disableRecurringScheduleForJob",
|
|
sliceFrom(
|
|
indexSource,
|
|
"async function ensureScheduledJobStillAuthorized(job) {",
|
|
"\n// adpanel:scheduler-server-identity-bind — the ONE execution-context identity",
|
|
"still-authorized slice"
|
|
) + "\nreturn ensureScheduledJobStillAuthorized;"
|
|
)(
|
|
async (_email) => user && { id: 42, ...user },
|
|
// async: the real call site hangs .catch off the lookup (the canonical-authz
|
|
// fallback), so the fake must return a promise.
|
|
async (name) => {
|
|
if (findServerImpl.throwErr) throw findServerImpl.throwErr;
|
|
return findServerImpl.row;
|
|
},
|
|
async (_email, name) => accessNames.map((n) => String(n).toLowerCase()).includes(String(name).toLowerCase()),
|
|
async () => perms,
|
|
schedulerRequiredPermissionForAction,
|
|
() => true,
|
|
async (job, reason) => {
|
|
disabled.push(reason);
|
|
if (disableImpl) return disableImpl(job, reason);
|
|
return true;
|
|
}
|
|
);
|
|
return { ensureScheduledJobStillAuthorized, disabled };
|
|
};
|
|
|
|
const AUTHZ_JOB = (serverId) => ({
|
|
id: "job-authz-1",
|
|
data: { serverName: "srv01", actionType: "console_command", userName: "admin@example.com", userId: 42, ...(serverId === undefined ? {} : { serverId }) },
|
|
});
|
|
|
|
test("re-auth: a replacement account cannot adopt a schedule even with sufficient server permissions", async () => {
|
|
const h = makeStillAuthorized({ findServerImpl: { row: { id: 7, name: "srv01" } }, accessNames: ["srv01"], perms: { console_write: true }, user: { id: 43, admin: true } });
|
|
await assert.rejects(() => h.ensureScheduledJobStillAuthorized(AUTHZ_JOB(7)), /creator no longer exists/);
|
|
assert.deepStrictEqual(h.disabled, ["user no longer exists"]);
|
|
});
|
|
|
|
test("re-auth: an email-only legacy schedule cannot establish creator identity", async () => {
|
|
const h = makeStillAuthorized({ findServerImpl: { row: { id: 7, name: "srv01" } }, accessNames: ["srv01"], perms: { console_write: true } });
|
|
const job = AUTHZ_JOB(7);
|
|
delete job.data.userId;
|
|
await assert.rejects(() => h.ensureScheduledJobStillAuthorized(job), /has no associated user/);
|
|
assert.deepStrictEqual(h.disabled, ["missing creator identity"]);
|
|
});
|
|
|
|
test("re-auth: an admin-creator schedule whose stored serverId no longer matches the resolved row takes the unauthorized outcome (the admin all-true projection cannot mask it)", async () => {
|
|
const h = makeStillAuthorized({
|
|
findServerImpl: { row: { id: 8, name: "srv01" } }, // same-name recreate: new row
|
|
user: { admin: true, suspended: false }, // admins pass every access check unconditionally
|
|
});
|
|
await assert.rejects(
|
|
() => h.ensureScheduledJobStillAuthorized(AUTHZ_JOB(7)),
|
|
/stored server identity does not match/
|
|
);
|
|
assert.deepStrictEqual(h.disabled, ["scheduled server identity mismatch (same-name recreate)"], "the mismatch must ride the ONE disable machinery, exactly like an access revoke");
|
|
});
|
|
|
|
test("re-auth: an unbound legacy job is refused before the boot sweep can run", async () => {
|
|
const h = makeStillAuthorized({
|
|
findServerImpl: { row: { id: 8, name: "srv01" } },
|
|
accessNames: ["srv01"],
|
|
perms: { console_write: true },
|
|
user: { admin: false, suspended: false },
|
|
disableImpl: async () => true,
|
|
});
|
|
await assert.rejects(h.ensureScheduledJobStillAuthorized(AUTHZ_JOB(undefined)), /no bound server identity/);
|
|
assert.deepStrictEqual(h.disabled, ["missing server identity"]);
|
|
});
|
|
|
|
test("re-auth: a matching stored serverId passes and returns the resolved row for the caller's execution-context binding", async () => {
|
|
const row = { id: 7, name: "srv01" };
|
|
const h = makeStillAuthorized({
|
|
findServerImpl: { row },
|
|
accessNames: ["srv01"],
|
|
perms: { console_write: true },
|
|
user: { admin: false, suspended: false },
|
|
disableImpl: async () => true,
|
|
});
|
|
const entry = await h.ensureScheduledJobStillAuthorized(AUTHZ_JOB(7));
|
|
assert.strictEqual(entry, row, "the caller must receive the same row object the check decided on");
|
|
});
|
|
|
|
test("re-auth: an UNRESOLVED server with a stored serverId is NOT a mismatch (the server-deleted self-heal owns that path; a transient lookup failure must not disable)", async () => {
|
|
const disabled = [];
|
|
const h = makeStillAuthorized({
|
|
findServerImpl: { row: null },
|
|
accessNames: ["srv01"], // the raw-name fallback the canonical-authz twin defines
|
|
perms: { console_write: true },
|
|
user: { admin: false, suspended: false },
|
|
disableImpl: async (_job, reason) => { disabled.push(reason); return true; },
|
|
});
|
|
const entry = await h.ensureScheduledJobStillAuthorized(AUTHZ_JOB(7));
|
|
assert.strictEqual(entry, null);
|
|
assert.deepStrictEqual(disabled, [], "an unresolved row proves no identity mismatch — nothing may be disabled here");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// adpanel:scheduler-server-identity-bind — same-row legacy_id backfill vs
|
|
// same-name recreate at re-auth. The create route stores the composed id
|
|
// (numeric N on a panel-created row born legacy_id = NULL); routine index
|
|
// writers backfill legacy_id = String(the row's OWN composed id) onto the
|
|
// SAME living row on ordinary lifecycle writes, flipping the resolved
|
|
// composed id to the string "N". The stored-vs-resolved comparison therefore
|
|
// coerces both sides to String: a backfill must authorize, a legacy_id-born
|
|
// row must authorize, and a true recreate (different AUTO_INCREMENT id M,
|
|
// whose composed form is "M") must still take the mismatch outcome.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("re-auth: a same-row legacy_id backfill (stored numeric id, resolved composed string id) must NOT disable — it is not a recreate", async () => {
|
|
const h = makeStillAuthorized({
|
|
// SAME row 7 after its first lifecycle write backfilled legacy_id:
|
|
// mapServerRow now composes the id as the STRING "7".
|
|
findServerImpl: { row: { id: "7", legacy_id: "7", name: "srv01" } },
|
|
accessNames: ["srv01"],
|
|
perms: { console_write: true },
|
|
user: { admin: false, suspended: false },
|
|
disableImpl: async () => true,
|
|
});
|
|
const entry = await h.ensureScheduledJobStillAuthorized(AUTHZ_JOB(7));
|
|
assert.strictEqual(entry.id, "7", "the schedule stays bound to the same living row");
|
|
assert.deepStrictEqual(h.disabled, [], "the NULL -> String(N) backfill on the same row must never read as a same-name recreate");
|
|
});
|
|
|
|
test("re-auth: a legacy_id-born row (stored string id, resolved the same string id) passes", async () => {
|
|
const h = makeStillAuthorized({
|
|
findServerImpl: { row: { id: "XYZ", legacy_id: "XYZ", name: "srv01" } },
|
|
accessNames: ["srv01"],
|
|
perms: { console_write: true },
|
|
user: { admin: false, suspended: false },
|
|
disableImpl: async () => true,
|
|
});
|
|
const entry = await h.ensureScheduledJobStillAuthorized(AUTHZ_JOB("XYZ"));
|
|
assert.strictEqual(entry.id, "XYZ");
|
|
assert.deepStrictEqual(h.disabled, []);
|
|
});
|
|
|
|
test("re-auth: a TRUE recreate still disables when the new row's composed id is its backfilled string (stored 7 vs composed \"8\")", async () => {
|
|
const h = makeStillAuthorized({
|
|
// Recreate: AUTO_INCREMENT id 8, then its own first lifecycle write
|
|
// backfilled legacy_id = "8". String("8") !== String(7): mismatch stands.
|
|
findServerImpl: { row: { id: "8", legacy_id: "8", name: "srv01" } },
|
|
user: { admin: true, suspended: false }, // the admin projection must not mask the mismatch
|
|
});
|
|
await assert.rejects(
|
|
() => h.ensureScheduledJobStillAuthorized(AUTHZ_JOB(7)),
|
|
/stored server identity does not match/
|
|
);
|
|
assert.deepStrictEqual(h.disabled, ["scheduled server identity mismatch (same-name recreate)"]);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// adpanel:scheduler-agent-enqueue-identity — the two agent fire cases
|
|
// (planner_next_to_agent / agent_prompt) hold no daemon-dial ctx, so their
|
|
// enqueue gates (queueSchedulerPlannerNextToAgent / queueSchedulerPromptTo
|
|
// Agent — the ONLY callers of both helpers) now enforce the same stored-
|
|
// serverId + authz-row comparison the six dial cases get from the ctx
|
|
// helper, through the ONE shared comparison core
|
|
// (schedulerServerIdentityMismatch). A gate mismatch fails THIS fire with
|
|
// the identity reason and enqueues NOTHING; the disable belongs to the NEXT
|
|
// fire's authz-time bind (the stored arm is always populated post
|
|
// adpanel:scheduler-legacy-identity-sweep), so the gate deliberately throws
|
|
// WITHOUT the disable machinery. These tests drive the REAL sliced gates
|
|
// bound to the REAL sliced core.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// Full-body slice of a top-level function (declaration line -> its column-0
|
|
// closing brace), the same window the other enqueue tests use.
|
|
function fullFunctionWindow(source, anchor, label) {
|
|
const start = source.indexOf(anchor);
|
|
assert.ok(start >= 0, `${label}: anchor not found: ${anchor}`);
|
|
const end = source.indexOf("\n}", start);
|
|
assert.ok(end > start, `${label}: no closing brace after: ${anchor}`);
|
|
return source.slice(start, end + 2);
|
|
}
|
|
|
|
// The REAL ctx helper + shared comparison core, sliced together (the core
|
|
// lives between the helper and the next comment anchor in index.js, so every
|
|
// existing slice window stays self-contained) and evaluated with a no-op
|
|
// disable stub.
|
|
const makeIdentityScope = (disableImpl) => new Function(
|
|
"disableRecurringScheduleForJob",
|
|
sliceFrom(
|
|
indexSource,
|
|
"async function ensureSchedulerFireServerIdentity(",
|
|
"\n// adpanel:planner-access-job-retract",
|
|
"identity scope (ctx helper + shared comparison core)"
|
|
) + "\nreturn { ensureSchedulerFireServerIdentity, schedulerServerIdentityMismatch };"
|
|
)(disableImpl);
|
|
|
|
const { schedulerServerIdentityMismatch: realIdentityCore } = makeIdentityScope(async () => true);
|
|
|
|
const plannerGateSource = fullFunctionWindow(indexSource, "async function queueSchedulerPlannerNextToAgent", "planner enqueue gate slice");
|
|
const promptGateSource = fullFunctionWindow(indexSource, "async function queueSchedulerPromptToAgent", "agent_prompt enqueue gate slice");
|
|
|
|
// Drives the REAL sliced queueSchedulerPlannerNextToAgent with fakes for its
|
|
// dependency surface. findServerRow is the enqueue gate's own resolution;
|
|
// storedServerId / authzRow are the fire context threaded through the new
|
|
// options (job / authzServerEntry). nextItem overrides the top-item read
|
|
// (null = idle board, adpanel:planner-idle-fire-skip); insertError makes the
|
|
// job INSERT fail (a genuine enqueue failure).
|
|
const makePlannerGateRunner = ({ findServerRow, storedServerId, authzRow, job, access = true, admin = false, activeJob = null, nextItem, insertError = null } = {}) => {
|
|
const inserted = [];
|
|
const pumped = [];
|
|
const connCalls = [];
|
|
const conn = {
|
|
beginTransaction: async () => { connCalls.push("begin"); },
|
|
execute: async () => { connCalls.push("range-lock"); },
|
|
commit: async () => { connCalls.push("commit"); },
|
|
rollback: async () => { connCalls.push("rollback"); },
|
|
release: () => { connCalls.push("release"); },
|
|
};
|
|
const queueSchedulerPlannerNextToAgent = new Function(
|
|
"resolveSchedulerAgentUser", "userCanUseAdpanelAgent", "findServer", "userHasAccessToServer",
|
|
"schedulerServerIdentityMismatch", "db", "getNextActivePlannerItem", "plannerItemHasActiveAgentJob",
|
|
"normalizeAiModelSelectionPayload", "assertAiProviderReady", "buildPlannerAgentPrompt",
|
|
"getEffectivePermsForUserOnServer", "buildPlannerItemFilePermEnvelope", "insertAiAgentChatJob", "enqueueAiAgentJob",
|
|
plannerGateSource + "\nreturn queueSchedulerPlannerNextToAgent;"
|
|
)(
|
|
async () => ({ id: 42, email: "creator@example.com", admin, suspended: false }),
|
|
() => true,
|
|
async () => findServerRow,
|
|
async () => access,
|
|
realIdentityCore,
|
|
{ pool: { getConnection: async () => conn } },
|
|
nextItem === undefined
|
|
? async () => ({ id: 9, title: "Task", prompt: "Do the thing", prompt_author_id: 43 })
|
|
: async () => nextItem,
|
|
async () => activeJob,
|
|
(p) => ({ provider: p?.provider ?? null, model: p?.model ?? null }),
|
|
(provider, model) => ({ provider, model }),
|
|
(item, name) => `planner prompt for ${name}`,
|
|
async () => ({ files_read: true }),
|
|
async ({ authorId }) => authorId ? { files_read: true, author_id: authorId } : null,
|
|
async (opts) => {
|
|
if (insertError) throw insertError;
|
|
inserted.push(opts);
|
|
return { jobId: 101, chatId: 7 };
|
|
},
|
|
(id) => { pumped.push(id); },
|
|
);
|
|
return {
|
|
run: () => queueSchedulerPlannerNextToAgent({
|
|
serverName: "srv01",
|
|
payload: { provider: "openai", model: "gpt-x" },
|
|
userId: 42,
|
|
userName: "creator@example.com",
|
|
job: job === undefined
|
|
? { id: "job-planner-1", data: { serverName: "srv01", ...(storedServerId === undefined ? {} : { serverId: storedServerId }) } }
|
|
: job,
|
|
authzServerEntry: authzRow,
|
|
}),
|
|
inserted, pumped, connCalls,
|
|
};
|
|
};
|
|
|
|
// The agent_prompt sibling, same shape (no transaction — its insert runs
|
|
// directly).
|
|
const makePromptGateRunner = ({ findServerRow, storedServerId, authzRow, job, access = true, admin = false } = {}) => {
|
|
const inserted = [];
|
|
const queueSchedulerPromptToAgent = new Function(
|
|
"resolveSchedulerAgentUser", "userCanUseAdpanelAgent", "findServer", "userHasAccessToServer",
|
|
"schedulerServerIdentityMismatch", "normalizeAiModelSelectionPayload", "sanitizeAiAgentPrompt",
|
|
"assertAiProviderReady", "insertAiAgentChatJob", "deriveAiAgentChatTitle",
|
|
promptGateSource + "\nreturn queueSchedulerPromptToAgent;"
|
|
)(
|
|
async () => ({ id: 42, email: "creator@example.com", admin, suspended: false }),
|
|
() => true,
|
|
async () => findServerRow,
|
|
async () => access,
|
|
realIdentityCore,
|
|
(p) => ({ provider: p?.provider ?? null, model: p?.model ?? null }),
|
|
(p) => String(p || ""),
|
|
(provider, model) => ({ provider, model }),
|
|
async (opts) => { inserted.push(opts); return { jobId: 202, chatId: 8 }; },
|
|
(p, fallback) => fallback,
|
|
);
|
|
return {
|
|
run: () => queueSchedulerPromptToAgent({
|
|
serverName: "srv01",
|
|
payload: { prompt: "hello world", provider: "openai", model: "gpt-x" },
|
|
userId: 42,
|
|
userName: "creator@example.com",
|
|
job: job === undefined
|
|
? { id: "job-prompt-1", data: { serverName: "srv01", ...(storedServerId === undefined ? {} : { serverId: storedServerId }) } }
|
|
: job,
|
|
authzServerEntry: authzRow,
|
|
}),
|
|
inserted,
|
|
};
|
|
};
|
|
|
|
test("enqueue gate (planner): a gate row that differs from the STORED serverId fails the fire with the identity reason and enqueues NOTHING", async () => {
|
|
// Same-name recreate between the fire's authz lookup and the enqueue gate's
|
|
// findServer: the gate resolved the recreated row (id 8); the schedule is
|
|
// bound to 7.
|
|
const h = makePlannerGateRunner({ findServerRow: { id: 8, name: "srv01" }, storedServerId: 7, authzRow: { id: 8, name: "srv01" } });
|
|
await assert.rejects(() => h.run(), /different server row/);
|
|
assert.strictEqual(h.inserted.length, 0, "no agent job may be enqueued on a recreated row");
|
|
assert.strictEqual(h.pumped.length, 0, "no queue pump may run for an identity-refused fire");
|
|
assert.strictEqual(h.connCalls.length, 0, "the mismatch must abort before the fire's transaction even begins");
|
|
});
|
|
|
|
test("enqueue gate (planner): a matching row enqueues under the fire's identity", async () => {
|
|
const h = makePlannerGateRunner({ findServerRow: { id: 7, name: "srv01" }, storedServerId: 7, authzRow: { id: 7, name: "srv01" } });
|
|
const result = await h.run();
|
|
assert.strictEqual(result.jobId, 101);
|
|
assert.strictEqual(result.itemId, 9);
|
|
assert.strictEqual(result.serverName, "srv01");
|
|
assert.strictEqual(h.inserted.length, 1);
|
|
assert.ok(h.connCalls.includes("commit"), "the separate worker only sees committed jobs");
|
|
assert.deepStrictEqual(h.pumped, [], "scheduled admission never starts a web consumer");
|
|
assert.deepStrictEqual(
|
|
h.inserted[0].serverEntry,
|
|
{ id: 7, name: "srv01" },
|
|
"the gate-verified row must ride into the insert (serverEntry option) — the server_id stamp is THIS row, never a second resolution (adpanel:ai-job-stamp-single-resolution)"
|
|
);
|
|
});
|
|
|
|
test("enqueue gate (planner): a gate row that differs from the AUTHZ row fails even when the stored arm matches", async () => {
|
|
// The authz arm is independent of the stored arm (the ctx helper's "runs
|
|
// for EVERY job" parity): authz resolved row 7, the gate resolved row 8.
|
|
const h = makePlannerGateRunner({ findServerRow: { id: 8, name: "srv01" }, storedServerId: 8, authzRow: { id: 7, name: "srv01" } });
|
|
await assert.rejects(() => h.run(), /different server row/);
|
|
assert.strictEqual(h.inserted.length, 0);
|
|
});
|
|
|
|
test("enqueue gate (planner): a job with NO stored serverId is still bound by the authz-row arm (undefined-skip stays; the authz arm covers it)", async () => {
|
|
const h = makePlannerGateRunner({ findServerRow: { id: 8, name: "srv01" }, storedServerId: undefined, authzRow: { id: 7, name: "srv01" } });
|
|
await assert.rejects(() => h.run(), /different server row/);
|
|
assert.strictEqual(h.inserted.length, 0);
|
|
});
|
|
|
|
test("enqueue gate (planner): the SAME row's legacy_id backfill (stored numeric id, gate resolves the composed string id) must NOT block the enqueue", async () => {
|
|
// The exact backfill regression the bind doctrine documents: stored 7
|
|
// (numeric), the gate's row backfilled legacy_id = "7" — String coercion
|
|
// must authorize.
|
|
const h = makePlannerGateRunner({ findServerRow: { id: "7", legacy_id: "7", name: "srv01" }, storedServerId: 7, authzRow: { id: "7", name: "srv01" } });
|
|
const result = await h.run();
|
|
assert.strictEqual(result.jobId, 101);
|
|
assert.strictEqual(h.inserted.length, 1);
|
|
});
|
|
|
|
test("enqueue gate (planner): a job-less caller (no schedule context) skips the identity check entirely", async () => {
|
|
// Byte-identical behavior for a non-fire caller: gate row 8 vs authz row 7
|
|
// would fail a fire, but with no job there is no schedule context to bind.
|
|
const h = makePlannerGateRunner({ findServerRow: { id: 8, name: "srv01" }, authzRow: { id: 7, name: "srv01" }, job: null });
|
|
const result = await h.run();
|
|
assert.strictEqual(result.jobId, 101);
|
|
assert.strictEqual(h.inserted.length, 1);
|
|
});
|
|
|
|
test("enqueue gate (planner): an UNRESOLVED gate row is not a mismatch (the canonical-authz raw-name fallback owns that path)", async () => {
|
|
const h = makePlannerGateRunner({ findServerRow: null, storedServerId: 7, authzRow: { id: 7, name: "srv01" } });
|
|
const result = await h.run();
|
|
assert.strictEqual(result.jobId, 101);
|
|
assert.strictEqual(h.inserted.length, 1);
|
|
assert.strictEqual(
|
|
h.inserted[0].serverEntry,
|
|
null,
|
|
"an unresolved gate row passes null — the insert keeps its internal resolution (the documented fallback, byte-identical)"
|
|
);
|
|
});
|
|
|
|
// adpanel:planner-idle-fire-skip — an empty planner board is the poller-shaped
|
|
// schedule's normal steady state, not a failure. Returning the dedupe path's
|
|
// skip shape (instead of throwing the "no active planner prompt found" 404)
|
|
// keeps the fire out of the worker's failure-streak catch: no streak tick, and
|
|
// the worker's "completed" handler resets any existing streak exactly like it
|
|
// does for a deduped fire — a skipped fire is a successful no-op run (the
|
|
// streak counts CONSECUTIVE failures only), so the recurrence stays armed
|
|
// instead of self-destructing after 20 idle fires.
|
|
test("enqueue gate (planner): an IDLE board is a clean skip — dedupe skip shape, no enqueue, no pump, transaction rolled back and released", async () => {
|
|
const h = makePlannerGateRunner({ findServerRow: { id: 7, name: "srv01" }, storedServerId: 7, authzRow: { id: 7, name: "srv01" }, nextItem: null });
|
|
const result = await h.run();
|
|
assert.deepStrictEqual(
|
|
result,
|
|
{ success: true, skipped: true, reason: "no_active_planner_item", serverName: "srv01" },
|
|
"the idle-board skip must return the dedupe path's success+skipped shape (no jobId — nothing was enqueued)"
|
|
);
|
|
assert.strictEqual(h.inserted.length, 0, "an idle board must enqueue nothing");
|
|
assert.strictEqual(h.pumped.length, 0, "no queue pump may run for a skipped fire");
|
|
assert.ok(!h.connCalls.includes("commit"), "a skipped fire must not commit its read-only transaction");
|
|
assert.strictEqual(h.connCalls.indexOf("rollback"), h.connCalls.length - 2, "the skip must roll back (after the range lock, before release)");
|
|
assert.strictEqual(h.connCalls[h.connCalls.length - 1], "release", "the connection must be released");
|
|
});
|
|
|
|
test("enqueue gate (planner): an unverified legacy author skips without creating a job", async () => {
|
|
const server = { id: 7, name: "srv01" };
|
|
const h = makePlannerGateRunner({
|
|
findServerRow: server, storedServerId: server.id, authzRow: server,
|
|
nextItem: { id: 9, title: "Task", prompt: "Review this item.", prompt_author_id: null },
|
|
});
|
|
assert.deepStrictEqual(await h.run(), {
|
|
success: true, skipped: true, reason: "planner_author_unverified", itemId: 9, serverName: "srv01",
|
|
});
|
|
assert.deepStrictEqual(h.inserted, []);
|
|
assert.deepStrictEqual(h.pumped, []);
|
|
assert.deepStrictEqual(h.connCalls, ["begin", "range-lock", "rollback", "release"]);
|
|
});
|
|
|
|
// A genuine enqueue failure (DB down, insert error) must keep throwing —
|
|
// the worker's catch then ticks the failure streak exactly as before.
|
|
test("enqueue gate (planner): a GENUINE enqueue failure still throws into the worker's failure-streak catch", async () => {
|
|
const h = makePlannerGateRunner({ findServerRow: { id: 7, name: "srv01" }, storedServerId: 7, authzRow: { id: 7, name: "srv01" }, insertError: new Error("db down") });
|
|
await assert.rejects(() => h.run(), /db down/);
|
|
assert.strictEqual(h.inserted.length, 0);
|
|
assert.strictEqual(h.pumped.length, 0, "a failed enqueue must never pump the queue");
|
|
assert.ok(h.connCalls.includes("rollback"), "the failed transaction must roll back");
|
|
assert.ok(!h.connCalls.includes("commit"), "the failed transaction must not commit");
|
|
});
|
|
|
|
test("adpanel:planner-idle-fire-skip wiring: the fire case's shared 'queued' log line is guarded on jobId and the skip rides the success path the streak resets on", () => {
|
|
const plannerCase = indexSource.slice(
|
|
indexSource.indexOf('case "planner_next_to_agent": {'),
|
|
indexSource.indexOf('case "agent_prompt": {')
|
|
);
|
|
assert.ok(
|
|
plannerCase.includes("if (result.jobId && !result.skipped) {"),
|
|
"only a new enqueue with a job id may be logged as queued"
|
|
);
|
|
assert.ok(
|
|
plannerCase.includes('return { success: true, action: "planner_next_to_agent", ...result };'),
|
|
"a skipped fire returns success so the worker's completed handler — the streak reset signal — fires for it, exactly like a deduped fire"
|
|
);
|
|
});
|
|
|
|
test("enqueue gate (agent_prompt): a gate row that differs from the STORED serverId fails the fire and inserts NOTHING", async () => {
|
|
const h = makePromptGateRunner({ findServerRow: { id: 8, name: "srv01" }, storedServerId: 7, authzRow: { id: 8, name: "srv01" } });
|
|
await assert.rejects(() => h.run(), /different server row/);
|
|
assert.strictEqual(h.inserted.length, 0, "no agent job row may be inserted on a recreated server");
|
|
});
|
|
|
|
test("enqueue gate (agent_prompt): a matching row inserts and returns the stored server name", async () => {
|
|
const h = makePromptGateRunner({ findServerRow: { id: 7, name: "srv01" }, storedServerId: 7, authzRow: { id: 7, name: "srv01" } });
|
|
const result = await h.run();
|
|
assert.strictEqual(result.jobId, 202);
|
|
assert.strictEqual(result.serverName, "srv01");
|
|
assert.strictEqual(h.inserted.length, 1);
|
|
assert.deepStrictEqual(
|
|
h.inserted[0].serverEntry,
|
|
{ id: 7, name: "srv01" },
|
|
"the gate-verified row must ride into the insert (serverEntry option) — the server_id stamp is THIS row, never a second resolution (adpanel:ai-job-stamp-single-resolution)"
|
|
);
|
|
});
|
|
|
|
test("enqueue gate (agent_prompt): a gate row that differs from the AUTHZ row fails the fire", async () => {
|
|
const h = makePromptGateRunner({ findServerRow: { id: 8, name: "srv01" }, storedServerId: undefined, authzRow: { id: 7, name: "srv01" } });
|
|
await assert.rejects(() => h.run(), /different server row/);
|
|
assert.strictEqual(h.inserted.length, 0);
|
|
});
|
|
|
|
test("enqueue gate (agent_prompt): a job-less caller skips the identity check entirely", async () => {
|
|
const h = makePromptGateRunner({ findServerRow: { id: 8, name: "srv01" }, authzRow: { id: 7, name: "srv01" }, job: null });
|
|
const result = await h.run();
|
|
assert.strictEqual(result.jobId, 202);
|
|
assert.strictEqual(h.inserted.length, 1);
|
|
});
|
|
|
|
// Wiring pins for the threading: both gates must decide through the ONE
|
|
// shared core (no re-implemented comparison), both worker fire cases must
|
|
// pass the bind context, and the six dial cases' ctx-helper calls must be
|
|
// untouched by the refactor.
|
|
test("adpanel:scheduler-agent-enqueue-identity wiring: gates call the shared core, fire cases thread job + authz row, the six dial calls stay intact", () => {
|
|
assert.ok(
|
|
plannerGateSource.includes("schedulerServerIdentityMismatch(enqueueServerEntry.id, authzServerEntry, job?.data?.serverId)"),
|
|
"the planner gate must decide through the ONE shared comparison core"
|
|
);
|
|
assert.ok(
|
|
promptGateSource.includes("schedulerServerIdentityMismatch(serverEntry.id, authzServerEntry, job?.data?.serverId)"),
|
|
"the agent_prompt gate must decide through the ONE shared comparison core"
|
|
);
|
|
const plannerCase = indexSource.slice(
|
|
indexSource.indexOf('case "planner_next_to_agent": {'),
|
|
indexSource.indexOf('case "agent_prompt": {')
|
|
);
|
|
const promptCase = indexSource.slice(
|
|
indexSource.indexOf('case "agent_prompt": {'),
|
|
indexSource.indexOf("\n default:")
|
|
);
|
|
assert.ok(
|
|
plannerCase.includes("queueSchedulerPlannerNextToAgent({ serverName, payload, userId, userName, job, authzServerEntry: schedulerAuthzServerEntry })"),
|
|
"the planner fire case must thread the bind context (job + the authorization row this fire decided on)"
|
|
);
|
|
assert.ok(
|
|
promptCase.includes("queueSchedulerPromptToAgent({ serverName, payload, userId, userName, job, authzServerEntry: schedulerAuthzServerEntry })"),
|
|
"the agent_prompt fire case must thread the bind context (job + the authorization row this fire decided on)"
|
|
);
|
|
assert.strictEqual(
|
|
(indexSource.match(/await ensureSchedulerFireServerIdentity\(job, ctx, schedulerAuthzServerEntry\);/g) || []).length,
|
|
6,
|
|
"the six daemon-dial cases' ctx-helper identity calls must remain exactly as they were"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Follow-up (verification round 2026-10-24): disableRecurringScheduleForJob
|
|
// used to fall through to a (serverName, actionType, name) signature match
|
|
// even for plain ONE-SHOT jobs (no repeat identity), so a failing legacy
|
|
// one-shot sharing a name with a healthy recurring task would delete that
|
|
// innocent schedule. The fix: a job with no repeatJobKey and no opts.repeat
|
|
// owns no recurring schedule — return without scanning. The signature
|
|
// fallback stays available for genuinely repeatable jobs whose key could
|
|
// not be resolved (older BullMQ shapes with opts.repeat but no key).
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// The slice closes over index.js's module-level schedulerQueue, so the stub
|
|
// queue is injected as that binding; the returned function takes (job, reason).
|
|
// adpanel:scheduler-failure-streak — the disable machinery also clears the
|
|
// failure-streak counter per removal, so the harness injects the scheduler
|
|
// state client (null: every consumer no-ops like a Redis outage) and a
|
|
// recording reset stub. The slice window also CONTAINS the inert
|
|
// recordSchedulerFailureStreak (declared between the disable machinery and
|
|
// the next anchor) — its out-of-window identifiers are bound below so a
|
|
// future test can drive the streak path through this harness without a
|
|
// ReferenceError; these tests never call it.
|
|
const makeDisabler = (queue, resets) => new Function(
|
|
"schedulerQueue",
|
|
"schedulerStateRedis",
|
|
"resetSchedulerFailureStreak",
|
|
"bumpSchedulerFailureStreak",
|
|
"SCHEDULER_MAX_CONSECUTIVE_FAILURES",
|
|
"DEFAULT_STREAK_TTL_SECONDS",
|
|
"raceWithDeadline",
|
|
sliceFrom(
|
|
indexSource,
|
|
"async function disableRecurringScheduleForJob(job, reason) {",
|
|
"\n// Re-validates, at execution time",
|
|
"disableRecurringScheduleForJob"
|
|
) + "\nreturn disableRecurringScheduleForJob;"
|
|
)(
|
|
queue,
|
|
null,
|
|
async (_client, repeatKey) => { if (resets) resets.push(repeatKey); },
|
|
async () => ({ tracked: false, count: 0, shouldDisable: false }),
|
|
20,
|
|
45 * 24 * 60 * 60,
|
|
(promise, _ms, fallback) => Promise.resolve(promise).catch(() => fallback)
|
|
);
|
|
|
|
function makeQueueStub(repeatables) {
|
|
const removed = [];
|
|
return {
|
|
removed,
|
|
getRepeatableJobs: async () => repeatables,
|
|
removeRepeatableByKey: async (key) => removed.push(key),
|
|
};
|
|
}
|
|
|
|
const SIGNATURE_REPEATABLE = {
|
|
key: "rk1",
|
|
name: JSON.stringify({ serverName: "srv01", actionType: "console_command", name: "Nightly restart", payload: { command: "stop" } }),
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Round-3 follow-up (final wired review): the hook's end-to-end chain
|
|
// (bump → threshold → disable → conditional reset) had no behavioral
|
|
// coverage — the makeDisabler harness binds the identifiers but never CALLS
|
|
// recordSchedulerFailureStreak. Drive the REAL hook, extracted from the same
|
|
// slice, against a Map-fake Redis through all three removal outcomes.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function makeHookHarness(removeImpl) {
|
|
const store = new Map();
|
|
const redis = {
|
|
async incr(key) { store.set(key, (store.get(key) || 0) + 1); return store.get(key); },
|
|
async expire(key, seconds) { if (store.has(key)) store.set(`${key}\u0000ttl`, seconds); return 1; },
|
|
async del(key) { store.delete(key); store.delete(`${key}\u0000ttl`); return 1; },
|
|
};
|
|
const hook = new Function(
|
|
"schedulerQueue", "schedulerStateRedis", "resetSchedulerFailureStreak",
|
|
"bumpSchedulerFailureStreak", "SCHEDULER_MAX_CONSECUTIVE_FAILURES",
|
|
"DEFAULT_STREAK_TTL_SECONDS", "raceWithDeadline",
|
|
sliceFrom(
|
|
indexSource,
|
|
"async function disableRecurringScheduleForJob(job, reason) {",
|
|
"\n// Re-validates, at execution time",
|
|
"streak hook slice"
|
|
) + "\nreturn recordSchedulerFailureStreak;"
|
|
)(
|
|
{ removeRepeatableByKey: removeImpl },
|
|
redis,
|
|
realStreak.resetSchedulerFailureStreak,
|
|
realStreak.bumpSchedulerFailureStreak,
|
|
20,
|
|
realStreak.DEFAULT_STREAK_TTL_SECONDS,
|
|
realStreak.raceWithDeadline
|
|
);
|
|
const job = {
|
|
id: "job-1",
|
|
opts: { repeat: { every: 60000 } },
|
|
repeatJobKey: "rk-x",
|
|
name: JSON.stringify({ serverName: "srv01", actionType: "console_command", name: "T", userName: "u@example.com" }),
|
|
data: { serverName: "srv01", actionType: "console_command", name: "T", userName: "u@example.com" },
|
|
};
|
|
const counterKey = realStreak.schedulerFailureStreakKey("rk-x");
|
|
return { hook, job, store, counterKey };
|
|
}
|
|
|
|
test("the failure-streak hook end-to-end: threshold disable fires, and the counter's fate follows the removal outcome", async () => {
|
|
const err = new Error("daemon 404");
|
|
// 19 failures: the fuse is live, nothing disabled yet.
|
|
{
|
|
const h = makeHookHarness(async () => true);
|
|
for (let i = 0; i < 19; i += 1) await h.hook(h.job, err);
|
|
assert.strictEqual(h.store.get(h.counterKey), 19, "19 consecutive failures must count to 19 without disabling");
|
|
}
|
|
// 20th failure + successful removal: counter cleared (schedule gone).
|
|
{
|
|
const h = makeHookHarness(async () => true);
|
|
for (let i = 0; i < 20; i += 1) await h.hook(h.job, err);
|
|
assert.strictEqual(h.store.get(h.counterKey), undefined, "a successful disable must clear the counter");
|
|
}
|
|
// 20th failure + "already removed" (BullMQ false): counter STILL cleared —
|
|
// the machinery's unconditional post-attempt reset owns the orphan.
|
|
{
|
|
const h = makeHookHarness(async () => false);
|
|
for (let i = 0; i < 20; i += 1) await h.hook(h.job, err);
|
|
assert.strictEqual(h.store.get(h.counterKey), undefined, "an already-removed schedule's counter must still be cleared");
|
|
}
|
|
// 20th failure + removal THROWS: counter PRESERVED at the threshold — the
|
|
// live fuse survives so the next failing run re-fires the disable (the
|
|
// removedAny gating from the round-3 review).
|
|
{
|
|
const h = makeHookHarness(async () => { throw new Error("redis down"); });
|
|
for (let i = 0; i < 20; i += 1) await h.hook(h.job, err);
|
|
assert.strictEqual(h.store.get(h.counterKey), 20, "a failed removal must keep the live counter — wiping it would restart the disable cycle from zero");
|
|
}
|
|
});
|
|
|
|
test("a one-shot job with a matching signature removes NOTHING (no collateral deletion)", async () => {
|
|
const queue = makeQueueStub([SIGNATURE_REPEATABLE]);
|
|
const oneShot = {
|
|
id: "one-1",
|
|
data: { serverName: "srv01", actionType: "console_command", name: "Nightly restart" },
|
|
// no repeatJobKey, no opts.repeat — a plain one-time job
|
|
};
|
|
await makeDisabler(queue)(oneShot, "invalid stored console command");
|
|
assert.deepStrictEqual(queue.removed, [], "a failing one-shot must never delete another job's recurring schedule");
|
|
});
|
|
|
|
test("a job with repeatJobKey removes exactly its own repeatable", async () => {
|
|
const queue = makeQueueStub([
|
|
SIGNATURE_REPEATABLE,
|
|
{ key: "rk2", name: JSON.stringify({ serverName: "other", actionType: "backup", name: "x" }) },
|
|
]);
|
|
const resets = [];
|
|
const repeatJob = {
|
|
id: "rep-1",
|
|
repeatJobKey: "rk1",
|
|
data: { serverName: "srv01", actionType: "console_command", name: "Nightly restart" },
|
|
};
|
|
await makeDisabler(queue, resets)(repeatJob, "permission revoked");
|
|
assert.deepStrictEqual(queue.removed, ["rk1"]);
|
|
assert.deepStrictEqual(resets, ["rk1"], "the streak counter must die with the schedule on the exact-key path");
|
|
});
|
|
|
|
test("a job whose repeat key resolves NEVER falls through to the signature fallback (legacy co-user schedules are untouchable)", async () => {
|
|
// adpanel:scheduler-failure-streak-identity — the failure-streak hook is
|
|
// the first failure-driven caller of the disable machinery, i.e. the first
|
|
// one a co-user can aim: a same-named guaranteed-failing task next to a
|
|
// victim's LEGACY (no-creator) repeatable used to remove both, because the
|
|
// exact-key match fell through to the loose scan. The exact-key path must
|
|
// stop after its own key.
|
|
const queue = makeQueueStub([
|
|
{ key: "attacker-rk", name: JSON.stringify({ serverName: "srv01", actionType: "console_command", name: "Nightly restart", payloadHash: "h", userName: "attacker@example.com" }) },
|
|
{ key: "victim-legacy-rk", name: JSON.stringify({ serverName: "srv01", actionType: "console_command", name: "Nightly restart", payload: { command: "stop" } }) },
|
|
]);
|
|
const attackerJob = {
|
|
id: "rep-attacker",
|
|
repeatJobKey: "attacker-rk",
|
|
data: { serverName: "srv01", actionType: "console_command", name: "Nightly restart", userName: "attacker@example.com" },
|
|
};
|
|
await makeDisabler(queue)(attackerJob, "failed 20 consecutive runs (last error: x)");
|
|
assert.deepStrictEqual(queue.removed, ["attacker-rk"], "only the attacker's own repeatable may be removed — the legacy victim's schedule must survive");
|
|
});
|
|
|
|
test("the signature fallback still works for a repeatable job whose key could not be resolved", async () => {
|
|
const queue = makeQueueStub([SIGNATURE_REPEATABLE]);
|
|
const legacyRepeatJob = {
|
|
id: "rep-2",
|
|
opts: { repeat: { every: 30000 } }, // repeat present, no resolvable key
|
|
data: { serverName: "srv01", actionType: "console_command", name: "Nightly restart" },
|
|
};
|
|
await makeDisabler(queue)(legacyRepeatJob, "user suspended");
|
|
assert.deepStrictEqual(queue.removed, ["rk1"], "compat fallback must survive for genuinely repeatable jobs");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 2 — default schedule quota
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function evalQuotaSlice() {
|
|
return new Function(
|
|
sliceFrom(
|
|
indexSource,
|
|
"const SCHEDULER_DEFAULT_MAX_SCHEDULES = Math.max(1",
|
|
"\n// Maps a scheduler action to the per-server permission",
|
|
"quota slice"
|
|
) +
|
|
"\nreturn { SCHEDULER_DEFAULT_MAX_SCHEDULES, SCHEDULER_MAX_TASK_NAME_LENGTH, resolveSchedulerMaxSchedules };"
|
|
)();
|
|
}
|
|
|
|
test("an unconfigured server falls back to the default quota instead of unlimited", () => {
|
|
delete process.env.SCHEDULER_DEFAULT_MAX_SCHEDULES;
|
|
const q = evalQuotaSlice();
|
|
assert.strictEqual(q.SCHEDULER_DEFAULT_MAX_SCHEDULES, 50, "sane built-in default");
|
|
assert.strictEqual(q.resolveSchedulerMaxSchedules(null), 50);
|
|
assert.strictEqual(q.resolveSchedulerMaxSchedules({}), 50);
|
|
assert.strictEqual(q.resolveSchedulerMaxSchedules({ resources: {} }), 50);
|
|
});
|
|
|
|
test("a stored 0 or negative maxSchedules degrades to the default, never to unlimited", () => {
|
|
delete process.env.SCHEDULER_DEFAULT_MAX_SCHEDULES;
|
|
const { resolveSchedulerMaxSchedules, SCHEDULER_DEFAULT_MAX_SCHEDULES } = evalQuotaSlice();
|
|
// Stored 0 is ambiguous (admin update routes collapse "field left empty"
|
|
// and an explicit 0 into 0) — fail closed to the default.
|
|
assert.strictEqual(resolveSchedulerMaxSchedules({ resources: { maxSchedules: 0 } }), SCHEDULER_DEFAULT_MAX_SCHEDULES);
|
|
assert.strictEqual(resolveSchedulerMaxSchedules({ docker: { maxSchedules: 0 } }), SCHEDULER_DEFAULT_MAX_SCHEDULES);
|
|
assert.strictEqual(resolveSchedulerMaxSchedules({ resources: { maxSchedules: -5 } }), SCHEDULER_DEFAULT_MAX_SCHEDULES);
|
|
});
|
|
|
|
test("an explicitly configured positive maxSchedules always wins (resources, then docker)", () => {
|
|
delete process.env.SCHEDULER_DEFAULT_MAX_SCHEDULES;
|
|
const { resolveSchedulerMaxSchedules } = evalQuotaSlice();
|
|
assert.strictEqual(resolveSchedulerMaxSchedules({ resources: { maxSchedules: 3 } }), 3);
|
|
assert.strictEqual(resolveSchedulerMaxSchedules({ docker: { maxSchedules: 7 } }), 7);
|
|
assert.strictEqual(
|
|
resolveSchedulerMaxSchedules({ resources: { maxSchedules: 3 }, docker: { maxSchedules: 99 } }),
|
|
3,
|
|
"resources.maxSchedules takes precedence over docker.maxSchedules (legacy fallback order)"
|
|
);
|
|
});
|
|
|
|
test("SCHEDULER_DEFAULT_MAX_SCHEDULES env var overrides the built-in default", () => {
|
|
process.env.SCHEDULER_DEFAULT_MAX_SCHEDULES = "7";
|
|
const q7 = evalQuotaSlice();
|
|
delete process.env.SCHEDULER_DEFAULT_MAX_SCHEDULES;
|
|
assert.strictEqual(q7.SCHEDULER_DEFAULT_MAX_SCHEDULES, 7);
|
|
assert.strictEqual(q7.resolveSchedulerMaxSchedules({}), 7);
|
|
|
|
// Non-numeric / zero keep the built-in default; a negative clamps up to 1
|
|
// (most restrictive), never unlimited.
|
|
for (const [value, expected] of [["abc", 50], ["0", 50], ["-3", 1]]) {
|
|
process.env.SCHEDULER_DEFAULT_MAX_SCHEDULES = value;
|
|
const q = evalQuotaSlice();
|
|
delete process.env.SCHEDULER_DEFAULT_MAX_SCHEDULES;
|
|
assert.strictEqual(q.SCHEDULER_DEFAULT_MAX_SCHEDULES, expected, `env=${value}`);
|
|
}
|
|
});
|
|
|
|
test("the create route resolves the quota through the helper (no optional-cap bypass)", () => {
|
|
const route = createRouteSlice(indexCode);
|
|
assert.ok(
|
|
route.includes("resolveSchedulerMaxSchedules(serverEntry)"),
|
|
"the create route must use the resolver"
|
|
);
|
|
assert.ok(
|
|
!route.includes("if (maxSchedules && maxSchedules > 0)"),
|
|
"the quota check must no longer be conditional on admin configuration"
|
|
);
|
|
});
|
|
|
|
test("quota runs after request validation and the permission gate", () => {
|
|
const route = createRouteSlice(indexCode);
|
|
const quotaPos = route.indexOf("resolveSchedulerMaxSchedules(serverEntry)");
|
|
const gatePos = route.indexOf("const requiredPermission = schedulerRequiredPermissionForAction(actionType);");
|
|
const validActionsPos = route.indexOf("if (!validActions.includes(actionType))");
|
|
assert.ok(quotaPos > gatePos, "the quota's Redis roundtrips and count disclosure must come after the per-action permission gate");
|
|
assert.ok(quotaPos > validActionsPos, "malformed requests must be rejected before the quota scan");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 3 — create-time permission gate + name clamp
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const schedulerRequiredPermissionForAction = new Function(
|
|
sliceFrom(
|
|
indexSource,
|
|
"function schedulerRequiredPermissionForAction(actionType) {",
|
|
"\n// Disables a recurring schedule so it stops firing",
|
|
"schedulerRequiredPermissionForAction"
|
|
) + "\nreturn schedulerRequiredPermissionForAction;"
|
|
)();
|
|
|
|
test("every schedulable action maps to a required permission (no ungated action)", () => {
|
|
const expected = {
|
|
console_command: "console_write",
|
|
server_start: "server_start",
|
|
server_stop: "server_stop",
|
|
create_file: "files_create",
|
|
modify_file: "files_write",
|
|
backup: "backups_create",
|
|
planner_next_to_agent: "planner_access",
|
|
agent_prompt: "scheduler_access",
|
|
};
|
|
for (const [actionType, permission] of Object.entries(expected)) {
|
|
assert.strictEqual(schedulerRequiredPermissionForAction(actionType), permission, actionType);
|
|
}
|
|
// The create route's validActions list and the mapping must stay in sync:
|
|
// anything creatable must be gated.
|
|
const route = createRouteSlice(indexSource);
|
|
const validActionsMatch = route.match(/const validActions = \[([^\]]*)\]/);
|
|
assert.ok(validActionsMatch, "validActions list not found in create route");
|
|
const validActions = validActionsMatch[1].split(",").map((s) => s.trim().replace(/"/g, ""));
|
|
for (const actionType of validActions) {
|
|
assert.ok(
|
|
schedulerRequiredPermissionForAction(actionType),
|
|
`${actionType} is creatable but maps to no permission — the create-time gate would skip it`
|
|
);
|
|
}
|
|
assert.strictEqual(schedulerRequiredPermissionForAction("bogus"), null);
|
|
});
|
|
|
|
test("create route gates every action through the shared mapping (create-time/run-time parity)", () => {
|
|
const route = createRouteSlice(indexCode);
|
|
assert.ok(
|
|
route.includes("const requiredPermission = schedulerRequiredPermissionForAction(actionType);"),
|
|
"the create route must resolve the required permission from the shared mapping"
|
|
);
|
|
assert.ok(
|
|
route.includes("if (requiredPermission && !perms[requiredPermission])"),
|
|
"the gate must 403 when the creator lacks the action's execution permission"
|
|
);
|
|
assert.ok(
|
|
!route.includes("actionType === \"backup\" && !perms.backups_create"),
|
|
"the backup-specific gate must be superseded by the generic one"
|
|
);
|
|
});
|
|
|
|
test("create route clamps task names to the UI's 100-character limit", () => {
|
|
const route = createRouteSlice(indexCode);
|
|
assert.ok(route.includes("SCHEDULER_MAX_TASK_NAME_LENGTH"), "name clamp constant must be referenced");
|
|
assert.ok(
|
|
route.includes("rawTaskName.length > SCHEDULER_MAX_TASK_NAME_LENGTH"),
|
|
"an over-long name must be rejected"
|
|
);
|
|
const q = evalQuotaSlice();
|
|
assert.strictEqual(q.SCHEDULER_MAX_TASK_NAME_LENGTH, 100, "matches bot.ejs maxlength=\"100\"");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Finding 4 — GET /tasks no longer discloses payloads or return values
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function getRouteSlice(source) {
|
|
return sliceFrom(
|
|
source,
|
|
'app.get("/api/scheduler/:serverName/tasks"',
|
|
'app.post("/api/scheduler/:serverName/tasks"',
|
|
"scheduler get route"
|
|
);
|
|
}
|
|
|
|
test("GET /tasks response no longer contains payload or returnValue", () => {
|
|
const route = getRouteSlice(indexCode);
|
|
assert.ok(!route.includes("payload"), "no payload field may be emitted anywhere in the GET route");
|
|
assert.ok(!route.includes("returnValue"), "no returnValue field may be emitted (it echoes executed console commands)");
|
|
});
|
|
|
|
test("GET /tasks keeps the management fields the UI renders", () => {
|
|
const route = getRouteSlice(indexCode);
|
|
for (const field of ["id:", "name:", "actionType:", "scheduleType:", "status:", "failedReason:"]) {
|
|
assert.ok(route.includes(field), `field ${field} must survive the scrub`);
|
|
}
|
|
assert.ok(route.includes("cron: job.pattern"), "recurring entries keep their cron pattern");
|
|
assert.ok(route.includes("every: Number(job.every) || null"), "repeatables with an interval keep the BullMQ cadence in milliseconds");
|
|
assert.ok(route.includes("next: job.next"), "recurring entries keep their next-run time");
|
|
});
|
|
|
|
test("Scheduler lists the cadence for interval tasks and keeps cron patterns for calendar tasks", () => {
|
|
const botSource = fs.readFileSync(path.join(ROOT, "public", "js", "bot.js"), "utf8");
|
|
const renderSource = sliceFrom(botSource, "function renderSchedulerTasks(", "function getActionIcon(", "renderSchedulerTasks");
|
|
const list = { innerHTML: "", querySelectorAll: () => [] };
|
|
const render = new Function("schedulerTasksList", "hasPerm", "escapeHtml", "getActionIcon",
|
|
`${renderSource}\nreturn renderSchedulerTasks;`)(list, () => false, String, () => "");
|
|
render([], [
|
|
{ id: "interval", status: "recurring", every: 30_000, cron: null },
|
|
{ id: "calendar", status: "recurring", every: null, cron: "0 9 * * *" }
|
|
]);
|
|
assert.match(list.innerHTML, /Every 30 seconds/);
|
|
assert.match(list.innerHTML, /Cron: 0 9 \* \* \*/);
|
|
assert.doesNotMatch(list.innerHTML, /Cron: N\/A/);
|
|
});
|
|
|
|
test("the frontend never consumed the removed fields (bot.js renders metadata only)", () => {
|
|
const bot = fs.readFileSync(path.join(ROOT, "public", "js", "bot.js"), "utf8");
|
|
const renderFn = sliceFrom(bot, "function renderSchedulerTasks(", "function getActionIcon(", "renderSchedulerTasks");
|
|
for (const forbidden of ["task.payload", ".payload", "returnValue"]) {
|
|
assert.ok(!renderFn.includes(forbidden), `renderSchedulerTasks must not depend on ${forbidden}`);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// adpanel:scheduler-backup-starvation — the fleet-wide backup slot cap
|
|
//
|
|
// One BullMQ worker (concurrency 5) serves every server's schedules, and a
|
|
// `backup` fire awaits the daemon's full server copy for up to 630 s while
|
|
// holding a slot. The 300 s recurrence floor and the backup-count cap bound
|
|
// how many backups EXIST, not aggregate slot occupancy: five concurrent
|
|
// backup runs saturate all five slots and every other tenant's schedules
|
|
// stop executing. Fix: a fleet-wide in-flight cap (SCHEDULER_MAX_CONCURRENT_
|
|
// BACKUPS, default 2) and a deferral — job.moveToDelayed + DelayedError,
|
|
// which bullmq 5.78's handleFailed treats as "already moved" (no failure
|
|
// recorded, no attempt consumed) — with the gate running BEFORE the
|
|
// stall-guard run-claim so a deferral leaks no claim slot.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function evalBackupStarvationSlice(deferDeadlineMsOverride) {
|
|
// The REAL limiter block (resolver + constants + counter + acquire/release)
|
|
// and the REAL processor gate, sliced from source and evaluated with the
|
|
// real bullmq DelayedError and the real raceWithDeadline (the gate's
|
|
// adpanel:scheduler-defer-deadline race) — same technique as the quota
|
|
// slices above. deferDeadlineMsOverride rewrites the deadline constant's
|
|
// literal for tests that must not wait 5000ms.
|
|
let limiter = sliceFrom(
|
|
indexCode,
|
|
"function resolveSchedulerMaxConcurrentBackups",
|
|
"\nasync function initializeScheduler() {",
|
|
"backup starvation limiter slice"
|
|
);
|
|
if (deferDeadlineMsOverride !== undefined) {
|
|
const literal = "const SCHEDULER_BACKUP_DEFER_DEADLINE_MS = 5000;";
|
|
assert.ok(limiter.includes(literal), "the deferral deadline constant literal moved — update the override");
|
|
limiter = limiter.replace(literal, `const SCHEDULER_BACKUP_DEFER_DEADLINE_MS = ${deferDeadlineMsOverride};`);
|
|
}
|
|
const gate = sliceFrom(
|
|
indexCode,
|
|
"let schedulerBackupSlotHeld = false;",
|
|
"const runClaimKey",
|
|
"backup starvation gate slice"
|
|
);
|
|
return new Function(
|
|
"DelayedError",
|
|
"raceWithDeadline",
|
|
limiter +
|
|
'\nreturn { SCHEDULER_MAX_CONCURRENT_BACKUPS, SCHEDULER_BACKUP_DEFER_DELAY_MS, SCHEDULER_BACKUP_DEFER_DEADLINE_MS, acquireSchedulerBackupSlot, releaseSchedulerBackupSlot, gate: async (job, token) => { const { actionType } = job.data;\n' +
|
|
gate +
|
|
"\nreturn schedulerBackupSlotHeld; } };"
|
|
)(require("bullmq").DelayedError, realStreak.raceWithDeadline);
|
|
}
|
|
|
|
function makeBackupJobSpy(moveToDelayedImpl) {
|
|
const calls = { moved: [] };
|
|
const job = {
|
|
id: "bk-defer-1",
|
|
data: { actionType: "backup", serverName: "srv01" },
|
|
moveToDelayed: async (timestamp, token) => {
|
|
calls.moved.push({ timestamp, token });
|
|
if (moveToDelayedImpl) return moveToDelayedImpl(timestamp, token);
|
|
},
|
|
};
|
|
return { job, calls };
|
|
}
|
|
|
|
test("the backup slot resolver clamps like the sibling SCHEDULER_* resolvers", () => {
|
|
const saved = process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
try {
|
|
delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
let q = evalBackupStarvationSlice();
|
|
assert.strictEqual(q.SCHEDULER_MAX_CONCURRENT_BACKUPS, 2, "default cap 2 — two slots for backups, three keep serving everyone else");
|
|
assert.strictEqual(q.SCHEDULER_BACKUP_DEFER_DELAY_MS > 0, true, "the deferral re-check delay must be positive");
|
|
|
|
for (const [value, expected] of [["5", 5], ["99", 5], ["1", 1], ["0", 1], ["-3", 1], ["abc", 2], ["", 2]]) {
|
|
process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS = value;
|
|
q = evalBackupStarvationSlice();
|
|
assert.strictEqual(q.SCHEDULER_MAX_CONCURRENT_BACKUPS, expected, `env "${value}" must resolve to ${expected} (min 1, max 5 = worker concurrency)`);
|
|
}
|
|
} finally {
|
|
if (saved === undefined) delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
else process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS = saved;
|
|
}
|
|
});
|
|
|
|
test("an unsaturated cap acquires a slot and never defers", async () => {
|
|
const saved = process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
try {
|
|
const q = evalBackupStarvationSlice();
|
|
const { job, calls } = makeBackupJobSpy();
|
|
const held = await q.gate(job, "tok-1");
|
|
assert.strictEqual(held, true, "below the cap the fire proceeds holding a slot");
|
|
assert.strictEqual(calls.moved.length, 0, "no deferral may be invoked below the cap");
|
|
q.releaseSchedulerBackupSlot();
|
|
} finally {
|
|
if (saved === undefined) delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
else process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS = saved;
|
|
}
|
|
});
|
|
|
|
test("a saturated cap defers through moveToDelayed and throws DelayedError (no failure recorded)", async () => {
|
|
const saved = process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
try {
|
|
const q = evalBackupStarvationSlice();
|
|
// Saturate: hold the cap's slots exactly the way live runs would.
|
|
let heldCount = 0;
|
|
while (q.acquireSchedulerBackupSlot()) heldCount++;
|
|
assert.strictEqual(heldCount, q.SCHEDULER_MAX_CONCURRENT_BACKUPS, "the counter must saturate at the cap");
|
|
|
|
const { job, calls } = makeBackupJobSpy();
|
|
let thrown = null;
|
|
try {
|
|
await q.gate(job, "tok-2");
|
|
} catch (err) {
|
|
thrown = err;
|
|
}
|
|
assert.ok(thrown, "a saturated cap must not run the backup inline");
|
|
assert.strictEqual(thrown.name, "DelayedError", "the deferral marker must be bullmq's DelayedError — handleFailed then records no failure and consumes no attempt");
|
|
assert.strictEqual(calls.moved.length, 1, "the deferral must move the job to the delayed set (same id, re-runnable)");
|
|
assert.ok(
|
|
Math.abs(calls.moved[0].timestamp - (Date.now() + q.SCHEDULER_BACKUP_DEFER_DELAY_MS)) < 5000,
|
|
"the deferred re-run must be scheduled at the re-check delay, not dropped or postponed to the next recurrence"
|
|
);
|
|
assert.strictEqual(calls.moved[0].token, "tok-2", "moveToDelayed must receive the worker's lock token");
|
|
|
|
// The gate took no slot on the deferral path, so a freed slot is usable again.
|
|
for (let i = 0; i < heldCount; i++) q.releaseSchedulerBackupSlot();
|
|
const { job: job2, calls: calls2 } = makeBackupJobSpy();
|
|
assert.strictEqual(await q.gate(job2, "tok-3"), true, "after releases the fire proceeds again");
|
|
assert.strictEqual(calls2.moved.length, 0);
|
|
q.releaseSchedulerBackupSlot();
|
|
} finally {
|
|
if (saved === undefined) delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
else process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS = saved;
|
|
}
|
|
});
|
|
|
|
test("a failed deferral fails open into today's behavior instead of wedging the worker", async () => {
|
|
const saved = process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
try {
|
|
const q = evalBackupStarvationSlice();
|
|
let heldCount = 0;
|
|
while (q.acquireSchedulerBackupSlot()) heldCount++; // saturate
|
|
const { job, calls } = makeBackupJobSpy(() => { throw new Error("lock lost"); });
|
|
const held = await q.gate(job, "tok-4");
|
|
assert.strictEqual(held, false, "limiter machinery error must run the backup unaccounted (fail-open), never throw past the gate");
|
|
assert.strictEqual(calls.moved.length, 1, "the deferral was attempted before failing open");
|
|
for (let i = 0; i < heldCount; i++) q.releaseSchedulerBackupSlot();
|
|
} finally {
|
|
if (saved === undefined) delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
else process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS = saved;
|
|
}
|
|
});
|
|
|
|
// adpanel:scheduler-defer-deadline — the deferral is a WRITE on the worker's
|
|
// connection: during a Redis outage the command queues indefinitely (BullMQ
|
|
// forces maxRetriesPerRequest: null), so the gate is raced against a hard
|
|
// deadline. On a deadline miss the gate must NOT fall through to the run
|
|
// (that is the double-run arm: the abandoned moveToDelayed can still succeed
|
|
// on recovery and defer the job WHILE the fail-open run executes it) — it
|
|
// exits as a deferral, and the abandoned write's late settlement (success:
|
|
// job moved to delayed; failure: token check -1/-2/-3/-6, job left active for
|
|
// the stalled-check machinery) executes the backup at most once. These tests
|
|
// drive the REAL sliced gate with a controllable never-settling move.
|
|
test("a deferral that outlives the deadline exits as a deferral without running (no indefinite await, no double-run)", async () => {
|
|
const saved = process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
try {
|
|
const q = evalBackupStarvationSlice(40);
|
|
assert.strictEqual(q.SCHEDULER_BACKUP_DEFER_DEADLINE_MS, 40, "the override must reach the sliced gate");
|
|
let heldCount = 0;
|
|
while (q.acquireSchedulerBackupSlot()) heldCount++; // saturate
|
|
|
|
// Controllable move: the command is in flight and never settles on its
|
|
// own — the offline-queue posture of the worker's connection mid-outage.
|
|
let settleMove = null;
|
|
const { job, calls } = makeBackupJobSpy(() => new Promise((resolve, reject) => {
|
|
settleMove = { resolve, reject };
|
|
}));
|
|
|
|
const startedAt = Date.now();
|
|
let thrown = null;
|
|
try {
|
|
await q.gate(job, "tok-deadline");
|
|
} catch (err) {
|
|
thrown = err;
|
|
}
|
|
assert.ok(thrown, "the deadline must settle the gate — a never-settling moveToDelayed may not wedge it");
|
|
assert.strictEqual(thrown.name, "DelayedError", "the timeout arm exits as a deferral (handleFailed records no failure, consumes no attempt), never as a fail-open run");
|
|
assert.ok(Date.now() - startedAt < 2000, "the gate must return at the deadline, not hang on the queued command");
|
|
assert.strictEqual(calls.moved.length, 1, "exactly one moveToDelayed attempt was issued — the timeout arm never re-issues it");
|
|
assert.strictEqual(calls.moved[0].token, "tok-deadline", "the move still carries the worker's lock token (its Lua token check arbitrates the late outcome)");
|
|
|
|
// The gate threw instead of falling through, so this attempt runs the
|
|
// backup ZERO times, and the slot counter is untouched: after releases a
|
|
// fresh fire proceeds (no slot wedged past the deadline).
|
|
for (let i = 0; i < heldCount; i++) q.releaseSchedulerBackupSlot();
|
|
const { job: job2, calls: calls2 } = makeBackupJobSpy();
|
|
assert.strictEqual(await q.gate(job2, "tok-after"), true, "the timeout arm leaked no slot — the cap is reachable again");
|
|
assert.strictEqual(calls2.moved.length, 0);
|
|
q.releaseSchedulerBackupSlot();
|
|
|
|
// The ABANDONED write settling LATE (Redis recovered, the queued Lua
|
|
// finally runs and succeeds — the job is deferred) must be inert: this
|
|
// attempt already exited as a deferral and never executed the backup, so
|
|
// the late success costs nothing and the delayed instance runs once.
|
|
const unhandled = [];
|
|
const onUnhandled = (err) => unhandled.push(err);
|
|
process.on("unhandledRejection", onUnhandled);
|
|
try {
|
|
settleMove.resolve();
|
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
assert.strictEqual(unhandled.length, 0, "a late-settling abandoned move must never surface as an unhandled rejection");
|
|
} finally {
|
|
process.off("unhandledRejection", onUnhandled);
|
|
}
|
|
} finally {
|
|
if (saved === undefined) delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
else process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS = saved;
|
|
}
|
|
});
|
|
|
|
test("the abandoned move rejecting after the deadline is swallowed — no unhandled rejection, no fail-open run", async () => {
|
|
const saved = process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
try {
|
|
const q = evalBackupStarvationSlice(40);
|
|
let heldCount = 0;
|
|
while (q.acquireSchedulerBackupSlot()) heldCount++; // saturate
|
|
let settleMove = null;
|
|
const { job, calls } = makeBackupJobSpy(() => new Promise((resolve, reject) => {
|
|
settleMove = { resolve, reject };
|
|
}));
|
|
let thrown = null;
|
|
try {
|
|
await q.gate(job, "tok-late-reject");
|
|
} catch (err) {
|
|
thrown = err;
|
|
}
|
|
assert.ok(thrown && thrown.name === "DelayedError", "the deadline arm must exit as a deferral before the late rejection arrives");
|
|
assert.strictEqual(calls.moved.length, 1);
|
|
|
|
// Late FAILURE (the arm the Lua token check produces when the lock
|
|
// expired or the job moved on: -1/-2/-3/-6): the run decision was already
|
|
// made — this attempt executed nothing — and the rejection must be
|
|
// swallowed by the settlement wrapper, never surfaced unhandled.
|
|
const unhandled = [];
|
|
const onUnhandled = (err) => unhandled.push(err);
|
|
process.on("unhandledRejection", onUnhandled);
|
|
try {
|
|
settleMove.reject(new Error("lock lost at recovery (Lua -2)"));
|
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
assert.strictEqual(unhandled.length, 0, "a late-rejecting abandoned move must never surface as an unhandled rejection");
|
|
} finally {
|
|
process.off("unhandledRejection", onUnhandled);
|
|
}
|
|
for (let i = 0; i < heldCount; i++) q.releaseSchedulerBackupSlot();
|
|
} finally {
|
|
if (saved === undefined) delete process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS;
|
|
else process.env.SCHEDULER_MAX_CONCURRENT_BACKUPS = saved;
|
|
}
|
|
});
|
|
|
|
test("the gate precedes the run-claim and the streak hook — a deferral leaks no claim and records no failure", () => {
|
|
const processor = sliceFrom(
|
|
indexCode,
|
|
'schedulerWorker = new Worker("adpanel-scheduler", async (job, token) => {',
|
|
'schedulerWorker.on("completed"',
|
|
"worker processor for backup starvation ordering"
|
|
);
|
|
const gateAt = processor.indexOf("let schedulerBackupSlotHeld = false;");
|
|
const claimAt = processor.indexOf("const runClaimKey");
|
|
const streakAt = processor.indexOf("await recordSchedulerFailureStreak(job, err);");
|
|
assert.ok(gateAt >= 0 && claimAt > gateAt, "the saturation gate must run BEFORE the per-run NX claim — a deferral must not leak a claim slot");
|
|
assert.ok(streakAt > claimAt, "the failure-streak hook lives in the body catch, structurally unreachable from the deferral path");
|
|
assert.strictEqual(processor.split("job.moveToDelayed(").length - 1, 1, "the deferral is the only moveToDelayed call in the processor");
|
|
assert.strictEqual(
|
|
processor.split('if (actionType === "backup") {').length - 1,
|
|
1,
|
|
"only the backup actionType is gated — console/server-control/file/agent jobs keep today's behavior byte-for-byte"
|
|
);
|
|
// adpanel:scheduler-defer-deadline — the deferral await is deadline-raced
|
|
// (a Redis outage may not wedge a worker slot past the deadline; the
|
|
// timeout arm is part of THIS gate, structurally before the run-claim), on
|
|
// the shared raceWithDeadline helper with a pinned literal constant, same
|
|
// doctrine as the run-claim and streak-hook deadlines.
|
|
assert.ok(
|
|
processor.includes("raceWithDeadline(") && processor.includes("SCHEDULER_BACKUP_DEFER_DEADLINE_MS"),
|
|
"the deferral must be deadline-raced against SCHEDULER_BACKUP_DEFER_DEADLINE_MS inside the gate"
|
|
);
|
|
assert.ok(
|
|
indexCode.includes("const SCHEDULER_BACKUP_DEFER_DEADLINE_MS = 5000;"),
|
|
"the deferral deadline is a pinned 5000ms constant (same doctrine as SCHEDULER_RUN_CLAIM_DEADLINE_MS)"
|
|
);
|
|
// The release must cover every post-gate exit: the body try/catch gained a
|
|
// finally, and the one pre-try exit (stall re-run guard) releases explicitly.
|
|
const tailWindow = sliceFrom(
|
|
processor,
|
|
"await recordSchedulerFailureStreak(job, err);",
|
|
"connection: bullmqConnectionOpts",
|
|
"worker catch tail"
|
|
);
|
|
assert.ok(tailWindow.includes("finally {") && tailWindow.includes("releaseSchedulerBackupSlot()"), "the body try/catch must release the backup slot on every post-gate exit");
|
|
const guardWindow = sliceFrom(
|
|
processor,
|
|
"if (alreadyRunning) {",
|
|
"try {",
|
|
"stall re-run guard window"
|
|
);
|
|
assert.ok(guardWindow.includes("releaseSchedulerBackupSlot()"), "the alreadyRunning throw bypasses the finally — it must release the slot explicitly");
|
|
});
|