Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+469
View File
@@ -0,0 +1,469 @@
"use strict";
// Regression tests for adpanel:scheduler-cron-wrap-floor — the 5-minute
// recurrence floor was bypassable through cron wrap-around.
//
// Bug (security review): the create route's floor gates validated the RAW
// interval, but the cron pattern scheduleToCron stores fires on a FIELD that
// wraps:
// - minutes "59" → 59*60 = 3540s ≥ 300 passed the raw backup/agent check,
// yet `*/59 * * * *` fires at :00 AND :59 — two full backup copies per
// hour, 1 minute apart (wrap gap 1 min);
// - minutes "7" → 420s ≥ 300 passed, yet `*/7` gaps are 7,7,...,7,4 — the
// wrap gap is 4 min < the 5-minute floor;
// - hourly "999" was silently clamped to */23 → `0 */23 * * *` fires TWICE
// daily (00:00 and 23:00, 1h apart) — a requested "every 999 hours"
// agent task ran ~41× more often than promised, on the panel's AI
// budget. scheduleToCron's own comment showed the wrap trap was
// understood for the 24h case only.
//
// Fix: a closed-form smallest-gap predictor (schedulerCronMinGapSeconds —
// there is NO cron-parser dependency to ask) placed next to scheduleToCron,
// and a create-route re-check AFTER the per-action raw floor blocks: for
// minutes/hourly, reject when the smallest ACTUAL gap of the pattern that
// would be stored is below the action's floor (backup/agent 300s, all other
// actions the generic 10s one). Hourly values above 24 are rejected as
// inexpressible instead of silently clamping to twice-daily */23. The raw
// checks stay (they reject non-numeric values the helper's legacy NaN
// defaults would paper over), and scheduleToCron keeps its clamps as
// worker-side safety for schedules stored before this gate.
//
// adpanel:scheduler-fire-floor-mirror — this file also exercises the REAL
// fire-time mirror decision function (schedulerStoredRecurrenceFloorViolation,
// sliced whole next to the helper): it re-derives the STORED schedule's
// smallest gap through schedulerCronMinGapSeconds and reports a disable
// reason when a repeat-identity job's pattern fires below its action's floor.
// The helper's seconds arm clamps EXACTLY like scheduleToCron, so a stored
// raw "3" (created while the route had no generic seconds gate — since
// adpanel:schedule-input-validation the create route 400s it, but pre-gate
// jobs persist in Redis with the 10s-floor pattern) must pass the fire too.
//
// index.js boots servers on require and cannot be loaded in-process, so —
// same technique as scheduler-interval-floor / scheduler-backup-interval-
// floor — the REAL helper and the REAL route gate block are sliced from
// source and evaluated, then exercised behaviorally.
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 helper + the REAL fire-floor mirror decision function, sliced
// whole (they sit next to each other above scheduleToCron). The slice starts
// at the floor CONSTANTS because the helper's clamped seconds arm and the
// mirror function read them at call time — the same window
// scheduler-interval-floor and scheduler-jobdata-bounds slice.
// ---------------------------------------------------------------------------
const { schedulerCronMinGapSeconds, scheduleToCron, schedulerStoredRecurrenceFloorViolation } = new Function(
sliceFrom(indexSource, "const SCHEDULER_MIN_INTERVAL_SECONDS", "\nasync function shutdownScheduler(", "wrap helper") +
"\nreturn { schedulerCronMinGapSeconds, scheduleToCron, schedulerStoredRecurrenceFloorViolation };"
)();
const FLOOR_MATCH = (name) => {
const m = indexCode.match(new RegExp(`const ${name} = (\\d+);`));
assert.ok(m, `${name} must be declared in index.js`);
return parseInt(m[1], 10);
};
const SCHEDULER_MIN_INTERVAL_SECONDS = FLOOR_MATCH("SCHEDULER_MIN_INTERVAL_SECONDS");
const SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS = FLOOR_MATCH("SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS");
const SCHEDULER_AGENT_MIN_INTERVAL_SECONDS = FLOOR_MATCH("SCHEDULER_AGENT_MIN_INTERVAL_SECONDS");
test("helper, minutes: the wrap gap is the minimum, not the requested step", () => {
const cases = {
// m: smallest actual gap in seconds (fires at 0, m, ..., lastFire; wrap = 60 - lastFire)
"59": 60, // fires :00 and :59 — the reported bypass
"7": 240, // gaps 7×8 then 4
"5": 300, // exact divisor at the backup floor
"6": 360, // exact divisor above it
"25": 600, // fires 0,25,50 → wrap 10 min
"30": 1800, // fires :00 and :30
"55": 300, // wrap exactly AT the floor (passes, not below)
"1": 60, // every minute
"2": 120,
};
for (const [value, expected] of Object.entries(cases)) {
assert.strictEqual(schedulerCronMinGapSeconds("minutes", value), expected, `minutes ${value}`);
}
});
test("helper, minutes: non-numeric keeps scheduleToCron's legacy 5-minute default", () => {
for (const bad of ["abc", "", undefined, null]) {
assert.strictEqual(schedulerCronMinGapSeconds("minutes", bad), 300, JSON.stringify(bad));
}
});
test("helper, hourly: 1..23 wrap-corrected, 24 is the daily special case, above 24 is inexpressible", () => {
const cases = {
"1": 3600,
"2": 7200,
"5": 14400, // */5 fires 0,5,10,15,20 → wrap 4h — the hourly wrap trap
"12": 43200,
"23": 3600, // the clamp target: fires 00:00 and 23:00
"24": 86400, // scheduleToCron maps 24 to daily-at-midnight
};
for (const [value, expected] of Object.entries(cases)) {
assert.strictEqual(schedulerCronMinGapSeconds("hourly", value), expected, `hourly ${value}`);
}
for (const inexpressible of ["25", "999", "100000"]) {
assert.strictEqual(schedulerCronMinGapSeconds("hourly", inexpressible), null, `hourly ${inexpressible}`);
}
// NaN and non-positive clamp to */1 exactly like scheduleToCron.
for (const legacy of ["abc", undefined, null, "0", "-5"]) {
assert.strictEqual(schedulerCronMinGapSeconds("hourly", legacy), 3600, JSON.stringify(legacy));
}
});
test("helper, seconds: the arm clamps exactly like scheduleToCron — the predicted gap is the STORED pattern's gap", () => {
// Conscious contract update (adpanel:scheduler-fire-floor-mirror): the arm
// used to return the RAW parsed value, which let the fire-time mirror
// permanently disable a create the route had accepted — at the time the
// route had NO generic seconds gate, so raw "3" was ACCEPTED and
// scheduleToCron stored it as every 10000ms (the 10s floor); since
// adpanel:schedule-input-validation the route 400s raw "3", but pre-gate
// stored jobs keep the clamped pattern. The pins mirror the stored pattern:
assert.strictEqual(schedulerCronMinGapSeconds("seconds", "3"), SCHEDULER_MIN_INTERVAL_SECONDS, "raw sub-floor value predicts the clamped stored gap");
assert.strictEqual(schedulerCronMinGapSeconds("seconds", "30"), 30);
assert.strictEqual(schedulerCronMinGapSeconds("seconds", "abc"), 30, "legacy NaN default");
});
test("helper, daily/weekly: a large constant stands in (DST can only shrink a day to ~23h)", () => {
assert.strictEqual(schedulerCronMinGapSeconds("daily", undefined), 23 * 3600);
assert.strictEqual(schedulerCronMinGapSeconds("weekly", "1"), 23 * 3600);
});
// ---------------------------------------------------------------------------
// adpanel:scheduler-fire-floor-mirror — the REAL fire-time decision function,
// sliced whole above and exercised behaviorally (the mirror previously had NO
// behavioral test). The core regression this pins: a stored generic seconds
// "3" (accepted by the create route before it had a generic seconds gate;
// since adpanel:schedule-input-validation the route 400s it, but pre-gate
// jobs persist in Redis) is stored by scheduleToCron as the 10s-floor
// pattern — the fire must accept it too, never permanently disable such a
// schedule on its first fire.
// ---------------------------------------------------------------------------
function mirrorJob(actionType, scheduleType, scheduleValue, withRepeat = true) {
const job = { data: { actionType, scheduleType, scheduleValue } };
if (withRepeat) job.opts = { repeat: {} };
return job;
}
test("mirror, the false-disable regression: a stored generic seconds '3' schedule (created under the pre-gate contract, stored as the 10s-floor pattern) must NOT be disabled on its first fire", () => {
// Precondition: the fire-time parse keeps its clamps (the create route now
// 400s raw "3" per adpanel:schedule-input-validation, but pre-gate stored
// jobs persist in Redis with the clamped pattern — every 10000ms).
assert.strictEqual(scheduleToCron("seconds", "3").ms, 10 * 1000, "precondition: the unchanged fire-time parse stores the clamped 10s pattern for raw '3'");
assert.strictEqual(SCHEDULER_MIN_INTERVAL_SECONDS, 10);
assert.strictEqual(
schedulerStoredRecurrenceFloorViolation(mirrorJob("console_command", "seconds", "3")),
null,
"stored pre-gate, fire must accept"
);
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("server_start", "seconds", "3")), null);
});
test("mirror, backup keeps its 300s cost-class floor: seconds '3' is a violation", () => {
assert.strictEqual(
schedulerStoredRecurrenceFloorViolation(mirrorJob("backup", "seconds", "3")),
"sub-floor recurrence interval"
);
});
test("mirror, legacy sub-floor agent row: seconds '10' (stored before the 300s agent floor) is disabled", () => {
assert.strictEqual(
schedulerStoredRecurrenceFloorViolation(mirrorJob("agent_prompt", "seconds", "10")),
"sub-floor recurrence interval"
);
});
test("mirror, allowed current creates pass: backup minutes 5/25, hourly 23, daily/weekly, console seconds 30", () => {
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("backup", "minutes", "5")), null);
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("backup", "minutes", "25")), null);
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("agent_prompt", "hourly", "23")), null);
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("backup", "daily", undefined)), null);
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("console_command", "weekly", "1")), null);
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("console_command", "seconds", "30")), null);
});
test("mirror, one-time job (no opts.repeat) never violates — the repeat-identity guard", () => {
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("backup", "seconds", "3", false)), null);
});
test("mirror, helper-null (inexpressible hourly '999') passes — no false disable", () => {
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(mirrorJob("agent_prompt", "hourly", "999")), null);
});
test("mirror, missing scheduleType fails open (the helper's daily/weekly default arm)", () => {
assert.strictEqual(
schedulerStoredRecurrenceFloorViolation({ data: { actionType: "console_command" }, opts: { repeat: {} } }),
null
);
});
// ---------------------------------------------------------------------------
// The REAL route gate (backup/agent floor blocks + the wrap re-check),
// evaluated with injected fakes — same harness shape as
// scheduler-backup-interval-floor.test.js.
// ---------------------------------------------------------------------------
function createRouteSlice(source) {
return sliceFrom(
source,
'app.post("/api/scheduler/:serverName/tasks"',
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
"scheduler create route"
);
}
const gateBody = sliceFrom(
createRouteSlice(indexCode),
'if (actionType === "backup") {',
"const rawTaskName = String(",
"wrap-floor route gate"
);
const runGate = new Function(
"actionType", "scheduleType", "scheduleValue", "res",
"SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS", "SCHEDULER_AGENT_MIN_INTERVAL_SECONDS",
"SCHEDULER_MIN_INTERVAL_SECONDS", "schedulerCronMinGapSeconds",
`"use strict";
${gateBody}
return { allowed: true };`
);
function gate(actionType, scheduleType, scheduleValue) {
const sent = {};
const res = {
status(code) {
sent.code = code;
return { json(body) { sent.body = body; return body; } };
}
};
const result = runGate(
actionType, scheduleType, scheduleValue, res,
SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS, SCHEDULER_AGENT_MIN_INTERVAL_SECONDS,
SCHEDULER_MIN_INTERVAL_SECONDS, schedulerCronMinGapSeconds
);
return { result, sent };
}
// The final ALLOWED minutes set for the 5-minute-floor actions (backup and
// the two agent actions): every value whose stored */m pattern never gaps
// below 300s — the exact divisors ≥ 5 plus the values whose wrap gap stays
// ≥ 5 (e.g. 9, 11, 13, 25, 55).
const ALLOWED_FIVE_MINUTE_FLOOR_MINUTES = ["5", "6", "9", "10", "11", "12", "13", "15", "16", "17", "18", "20", "21", "22", "23", "24", "25", "26", "27", "30", "31", "35", "40", "45", "50", "55"];
// The final DISALLOWED set: below the raw floor (1-4), or raw-passing but
// wrap-violating.
const DISALLOWED_FIVE_MINUTE_FLOOR_MINUTES = ["1", "2", "3", "4", "7", "8", "14", "19", "28", "29", "56", "57", "58", "59"];
test("backup minutes: the full allowed set passes and the full disallowed set 400s", () => {
for (const good of ALLOWED_FIVE_MINUTE_FLOOR_MINUTES) {
const { result, sent } = gate("backup", "minutes", good);
assert.deepStrictEqual(sent, {}, `minutes ${good} must pass`);
assert.deepStrictEqual(result, { allowed: true });
}
// Below the raw floor the ORIGINAL raw check still owns the rejection and
// its message (the wrap gate sits after it).
for (const rawBad of ["1", "2", "3", "4"]) {
const { sent } = gate("backup", "minutes", rawBad);
assert.strictEqual(sent.code, 400, `minutes ${rawBad} must 400`);
assert.match(sent.body.error, /backup tasks must run at most every 5 minutes/, `minutes ${rawBad}`);
}
// Raw-passing but wrap-violating values get the wrap message.
for (const wrapBad of ["7", "8", "14", "19", "28", "29", "56", "57", "58", "59"]) {
const { sent } = gate("backup", "minutes", wrapBad);
assert.strictEqual(sent.code, 400, `minutes ${wrapBad} must 400 (raw ≥ 300 but the wrap gap is smaller)`);
assert.match(sent.body.error, /wraps at the hour boundary/, `minutes ${wrapBad}`);
}
});
test("agent actions get the same wrap re-check through their own 5-minute floor", () => {
for (const actionType of ["planner_next_to_agent", "agent_prompt"]) {
const { sent: ok } = gate(actionType, "minutes", "15");
assert.deepStrictEqual(ok, {}, `${actionType} minutes 15 must pass`);
const { sent } = gate(actionType, "minutes", "59");
assert.strictEqual(sent.code, 400, `${actionType} minutes 59 must 400`);
assert.match(sent.body.error, /wraps at the hour boundary/);
}
});
test("backup/agent hourly: 1..23 pass, 24 passes (daily special case), above 24 is rejected as inexpressible", () => {
for (const actionType of ["backup", "planner_next_to_agent", "agent_prompt"]) {
for (const good of ["1", "2", "5", "12", "23", "24"]) {
const { sent } = gate(actionType, "hourly", good);
assert.deepStrictEqual(sent, {}, `${actionType} hourly ${good} must pass`);
}
for (const bad of ["25", "999"]) {
const { sent } = gate(actionType, "hourly", bad);
assert.strictEqual(sent.code, 400, `${actionType} hourly ${bad} must 400 (the old silent clamp-to-23 made it twice daily)`);
assert.strictEqual(sent.body.error, "hourly intervals are expressible only from 1 to 23 hours");
}
}
});
test("generic actions keep the 10s floor: UI minutes (1, 2, 5, 59) pass, but inexpressible hourly values are still rejected", () => {
assert.strictEqual(SCHEDULER_MIN_INTERVAL_SECONDS, 10);
for (const actionType of ["console_command", "create_file", "server_start"]) {
for (const good of ["1", "2", "5", "59"]) {
// Under a 10s floor no minutes value can wrap below 60s — the minutes
// arm only ever fires for the 5-minute floors.
const { sent } = gate(actionType, "minutes", good);
assert.deepStrictEqual(sent, {}, `${actionType} minutes ${good} must pass (generic 10s floor)`);
}
for (const bad of ["25", "999"]) {
const { sent } = gate(actionType, "hourly", bad);
assert.strictEqual(sent.code, 400, `${actionType} hourly ${bad} must 400`);
assert.strictEqual(sent.body.error, "hourly intervals are expressible only from 1 to 23 hours");
}
}
});
test("seconds are untouched: the raw numeric floor still owns them, the wrap gate never runs", () => {
const { sent: under } = gate("backup", "seconds", "299");
assert.strictEqual(under.code, 400);
assert.match(under.body.error, /backup tasks must run at most every 5 minutes/, "the raw seconds message, not the wrap message");
const { sent: at } = gate("backup", "seconds", "300");
assert.deepStrictEqual(at, {});
const { sent: generic } = gate("console_command", "seconds", "10");
assert.deepStrictEqual(generic, {});
});
test("once/daily/weekly never reach the wrap re-check", () => {
for (const scheduleType of ["once", "daily", "weekly"]) {
const { sent } = gate("backup", scheduleType, "0");
assert.deepStrictEqual(sent, {}, `${scheduleType} must pass`);
}
});
// ---------------------------------------------------------------------------
// Worker-side safety: scheduleToCron's clamps stay exactly as shipped
// ---------------------------------------------------------------------------
test("scheduleToCron keeps its clamps (worker-side safety for pre-gate stored jobs)", () => {
assert.strictEqual(scheduleToCron("minutes", "59"), "*/59 * * * *");
assert.strictEqual(scheduleToCron("hourly", "999"), "0 */23 * * *");
assert.strictEqual(scheduleToCron("hourly", "24"), "0 0 * * *");
assert.strictEqual(scheduleToCron("minutes", "70"), "*/59 * * * *");
});
// ---------------------------------------------------------------------------
// Wiring: the wrap re-check sits after both per-action floor blocks and
// before any quota/lock/job-creation work
// ---------------------------------------------------------------------------
test("the wrap re-check is wired after the per-action floors and before the name gate/quota/lock", () => {
// RAW slice: the constraint comment must be present verbatim.
const route = createRouteSlice(indexSource);
const codeRoute = createRouteSlice(indexCode);
assert.strictEqual(
codeRoute.includes("schedulerWrapFloorSeconds"),
true,
"the wrap re-check must be live code in the route"
);
const wrapAt = route.indexOf("schedulerCronMinGapSeconds(scheduleType, scheduleValue)");
assert.ok(wrapAt > 0, "the wrap re-check must call the named helper");
const backupFloorAt = route.indexOf('if (actionType === "backup") {');
const agentFloorAt = route.indexOf('if (actionType === "planner_next_to_agent" || actionType === "agent_prompt") {');
const taskNameAt = route.indexOf("const rawTaskName = String(");
const quotaAt = route.indexOf("resolveSchedulerMaxSchedules(serverEntry)");
const lockAt = route.indexOf("withSchedulerCreateLock(");
assert.ok(wrapAt > backupFloorAt, "the wrap re-check must follow the backup floor block");
assert.ok(wrapAt > agentFloorAt, "the wrap re-check must follow the agent floor block");
assert.ok(wrapAt < taskNameAt, "the wrap re-check must reject before anything is stored");
assert.ok(wrapAt < quotaAt && wrapAt < lockAt, "request-shape garbage must not pay the quota scan or hold the create lock");
assert.ok(
route.includes("adpanel:scheduler-cron-wrap-floor"),
"the route gate must carry the constraint comment"
);
});
test("the helper is declared exactly once, next to scheduleToCron, before the route uses it", () => {
const declCount = (indexCode.match(/function schedulerCronMinGapSeconds\(/g) || []).length;
assert.strictEqual(declCount, 1, "one implementation, one home");
const declAt = indexCode.indexOf("function schedulerCronMinGapSeconds(");
const scheduleToCronAt = indexCode.indexOf("function scheduleToCron(");
const routeAt = indexCode.indexOf("schedulerCronMinGapSeconds(scheduleType, scheduleValue)");
assert.ok(declAt < scheduleToCronAt, "the helper lives directly above scheduleToCron");
assert.ok(routeAt > declAt, "the route must reference the declared helper (no use-before-declare at boot)");
});
// ---------------------------------------------------------------------------
// adpanel:scheduler-fire-floor-mirror — the worker call-site wiring
// (source-window pin per repo convention: index.js boots servers on require,
// so the processor is sliced from source between well-anchored markers).
// ---------------------------------------------------------------------------
function workerProcessorSlice(source) {
// adpanel:scheduler-backup-starvation — the processor now takes the
// (job, token) signature: the token is the worker's lock token the backup
// deferral gate needs for job.moveToDelayed. The slice markers track that
// signature additively; the assertions below are unchanged.
return sliceFrom(
source,
'schedulerWorker = new Worker("adpanel-scheduler", async (job, token) => {',
'schedulerWorker.on("completed"',
"scheduler worker processor"
);
}
test("the worker processor runs the fire-mirror before the action switch and disables+throws on a violation", () => {
const workerCode = workerProcessorSlice(indexCode);
const callAt = workerCode.indexOf("const floorViolation = schedulerStoredRecurrenceFloorViolation(job);");
assert.notStrictEqual(callAt, -1, "the worker processor must consult schedulerStoredRecurrenceFloorViolation(job)");
const switchAt = workerCode.indexOf("switch (actionType) {");
assert.notStrictEqual(switchAt, -1, "the worker's action dispatch switch must exist");
assert.ok(
callAt < switchAt,
"the fire-mirror must run BEFORE the action switch — no action case may execute before the STORED recurrence has passed its floor"
);
const gate = workerCode.slice(callAt, switchAt);
assert.ok(
gate.includes("if (floorViolation) {"),
"a non-null violation result must be gated, never ignored"
);
assert.ok(
gate.includes("await disableRecurringScheduleForJob(job, floorViolation);"),
"a violation must disable the recurrence through the ONE disable machinery, with the helper's reason"
);
assert.ok(
gate.includes('throw new Error("Stored recurrence interval is below the minimum allowed interval");'),
"a violation must fail the run AFTER the disable — the job itself never executes below the floor"
);
// One call site: the decision lives in the helper (behaviorally tested
// above); the worker stays a bare disable-then-throw and cannot drift.
assert.strictEqual(
indexCode.split("const floorViolation = schedulerStoredRecurrenceFloorViolation(job);").length - 1,
1,
"the mirror call must exist exactly once in index.js — the worker processor is its only caller"
);
// The constraint comment rides the worker site in the RAW source.
assert.ok(
workerProcessorSlice(indexSource).includes("adpanel:scheduler-fire-floor-mirror"),
"the worker mirror site must carry the adpanel:scheduler-fire-floor-mirror constraint comment"
);
});