Files
Kelx/tests/scheduler-file-actions.test.js
T
2026-11-30 16:32:37 +00:00

666 lines
29 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
// Regression tests for the scheduler create_file/modify_file dead endpoint.
//
// Bug: the scheduler worker executed both file actions with
// PUT /v1/servers/<server>/files/<encodeURIComponent(filePath)> body {content}
// but the node daemon's router only dispatches the fixed sub-actions
// list/read/write/delete/upload/archive under files/ (main.go handleAPIv1);
// any real path like config/settings.yml matched no sub-action and fell
// through to the router's global 404. Every scheduled file task therefore
// failed on every run ("File create failed: 404") — the feature was dead
// code the UI still let users schedule.
//
// Fix: both actions now go through schedulerNodeFileWrite(), which follows
// the interactive write relay contract (nodes.js POST /api/nodes/server/:name/file):
// safeJoinUnix pins the path under ctx.baseDir (throwing on absolute /
// traversal / control-character input BEFORE any node call) and POST /v1/fs/write
// receives { path, server, content, encoding, mode }. The daemon enforces the
// mode atomically: "create" refuses an existing target (409), "update"
// refuses a missing one (404 + existed:false), so a recurring create cannot
// silently clobber and a recurring modify cannot silently resurrect a deleted
// file. The 120s timeout is the write parity budget (a shorter one aborts the
// panel-side call while the daemon completes the write anyway — the exact
// re-execution bug class documented in node-relay-timeout-parity.test.js).
//
// index.js boots servers on require and cannot be loaded in-process, so —
// same technique as fs-op-ack / node-relay-timeout-parity — the REAL
// safeJoinUnix and schedulerNodeFileWrite are sliced from source and
// evaluated with injected fakes (a stub nodes module records the httpJson
// call and returns canned daemon responses); the wiring around them is pinned
// with comment-stripped source assertions.
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);
}
// ---------------------------------------------------------------------------
// Evaluate the REAL helpers with injectable dependencies
// ---------------------------------------------------------------------------
// adpanel:relay-helper-consolidation — safeJoinUnix moved to
// services/node-fs-relay.js (one implementation shared with nodes.js; the
// panel policy is the default style). The REAL implementation is still sliced
// and evaluated — now from the shared module — with the same invariant:
// absolute / traversal / control-character input throws BEFORE any node call,
// with the panel message vocabulary the write-relay contract surfaces.
const NODE_FS_RELAY_JS = path.join(ROOT, "services", "node-fs-relay.js");
const nodeFsRelaySource = fs.readFileSync(NODE_FS_RELAY_JS, "utf8");
const safeJoinUnix = new Function(
"path",
sliceFrom(nodeFsRelaySource, "function safeJoinUnix(baseDir, rel, style) {", "\nfunction safeJoinUnixRelay(", "safeJoinUnix") +
"\nreturn safeJoinUnix;"
)(path);
// A stub ./nodes.js: records the single httpJson call per invocation and
// replies with a canned { status, json } daemon response.
function makeStubNodes(response) {
const calls = [];
const stub = {
calls,
httpJson: async (url, opts) => {
calls.push({ url, opts });
return typeof response === "function" ? response(calls.length, { url, opts }) : response;
},
nodeUrl: (node, p) => `${node.baseUrl}${p}`,
nodeHeaders: (node) => ({ Authorization: `Bearer ${node.token}` }),
};
return { stub, calls };
}
const schedulerNodeFileWrite = new Function(
"require",
"safeJoinUnix",
sliceFrom(indexSource, "async function schedulerNodeFileWrite(", "\nfunction scheduleToCron(", "schedulerNodeFileWrite") +
"\nreturn schedulerNodeFileWrite;"
)((moduleName) => {
assert.strictEqual(moduleName, "./nodes.js");
return currentStub;
},
safeJoinUnix);
// Mutable target for the fake require — each test installs its own stub.
let currentStub = null;
const CTX = {
node: { baseUrl: "http://node.example:8081", token: "node-token" },
nodeServerName: "srv01",
baseDir: "/vols/srv01",
server: { name: "srv01" },
};
function install(response) {
const made = makeStubNodes(response);
currentStub = made.stub;
return made.calls;
}
// ---------------------------------------------------------------------------
// Behavioral: request shape against a stub node
// ---------------------------------------------------------------------------
test("create mode POSTs the relay contract to /v1/fs/write", async () => {
const calls = install({ status: 200, json: { ok: true, existed: false } });
const json = await schedulerNodeFileWrite(CTX, "config/settings.yml", "line1\nline2\n", "create");
assert.strictEqual(json.ok, true);
assert.strictEqual(calls.length, 1, "exactly one node call");
const { url, opts } = calls[0];
assert.strictEqual(url, "http://node.example:8081/v1/fs/write");
assert.strictEqual(opts.method, "POST");
assert.strictEqual(opts.timeoutMs, 120000, "write parity budget (nodeFsPost / relay)");
assert.deepStrictEqual(opts.headers, { "Content-Type": "application/json", Authorization: "Bearer node-token" });
assert.deepStrictEqual(opts.body, {
path: "/vols/srv01/config/settings.yml",
server: "srv01",
content: "line1\nline2\n",
encoding: "utf8",
mode: "create",
});
});
test("update mode is forwarded verbatim (scheduled modify)", async () => {
const calls = install({ status: 200, json: { ok: true, existed: true } });
const json = await schedulerNodeFileWrite(CTX, "server.properties", "motd=hi", "update");
assert.deepStrictEqual(calls[0].opts.body, {
path: "/vols/srv01/server.properties",
server: "srv01",
content: "motd=hi",
encoding: "utf8",
mode: "update",
});
assert.strictEqual(json.existed, true);
});
test("null/undefined content is normalized to an empty string", async () => {
const calls = install({ status: 200, json: { ok: true, existed: false } });
await schedulerNodeFileWrite(CTX, ".keep", null, "create");
assert.strictEqual(calls[0].opts.body.content, "");
});
test("traversal path is rejected before any node call", async () => {
const calls = install({ status: 200, json: { ok: true } });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "../../etc/passwd", "x", "create"),
/Unix path traversal detected/
);
assert.strictEqual(calls.length, 0, "no HTTP call may leave the panel for a traversal path");
});
test("absolute path is rejected before any node call", async () => {
const calls = install({ status: 200, json: { ok: true } });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "/etc/passwd", "x", "update"),
/Absolute path not allowed/
);
assert.strictEqual(calls.length, 0);
});
test("control characters in the path are rejected before any node call", async () => {
const calls = install({ status: 200, json: { ok: true } });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "a\nb", "x", "create"),
/Unsafe characters in path/
);
assert.strictEqual(calls.length, 0);
});
// ---------------------------------------------------------------------------
// Behavioral: daemon response mapping
// ---------------------------------------------------------------------------
test("409 (create hit an existing target) surfaces as 'file already exists'", async () => {
install({ status: 409, json: { ok: false, error: "file already exists", existed: true } });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "exists.txt", "x", "create"),
/file already exists/
);
});
test("404 with existed:false (update hit a missing target) surfaces as 'file not found'", async () => {
install({ status: 404, json: { ok: false, error: "file not found", existed: false } });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "missing.txt", "x", "update"),
/file not found/
);
});
test("a plain 404 WITHOUT existed:false stays a generic write failure", async () => {
// Guards the mapping against a regression to another wrong-URL era: a
// router-level 404 must not masquerade as the mode-specific "file not found".
install({ status: 404, json: null });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "a.txt", "x", "update"),
/File write failed: 404/
);
});
test("507 quota responses propagate the daemon's quota error", async () => {
install({ status: 507, json: { ok: false, error: "disk quota exceeded (10GiB)" } });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "big.txt", "x", "create"),
/disk quota exceeded \(10GiB\)/
);
});
test("507 without a daemon message falls back to a generic quota error", async () => {
install({ status: 507, json: {} });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "big.txt", "x", "create"),
/disk quota exceeded/
);
});
test("other non-200 responses surface the daemon error or the status", async () => {
install({ status: 500, json: { ok: false, error: "failed to write file" } });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "a.txt", "x", "create"),
/failed to write file/
);
install({ status: 502, json: null });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "a.txt", "x", "create"),
/File write failed: 502/
);
});
test("200 with ok:false is still a failure", async () => {
install({ status: 200, json: { ok: false } });
await assert.rejects(
() => schedulerNodeFileWrite(CTX, "a.txt", "x", "create"),
/File write failed: 200/
);
});
// ---------------------------------------------------------------------------
// Source-level: the worker and the create route are wired to the helper
// ---------------------------------------------------------------------------
test("the dead files/<encodeURIComponent(path)> URL no longer exists in index.js", () => {
assert.ok(
!indexCode.includes("files/${encodeURIComponent"),
"the scheduler must not address the node's files router with a raw file path — that URL always 404s (only the fixed sub-actions list/read/write/delete/upload/archive are routed)"
);
});
test("create_file and modify_file cases call the helper with create/update modes", () => {
const createCase = sliceFrom(indexCode, 'case "create_file": {', 'case "modify_file": {', "create_file case");
const modifyCase = sliceFrom(indexCode, 'case "modify_file": {', "case \"backup\": {", "modify_file case");
assert.ok(createCase.includes('schedulerNodeFileWrite(ctx, targetPath, content, "create")'), "create_file must use mode \"create\"");
assert.ok(modifyCase.includes('schedulerNodeFileWrite(ctx, targetPath, content, "update")'), "modify_file must use mode \"update\"");
// Audit parity with the interactive write relay and the scheduled-backup
// convention: scheduled file writes record file_edit activity.
assert.ok(createCase.includes('"file_edit"'), "create_file records file_edit activity");
assert.ok(modifyCase.includes('"file_edit"'), "modify_file records file_edit activity");
});
test("the create route probes filePath with the same safeJoinUnix before storing the task", () => {
const route = sliceFrom(
indexCode,
'app.post("/api/scheduler/:serverName/tasks"',
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
"scheduler create route"
);
assert.ok(route.includes('safeJoinUnix("/probe"'), "creation-time filePath probe missing");
assert.ok(
route.includes("filePath must be a relative path inside the server directory"),
"the probe's 400 message is missing"
);
});
test("the create route 500 no longer leaks internal error text (parity with siblings)", () => {
const route = sliceFrom(
indexCode,
'app.post("/api/scheduler/:serverName/tasks"',
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
"scheduler create route"
);
assert.ok(route.includes('error: "internal error"'), "the catch must answer the sibling routes' bare shape");
assert.ok(
!route.includes("detail: err?.message"),
"internal exception text (BullMQ/Redis/library messages) must not reach the client"
);
assert.ok(route.includes('console.error("[scheduler] Create task error:"'), "the full error stays in the server log");
});
// ---------------------------------------------------------------------------
// adpanel:scheduler-file-content-cap — create_file/modify_file content is the
// only scheduler payload field without its own cap (console command 512, task
// name 100, agent prompt 12000, backup name/desc 120/500): it used to be
// bounded only by the global 1 MB JSON body parser × the per-server task
// quota, so a scheduler_create + files_create holder could pin tens of MB
// verbatim in the scheduler's SHARED Redis (the same instance backs the queue
// and the rate-limit stores). The daemon's 10 MiB per-write cap cannot bound
// that residency because the content is STORED in job data, not just sent.
// Fix: a 262144 (256 KiB) cap enforced at creation (route 400) and mirrored
// at fire time (worker disables a recurring schedule whose STORED payload can
// never pass — the console_command invalid-stored-payload pattern; one-time
// jobs just fail the run). Absent/null content stays legitimate (an empty
// new file — the write helper normalizes it to ""), and non-string content is
// rejected at the gate instead of being silently stringified by the worker.
// ---------------------------------------------------------------------------
// The shipped cap, read from source — not a test-local copy (same technique
// as scheduler-backup-interval-floor's floor parse).
const CAP_MATCH = indexCode.match(/const SCHEDULER_MAX_FILE_CONTENT_LENGTH = (\d+);/);
assert.ok(CAP_MATCH, "SCHEDULER_MAX_FILE_CONTENT_LENGTH must be declared in index.js");
const SCHEDULER_MAX_FILE_CONTENT_LENGTH = parseInt(CAP_MATCH[1], 10);
// (c) Constant lockstep: ONE declaration, the shipped value, and every use
// site referencing the named constant (a bare literal in either copy would
// let route and worker drift — the exact multi-copy failure mode AGENTS.md
// exists for).
test("the content cap is 262144 (256 KiB), declared once, before the route and the worker use it", () => {
assert.strictEqual(SCHEDULER_MAX_FILE_CONTENT_LENGTH, 262144);
const declCount = (indexCode.match(/const SCHEDULER_MAX_FILE_CONTENT_LENGTH = /g) || []).length;
assert.strictEqual(declCount, 1, "the cap must have exactly one declaration");
const declAt = indexCode.indexOf("const SCHEDULER_MAX_FILE_CONTENT_LENGTH = 262144;");
const routeAt = indexCode.indexOf("fileContent.length > SCHEDULER_MAX_FILE_CONTENT_LENGTH");
const workerAt = indexCode.indexOf("content.length > SCHEDULER_MAX_FILE_CONTENT_LENGTH");
assert.ok(routeAt > declAt, "the route gate must reference the declared constant");
assert.ok(workerAt > declAt, "the worker mirror must reference the declared constant (a module-level const used before declaration would throw at boot)");
});
// (a) Create route: slice the REAL `const fileContent = ...` + 400 gate out
// of the create route and evaluate it with a fake res (same technique as
// scheduler-backup-interval-floor's backup-recurrence gate). The cap value is
// injected from the parsed declaration, so the behavioral assertions follow
// the shipped constant (lockstep by construction).
const contentGateBody = sliceFrom(
indexCode,
'const fileContent = (actionType === "create_file" || actionType === "modify_file") ? payload?.content : undefined;',
"const user = await findUserByEmail(email);",
"create-route file-content gate"
);
const runContentGate = new Function(
"actionType", "payload", "res", "SCHEDULER_MAX_FILE_CONTENT_LENGTH",
`"use strict";
${contentGateBody}
return null;`
);
function gate400(actionType, payload) {
const sent = {};
const res = {
status(code) {
sent.code = code;
return { json(body) { sent.body = body; return body; } };
}
};
const result = runContentGate(actionType, payload, res, SCHEDULER_MAX_FILE_CONTENT_LENGTH);
return { result, sent };
}
test("create route: absent or null content is legitimate (an empty new file) — no 400", () => {
for (const payload of [{}, { content: null }, { filePath: "a.txt" }]) {
const { result, sent } = gate400("create_file", payload);
assert.strictEqual(result, null, JSON.stringify(payload));
assert.strictEqual(sent.code, undefined, JSON.stringify(payload));
}
});
test("create route: content exactly at the cap passes; cap+1 is rejected with the sibling 400 shape", () => {
const ok = gate400("create_file", { content: "x".repeat(SCHEDULER_MAX_FILE_CONTENT_LENGTH) });
assert.strictEqual(ok.result, null, "exactly at the cap must pass");
assert.strictEqual(ok.sent.code, undefined);
const { result, sent } = gate400("create_file", { content: "x".repeat(SCHEDULER_MAX_FILE_CONTENT_LENGTH + 1) });
assert.deepStrictEqual(result, {
ok: false,
error: `file content must be ${SCHEDULER_MAX_FILE_CONTENT_LENGTH} characters or fewer`
});
assert.strictEqual(sent.code, 400);
});
test("create route: non-string content (number/object/array) is rejected like an oversized one", () => {
// The worker writes content verbatim via `content == null ? "" : String(content)`,
// so a stored non-string would be silently stringified — tightened to
// string-only at the gate (absent/null still allowed).
for (const bad of [5, { nested: true }, ["x"]]) {
const { result, sent } = gate400("modify_file", { content: bad });
assert.deepStrictEqual(result, {
ok: false,
error: `file content must be ${SCHEDULER_MAX_FILE_CONTENT_LENGTH} characters or fewer`
}, JSON.stringify(bad));
assert.strictEqual(sent.code, 400, JSON.stringify(bad));
}
});
test("create route: the content gate keys on the file actions only and always through the named constant", () => {
// console_command's payload has its own sanitizer (≤512, single line) — the
// file-content gate must not reach into other actions' payloads.
const other = gate400("console_command", { content: "x".repeat(SCHEDULER_MAX_FILE_CONTENT_LENGTH + 1) });
assert.strictEqual(other.result, null);
assert.strictEqual(other.sent.code, undefined);
const route = sliceFrom(
indexCode,
'app.post("/api/scheduler/:serverName/tasks"',
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
"scheduler create route"
);
assert.ok(
route.includes("fileContent !== undefined && fileContent !== null"),
"the gate must allow absent/null content (an empty new file is legitimate)"
);
assert.ok(
route.includes("typeof fileContent !== \"string\" || fileContent.length > SCHEDULER_MAX_FILE_CONTENT_LENGTH"),
"present content must be a string within the named constant"
);
assert.ok(
!route.includes("> 262144"),
"no bare literal may bypass the constant (route/worker lockstep)"
);
});
// ---------------------------------------------------------------------------
// (b) Worker mirror: slice the REAL create_file/modify_file case bodies out
// of the BullMQ worker and run them inside a switch harness with injected
// dependencies (scheduler-hardening's console_command technique). The disable
// step is the REAL sliced disableRecurringScheduleForJob driven against a
// queue stub, so the recurring/one-time distinction is proven end-to-end
// rather than against a mimic.
// ---------------------------------------------------------------------------
const createFileCaseBody = sliceFrom(indexSource, 'case "create_file": {', 'case "modify_file": {', "worker create_file case");
const modifyFileCaseBody = sliceFrom(indexSource, 'case "modify_file": {', 'case "backup": {', "worker modify_file case");
// The real disable machinery, bound exactly like scheduler-hardening's
// makeDisabler (the slice window also contains the inert
// recordSchedulerFailureStreak, whose out-of-window identifiers are bound
// below but never called by these tests).
const makeRealDisabler = (queue, streakResets) => 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 (streakResets) streakResets.push(repeatKey); },
async () => ({ tracked: false, count: 0, shouldDisable: false }),
20,
45 * 24 * 60 * 60,
(promise, _ms, fallback) => Promise.resolve(promise).catch(() => fallback)
);
function makeFileWorkerHarness({ actionType, payload, job }) {
const writes = [];
const disableCalls = [];
const removedKeys = [];
const activities = [];
const queueStub = {
removeRepeatableByKey: async (key) => { removedKeys.push(key); return true; },
};
const realDisable = makeRealDisabler(queueStub, []);
const recordDisable = async (j, reason) => {
disableCalls.push({ jobId: j.id, reason });
return realDisable(j, reason);
};
const stubNodes = {
remoteContext: async () => ({
exists: true,
remote: true,
node: { baseUrl: "http://node.example:8081", token: "node-token" },
nodeServerName: "srv01",
baseDir: "/vols/srv01",
// adpanel:scheduler-server-identity-bind — the case re-checks its
// execution resolution against the authorization row; id 7 matches the
// injected authzServerEntry below (the normal fire passes the check).
server: { id: 7, name: "srv01" },
}),
httpJson: async () => ({ status: 200, json: { ok: true } }),
nodeUrl: (node, p) => `${node.baseUrl}${p}`,
nodeHeaders: (node) => ({ Authorization: `Bearer ${node.token}` }),
};
const caseBody = actionType === "create_file" ? createFileCaseBody : modifyFileCaseBody;
const run = new Function(
"payload", "serverName", "job", "userName", "userId",
"require", "recordActivity", "disableRecurringScheduleForJob",
"schedulerNodeFileWrite", "getCanonicalServerName", "SCHEDULER_MAX_FILE_CONTENT_LENGTH",
// adpanel:scheduler-server-identity-bind — the REAL sliced helper + the
// authz row the fire was authorized on.
"schedulerAuthzServerEntry", "ensureSchedulerFireServerIdentity",
`"use strict";
return async () => {
const actionType = ${JSON.stringify(actionType)};
switch (actionType) {
${caseBody}
}
};`
)(
payload,
"srv01",
job,
"creator@example.com",
42,
(moduleName) => {
assert.strictEqual(moduleName, "./nodes.js");
return stubNodes;
},
(serverName, type, detail) => activities.push({ serverName, type, detail }),
recordDisable,
async (ctx, targetPath, content, mode) => {
writes.push({ targetPath, content, mode });
return { existed: false };
},
(server, fallback) => (server && server.name) || fallback,
SCHEDULER_MAX_FILE_CONTENT_LENGTH,
{ id: 7, name: "srv01" },
new Function(
"disableRecurringScheduleForJob",
sliceFrom(
indexSource,
"async function ensureSchedulerFireServerIdentity(",
"\n// adpanel:planner-access-job-retract",
"fire identity checker (file actions)"
) + "\nreturn ensureSchedulerFireServerIdentity;"
)(recordDisable)
);
return { run, writes, disableCalls, removedKeys, activities };
}
const RECURRING_JOB = (actionType) => ({
id: "job-1",
data: { serverName: "srv01", actionType, name: "Nightly config", userName: "creator@example.com" },
repeatJobKey: "repeat-key-1",
});
test("worker: recurring create_file with oversized stored content disables the schedule and throws before any node call", async () => {
const h = makeFileWorkerHarness({
actionType: "create_file",
payload: { filePath: "config/settings.yml", content: "x".repeat(SCHEDULER_MAX_FILE_CONTENT_LENGTH + 1) },
job: RECURRING_JOB("create_file"),
});
await assert.rejects(() => h.run(), /Invalid stored file content/);
assert.strictEqual(h.writes.length, 0, "no write may reach the node for an oversized stored payload");
assert.strictEqual(h.disableCalls.length, 1);
assert.strictEqual(h.disableCalls[0].reason, "stored file content exceeds the content cap");
assert.deepStrictEqual(h.removedKeys, ["repeat-key-1"], "the real disable machinery must remove the job's own repeatable");
});
test("worker: recurring modify_file mirrors the same disable-then-throw", async () => {
const h = makeFileWorkerHarness({
actionType: "modify_file",
payload: { filePath: "server.properties", content: "y".repeat(SCHEDULER_MAX_FILE_CONTENT_LENGTH + 1) },
job: RECURRING_JOB("modify_file"),
});
await assert.rejects(() => h.run(), /Invalid stored file content/);
assert.strictEqual(h.writes.length, 0);
assert.strictEqual(h.disableCalls.length, 1);
assert.strictEqual(h.disableCalls[0].reason, "stored file content exceeds the content cap");
assert.deepStrictEqual(h.removedKeys, ["repeat-key-1"]);
});
test("worker: content exactly at the cap runs normally — no disable, content forwarded verbatim", async () => {
const content = "x".repeat(SCHEDULER_MAX_FILE_CONTENT_LENGTH);
const h = makeFileWorkerHarness({
actionType: "create_file",
payload: { filePath: "config/settings.yml", content },
job: RECURRING_JOB("create_file"),
});
const result = await h.run();
assert.deepStrictEqual(result, { success: true, action: "create_file", path: "config/settings.yml" });
assert.strictEqual(h.writes.length, 1);
assert.strictEqual(h.writes[0].content, content);
assert.strictEqual(h.disableCalls.length, 0);
assert.deepStrictEqual(h.removedKeys, []);
});
test("worker: a one-time job with oversized stored content throws but disables NOTHING", async () => {
// No repeatJobKey / no opts.repeat — a plain one-time job owns no recurring
// schedule; the real disable machinery no-ops for it and the throw fails
// the run (the same contract the console_command case relies on).
const h = makeFileWorkerHarness({
actionType: "create_file",
payload: { filePath: "a.txt", content: "x".repeat(SCHEDULER_MAX_FILE_CONTENT_LENGTH + 1) },
job: { id: "one-1", data: { serverName: "srv01", actionType: "create_file", name: "T", userName: "creator@example.com" } },
});
await assert.rejects(() => h.run(), /Invalid stored file content/);
assert.strictEqual(h.disableCalls.length, 1, "the case still attempts the disable");
assert.deepStrictEqual(h.removedKeys, [], "the disable must no-op for a job with no repeat identity");
assert.strictEqual(h.writes.length, 0);
});
test("worker: absent or null stored content stays legitimate (forwarded to the write helper, which normalizes it)", async () => {
for (const content of [undefined, null]) {
const h = makeFileWorkerHarness({
actionType: "modify_file",
payload: { filePath: "a.txt", content },
job: RECURRING_JOB("modify_file"),
});
const result = await h.run();
assert.deepStrictEqual(result, { success: true, action: "modify_file", path: "a.txt" }, String(content));
assert.strictEqual(h.writes.length, 1);
assert.strictEqual(h.writes[0].content, content, "the gate must not fire; schedulerNodeFileWrite keeps its null→\"\" normalization");
assert.deepStrictEqual(h.removedKeys, []);
}
});
test("worker: both file cases cap the stored content against the SAME named constant through the ONE disable machinery", () => {
for (const [label, body] of [
["create_file", createFileCaseBody],
["modify_file", modifyFileCaseBody],
]) {
const code = stripFullLineComments(body);
assert.ok(
code.includes("content.length > SCHEDULER_MAX_FILE_CONTENT_LENGTH"),
`${label} must cap the STORED content against the named constant`
);
assert.ok(
code.includes("disableRecurringScheduleForJob(job, reason)"),
`${label} must disable through the ONE disable machinery`
);
assert.ok(
code.includes('"stored file content exceeds the content cap"'),
`${label} must use the shared disable reason`
);
assert.ok(
!code.includes("> 262144"),
`${label} must not hard-code the cap value (route/worker lockstep)`
);
assert.ok(
body.includes("adpanel:scheduler-file-content-cap"),
`${label} must carry the constraint comment`
);
}
});