Files
Kelx/tests/scheduler-legacy-identity-sweep.test.js
T
2026-11-30 16:32:37 +00:00

496 lines
23 KiB
JavaScript

"use strict";
// Tests for adpanel:scheduler-legacy-identity-sweep — the leader-only boot
// retirement of the pre-bind schedule population.
//
// The finding: schedules stored BEFORE adpanel:scheduler-server-identity-bind
// carry no serverId, so the fire-time identity checks (which trigger only on a
// POSITIVE mismatch) skip them. When such a schedule's server is deleted with
// its cleanup missed (deleteServerSchedules is best-effort and can strand
// jobs) and a DIFFERENT owner's server is recreated under the same name, the
// stored payload keeps firing on that owner's server on every tick for EVERY
// creator whose access check still passes — admins pass
// userHasAccessToServer unconditionally for any name, and a non-admin creator
// who is later GRANTED access to the recreated row (a new owner shares it)
// passes too, so the old "non-admins self-heal" framing was true only for
// creators WITHOUT access to the recreated row.
//
// The fix: once per boot, from the C4 leader flow (the tail of
// initializeScheduler — its ONLY call site), the sweep enumerates the
// fleet-wide queue's waiting/delayed jobs through the shared scan helper plus
// the repeatable templates, and retires every job whose data lacks a serverId:
// recurring schedules lose their recurrence through the ONE disable machinery
// (which removes the template and its next delayed iteration), one-time
// waiting/delayed jobs are removed with a loud payload-free log. A backfill
// (stamping the CURRENT row's id onto a stranded job) was deliberately
// rejected — it would legitimize the stale payload on the new owner's server.
//
// index.js boots servers on require and cannot be loaded in-process, so —
// same technique as scheduler-hardening / scheduler-revoke-pagination — the
// REAL sweep, the REAL fleet-paginated scan helper and the REAL disable
// machinery are sliced from source and evaluated with injected fakes; the
// queue stub reproduces BullMQ 5's removeRepeatable script semantics (the
// removal takes the template AND its next delayed iteration; a waiting
// iteration is left to fire at most once more, and the worker's
// updateJobScheduler script refuses to iterate once the scheduler entry is
// gone — "If it does not exist we should not iterate anymore").
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 cannot satisfy the
// source-level assertions.
function stripFullLineComments(src) {
return src
.split("\n")
.filter((line) => !/^\s*\/\//.test(line))
.join("\n");
}
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);
}
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);
}
// The REAL disable machinery — the identical slice window
// scheduler-hardening.test.js binds (the sweep must not grow a fork of it).
const disableMachinerySlice = sliceFrom(
INDEX_SRC,
"async function disableRecurringScheduleForJob(job, reason) {",
"\n// Re-validates, at execution time",
"disable machinery slice"
);
// The REAL fleet-paginated scan helper + the REAL sweep, one window (the
// constants, fetchAllSchedulerJobsInStates, the sweep reason and the sweep).
const sweepSlice = sliceFrom(
INDEX_SRC,
"const SCHEDULER_JOB_SCAN_BATCH = 1000;",
"\n// Cross-site read guard",
"legacy identity sweep slice"
);
const repeatKeyOf = (job) => job.repeatJobKey || job.opts?.repeat?.key || null;
// BullMQ-shaped stub: getJobs pages ONE state per call (what the real scan
// helper requests); removeRepeatableByKey reproduces the removeRepeatable
// script (template + next DELAYED iteration die; waiting iterations remain);
// job.remove() drops the job from whichever state list holds it.
function makeQueueStub({ waitingSpecs = [], delayedSpecs = [], repeatables = [] } = {}) {
const state = { waiting: [], delayed: [], repeatables: repeatables.map((r) => ({ ...r })) };
const calls = { getJobs: [], repeatKeyRemovals: [], jobRemovals: [] };
const makeJob = (list, spec) => ({
id: spec.id,
repeatJobKey: spec.repeatJobKey ?? null,
opts: spec.opts || {},
data: spec.data,
remove: async () => {
if (spec.failRemove) throw new Error(spec.failRemove);
calls.jobRemovals.push(spec.id);
const idx = state[list].findIndex((j) => j.id === spec.id);
if (idx >= 0) state[list].splice(idx, 1);
},
});
state.waiting = waitingSpecs.map((spec) => makeJob("waiting", spec));
state.delayed = delayedSpecs.map((spec) => makeJob("delayed", spec));
const queue = {
calls,
state,
async getJobs(states, start, end) {
calls.getJobs.push({ states: [...states], start, end });
const list = states[0] === "waiting" ? state.waiting : state.delayed;
return list.slice(start, end + 1);
},
async getRepeatableJobs() {
return state.repeatables;
},
async removeRepeatableByKey(key) {
if (repeatables.find((r) => r.key === key && r.failRemove)) {
throw new Error("redis down");
}
calls.repeatKeyRemovals.push(key);
const before = state.repeatables.length;
state.repeatables = state.repeatables.filter((r) => r.key !== key);
state.delayed = state.delayed.filter((j) => repeatKeyOf(j) !== key);
return state.repeatables.length < before;
},
};
return { queue, state, calls };
}
// Evaluates the REAL sliced machinery + scan helper + sweep sharing ONE
// schedulerQueue binding, exactly like the makeDisabler harness binds them.
function makeHarness({ stub = null, queue = undefined } = {}) {
const queueStub = stub || makeQueueStub();
const resets = [];
const fns = new Function(
"schedulerQueue",
"schedulerStateRedis",
"resetSchedulerFailureStreak",
"bumpSchedulerFailureStreak",
"SCHEDULER_MAX_CONSECUTIVE_FAILURES",
"DEFAULT_STREAK_TTL_SECONDS",
"raceWithDeadline",
disableMachinerySlice + "\n" + sweepSlice +
"\nreturn { runSchedulerLegacyIdentitySweep, SCHEDULER_LEGACY_IDENTITY_SWEEP_REASON, fetchAllSchedulerJobsInStates, disableRecurringScheduleForJob };"
)(
queue !== undefined ? queue : queueStub.queue,
null,
async (_client, repeatKey) => { resets.push(repeatKey); },
async () => ({ tracked: false, count: 0, shouldDisable: false }),
20,
45 * 24 * 60 * 60,
(promise, _ms, fallback) => Promise.resolve(promise).catch(() => fallback)
);
return { ...fns, ...queueStub, resets };
}
async function captureLogs(run) {
const warnings = [];
const logs = [];
const origWarn = console.warn;
const origLog = console.log;
console.warn = (...args) => warnings.push(args.join(" "));
console.log = (...args) => logs.push(args.join(" "));
try {
await run();
} finally {
console.warn = origWarn;
console.log = origLog;
}
return { warnings, logs };
}
// Fixtures. The SECRET-* markers exist so the tests can prove the stored
// payload content never reaches a log line.
const LEGACY_RECURRING = (over = {}) => ({
id: "rep-legacy-1",
repeatJobKey: "rk-legacy",
opts: { repeat: { pattern: "0 3 * * *", key: "rk-legacy" } },
data: {
serverName: "srv01",
actionType: "console_command",
name: "Legacy recurring",
userName: "creator@example.com",
payload: { command: "SECRET-CONSOLE-PAYLOAD" },
...over.data,
},
...over.fields,
});
const BOUND_RECURRING = (over = {}) => ({
id: "rep-bound-1",
repeatJobKey: "rk-bound",
opts: { repeat: { pattern: "0 4 * * *", key: "rk-bound" } },
data: { serverName: "srv01", actionType: "backup", name: "Bound recurring", userName: "owner@example.com", serverId: 7, ...over.data },
...over.fields,
});
const LEGACY_ONE_TIME = (over = {}) => ({
id: "once-legacy-1",
opts: { delay: 60000 },
data: {
serverName: "srv01",
actionType: "console_command",
name: "Legacy once",
userName: "creator@example.com",
payload: { command: "SECRET-ONCE-PAYLOAD" },
...over.data,
},
...over.fields,
});
const BOUND_ONE_TIME = (over = {}) => ({
id: "once-bound-1",
opts: { delay: 120000 },
data: { serverName: "srv01", actionType: "backup", name: "Bound once", userName: "owner@example.com", serverId: 7, ...over.data },
...over.fields,
});
const TEMPLATE = (key, extra = {}) => ({
key,
name: JSON.stringify({ serverName: "srv01", actionType: "console_command", name: "T", userName: "creator@example.com" }),
pattern: "0 3 * * *",
next: Date.now() + 60000,
...extra,
});
// ─── 1. The legacy populations are retired ───────────────────────────────────
test("a legacy recurring schedule (no serverId) loses its recurrence through the ONE disable machinery, with the re-bind reason", async () => {
const h = makeHarness({
stub: makeQueueStub({
delayedSpecs: [LEGACY_RECURRING()],
repeatables: [TEMPLATE("rk-legacy")],
}),
});
const { warnings } = await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
assert.deepStrictEqual(h.calls.repeatKeyRemovals, ["rk-legacy"], "the exact repeat key must be removed through the ONE disable machinery");
assert.deepStrictEqual(h.state.repeatables, [], "the repeatable template dies with the disable");
assert.deepStrictEqual(h.state.delayed, [], "the next delayed iteration dies with the disable (removeRepeatable script semantics)");
assert.deepStrictEqual(h.resets, ["rk-legacy"], "the failure-streak counter dies with the schedule, like every disable path");
const disableWarn = warnings.find((w) => w.includes("Disabled recurring schedule"));
assert.ok(disableWarn, "the machinery's own disable warning must fire");
assert.ok(disableWarn.includes(h.SCHEDULER_LEGACY_IDENTITY_SWEEP_REASON), "the reason must tell the operator how to re-bind");
assert.ok(!warnings.some((w) => w.includes("SECRET-CONSOLE-PAYLOAD")), "the stored payload content must never reach a log line");
});
test("a legacy one-time waiting/delayed job is removed with a loud single-line log naming the task, never the payload", async () => {
const h = makeHarness({
stub: makeQueueStub({
delayedSpecs: [
LEGACY_ONE_TIME({ data: { name: "Legacy\nonce\x07task" } }), // pre-strip controls in the stored name
],
}),
});
const { warnings } = await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
assert.deepStrictEqual(h.calls.jobRemovals, ["once-legacy-1"], "the one-time job itself must be removed");
assert.deepStrictEqual(h.calls.repeatKeyRemovals, [], "a one-time job owns no recurrence — the disable machinery must not be pointed at it");
assert.deepStrictEqual(h.state.delayed, [], "the job is gone from the queue");
const removalWarn = warnings.find((w) => w.includes("Removed legacy one-time schedule job"));
assert.ok(removalWarn, "the removal must be loud");
assert.ok(removalWarn.includes("srv01 / Legacy once task"), "the log names the server and the (stripped) task name");
assert.ok(!removalWarn.includes("\n") && !removalWarn.includes("\x07"), "no control character may survive into the log line (log-injection strip)");
assert.ok(!warnings.some((w) => w.includes("SECRET-ONCE-PAYLOAD")), "the stored payload content must never reach a log line");
});
test("a job carrying a serverId is NEVER touched — the skip predicate is exactly undefined/null", async () => {
const h = makeHarness({
stub: makeQueueStub({
waitingSpecs: [BOUND_RECURRING()],
delayedSpecs: [BOUND_ONE_TIME()],
repeatables: [TEMPLATE("rk-bound")],
}),
});
const { warnings, logs } = await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
assert.deepStrictEqual(h.calls.repeatKeyRemovals, [], "a bound recurring schedule must never lose its recurrence");
assert.deepStrictEqual(h.calls.jobRemovals, [], "a bound one-time job must never be removed");
assert.strictEqual(h.state.waiting.length, 1);
assert.strictEqual(h.state.delayed.length, 1);
assert.strictEqual(h.state.repeatables.length, 1);
assert.ok(
[...logs, ...warnings].some((l) => l.includes("found no un-bound schedules (2 bound schedules untouched, 1 recurring templates)")),
"the boot summary must report the untouched bound population"
);
});
test("a mixed queue retires ONLY the un-bound population (uniformly across creators)", async () => {
const h = makeHarness({
stub: makeQueueStub({
waitingSpecs: [BOUND_RECURRING(), LEGACY_ONE_TIME()],
delayedSpecs: [BOUND_ONE_TIME(), LEGACY_RECURRING()],
repeatables: [TEMPLATE("rk-bound"), TEMPLATE("rk-legacy")],
}),
});
const { warnings } = await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
assert.deepStrictEqual(h.calls.repeatKeyRemovals.sort(), ["rk-legacy"], "only the legacy repeatable is removed");
assert.deepStrictEqual(h.calls.jobRemovals, ["once-legacy-1"], "only the legacy one-time job is removed");
assert.strictEqual(h.state.waiting.length, 1, "the bound recurring iteration survives");
assert.strictEqual(h.state.delayed.length, 1, "the bound one-time job survives");
assert.strictEqual(h.state.repeatables.length, 1, "the bound template survives");
assert.ok(
warnings.some((w) => w.includes("retired 1 recurring and 1 one-time schedules stored without server identity binding (0 retirement failure(s) retry next boot, 2 bound schedules untouched, 1 recurring templates remain)")),
"the boot summary counts the retirement"
);
});
// ─── 2. Idempotence + bounding ───────────────────────────────────────────────
test("the sweep is idempotent: a second boot finds nothing and touches nothing", async () => {
const h = makeHarness({
stub: makeQueueStub({
waitingSpecs: [BOUND_RECURRING()],
delayedSpecs: [LEGACY_RECURRING(), LEGACY_ONE_TIME()],
repeatables: [TEMPLATE("rk-bound"), TEMPLATE("rk-legacy")],
}),
});
await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
const removalsAfterFirst = h.calls.repeatKeyRemovals.length + h.calls.jobRemovals.length;
assert.strictEqual(removalsAfterFirst, 2);
const { warnings, logs } = await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
assert.strictEqual(h.calls.repeatKeyRemovals.length + h.calls.jobRemovals.length, removalsAfterFirst, "the second run must remove nothing");
assert.deepStrictEqual(h.state.delayed, [], "the legacy delayed population is gone after the first boot");
assert.strictEqual(h.state.waiting.length, 1);
assert.strictEqual(h.state.repeatables.length, 1);
assert.ok(
[...logs, ...warnings].some((l) => l.includes("found no un-bound schedules (1 bound schedules untouched, 1 recurring templates)")),
"the second boot's summary must show a clean population"
);
});
test("the scan rides the REAL fleet-paginated helper over waiting+delayed only (hard-cap-bounded, active untouched)", async () => {
const h = makeHarness({
stub: makeQueueStub({
delayedSpecs: [LEGACY_ONE_TIME()],
}),
});
await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
const scannedStates = h.calls.getJobs.map((c) => c.states[0]);
assert.deepStrictEqual(scannedStates, ["waiting", "delayed"], "exactly the two states the sweep is specced for — never active");
assert.ok(h.calls.getJobs.every((c) => c.end === c.start + 999), "the helper pages in its 1000-job batches (the hard cap lives inside it)");
});
test("queue client absent (scheduler disabled / no Redis / failed init) → sweep skipped, never thrown", async () => {
const h = makeHarness({ queue: null });
const { logs } = await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
assert.ok(
logs.some((l) => l.includes("Legacy identity sweep skipped: scheduler queue client unavailable")),
"the skip must be visible to operators"
);
});
// ─── 3. Best-effort per job, retried next boot ───────────────────────────────
test("a job whose removal fails logs, is skipped, and leaves the others untouched (next boot retries)", async () => {
const h = makeHarness({
stub: makeQueueStub({
waitingSpecs: [
LEGACY_ONE_TIME({ fields: { id: "once-broken", failRemove: "redis down" } }),
LEGACY_ONE_TIME({ fields: { id: "once-healthy" } }),
],
}),
});
const { warnings } = await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
assert.deepStrictEqual(h.calls.jobRemovals, ["once-healthy"], "the failing removal must not stop the sweep");
assert.ok(warnings.some((w) => w.includes("Legacy identity sweep could not retire job once-broken: redis down")), "the failure is logged per job");
assert.strictEqual(h.state.waiting.length, 1, "the un-retired job stays in the queue — the next boot's sweep retries it");
assert.strictEqual(h.state.waiting[0].id, "once-broken");
});
test("a recurring disable that fails to remove logs via the machinery and is not counted (the template survives for the next boot)", async () => {
const h = makeHarness({
stub: makeQueueStub({
delayedSpecs: [LEGACY_RECURRING()],
repeatables: [{ ...TEMPLATE("rk-legacy"), failRemove: true }],
}),
});
const { warnings } = await captureLogs(() => h.runSchedulerLegacyIdentitySweep());
assert.deepStrictEqual(h.state.repeatables.length, 1, "the template survives when the removal throws");
assert.strictEqual(h.state.delayed.length, 1, "the delayed iteration survives with it");
assert.ok(
warnings.some((w) => w.includes("retired 0 recurring and 0 one-time schedules stored without server identity binding (1 retirement failure(s) retry next boot")),
"an unconfirmed removal must not be counted as retired, but the failure must surface in the summary"
);
assert.ok(
warnings.some((w) => w.includes("Failed to disable recurring schedule rk-legacy")),
"the ONE machinery owns the failure warning"
);
});
// ─── 4. Wiring: leader-only, fire-and-forget, exactly once ───────────────────
test("the sweep's only call site is the fire-and-forget tail of the leader-only initializeScheduler", () => {
const code = stripFullLineComments(INDEX_SRC);
assert.strictEqual(
(code.match(/async function runSchedulerLegacyIdentitySweep\(/g) || []).length,
1,
"the sweep must be defined exactly once"
);
assert.strictEqual(
(code.match(/runSchedulerLegacyIdentitySweep\(\)\.catch\(/g) || []).length,
1,
"the sweep must be called exactly once, fire-and-forget with a .catch"
);
assert.ok(
!code.includes("await runSchedulerLegacyIdentitySweep"),
"the sweep must never be awaited (it can neither delay the leader's init nor block the worker start)"
);
const initBody = stripFullLineComments(sliceFrom(
INDEX_SRC,
"async function initializeScheduler() {",
"\n// Scheduled create_file/modify_file",
"initializeScheduler window"
));
assert.ok(
initBody.includes("runSchedulerLegacyIdentitySweep().catch("),
"the only call must live inside initializeScheduler — the C4 leader flow, never a process-wide boot path"
);
const workerInitAt = initBody.indexOf("[scheduler] BullMQ scheduler worker initialized");
const sweepAt = initBody.indexOf("runSchedulerLegacyIdentitySweep().catch(");
assert.ok(workerInitAt !== -1 && sweepAt > workerInitAt, "the sweep must run after the worker init ordering the leader flow establishes");
});
test("the sweep scans through the shared scan helper and the ONE disable machinery (no forks)", () => {
const code = stripFullLineComments(INDEX_SRC);
assert.strictEqual(
(code.match(/async function fetchAllSchedulerJobsInStates\(states\)/g) || []).length,
1,
"the fleet-paginated scan helper stays the ONE home of the pagination machinery"
);
// Sliced from the RAW source (the end anchor is a comment line), then
// comment-stripped so prose can never satisfy the code assertions.
const sweepBody = stripFullLineComments(sliceFrom(
INDEX_SRC,
"async function runSchedulerLegacyIdentitySweep() {",
"\n// Cross-site read guard",
"sweep body"
));
assert.ok(
sweepBody.includes('fetchAllSchedulerJobsInStates(["waiting", "delayed"])'),
"the sweep must enumerate through the shared helper, not a private getJobs window"
);
assert.ok(
sweepBody.includes("disableRecurringScheduleForJob(job, SCHEDULER_LEGACY_IDENTITY_SWEEP_REASON)"),
"recurring retirement must ride the ONE disable machinery"
);
assert.ok(
sweepBody.includes("if (data.serverId !== undefined && data.serverId !== null) {"),
"the skip predicate must be EXACTLY serverId === undefined || serverId === null"
);
assert.ok(
!/getJobs\(\[/.test(sweepBody),
"the sweep must not open its own fixed getJobs windows"
);
});
// ─── 5. The comment truth: the residual is closed, never backfilled ──────────
test("both accepted-residual comments now cite the sweep and drop the stale framing", () => {
const bindComment = windowBetween(
INDEX_SRC,
"adpanel:scheduler-server-identity-bind — the stored serverId (written by",
"const storedServerId = job.data?.serverId;",
"bind check comment"
);
assert.ok(bindComment.includes("adpanel:scheduler-legacy-identity-sweep"), "the fire-time bind comment must cite the sweep that closes the residual");
assert.ok(bindComment.includes("REJECTED"), "the bind comment must record the rejected backfill alternative");
assert.ok(!bindComment.includes("accepted residual"), "the stale accepted-residual framing must be gone");
const createComment = windowBetween(
INDEX_SRC,
"adpanel:scheduler-server-identity-bind — the schedule is bound to the",
"serverId: serverEntry.id,",
"create route serverId comment"
);
assert.ok(createComment.includes("adpanel:scheduler-legacy-identity-sweep"), "the create-route comment must cite the sweep for un-bound stores");
assert.ok(createComment.includes("Never a backfill"), "the create-route comment must record the rejected backfill alternative");
assert.ok(!createComment.includes("accepted residual"), "the stale accepted-residual framing must be gone");
assert.strictEqual(
(INDEX_SRC.match(/accepted residual/g) || []).length,
0,
"no accepted-residual framing may remain anywhere in index.js"
);
});