Files
Kelx/tests/scheduler-schedule-input-validation.test.js
2026-11-30 16:32:37 +00:00

365 lines
19 KiB
JavaScript

"use strict";
// Regression tests for adpanel:schedule-input-validation — the scheduler
// create route's per-type strict schedule-field gate.
//
// Bug (owner-verified, mis-schedule): the recurring schedule inputs were
// silently CLAMPED into safe cron ranges instead of validated. Weekly
// `parseInt(scheduleValue, 10) || 0` clamped 0-6, so a "garbage" day became
// Saturday 23:59 (the "99:99" time clamped by parseCronTimeFields) and "-1"
// became Sunday; hourly 0/NaN became every hour; minutes garbage became */5;
// a sub-floor seconds value became the 10s floor. The 200 response does not
// echo the effective cron, so the creator learned the real pattern only from
// the task list. Cron-range safety was never the issue — the clamps kept
// every stored pattern valid — so the fix is a contract fix: the CREATE
// route validates strictly and 400s in the same { ok:false } family as the
// backup/agent floor messages, while the FIRE-time parse stays lenient for
// schedules stored before the contract change (a stored value that only
// exists because of the old clamp keeps firing its old pattern instead of
// failing into the disable streak).
//
// UI value shapes the shipped client legitimately sends (the gate accepts
// exactly these, per the "validate what the UI sends" contract):
// - bot.js createSchedulerTask (~7095-7106): seconds/minutes/hourly/
// weekly scheduleValue come from <select> .value with digit-only
// options; daily sends NO scheduleValue at all; weekly/daily
// scheduleTime come from <input type="time"> values (HTML time inputs
// emit zero-padded "HH:MM", never "H:MM" — a single-digit hour is still
// accepted server-side as unambiguous leniency that cannot change the
// fire minute); "once" sends neither field (its contract is the
// separately validated scheduledTimestamp).
// - bot.ejs option lists: schedulerSecondsInterval 10/15/30/45 (min 10),
// schedulerMinutesInterval 1..30 (min 1), schedulerHourlyInterval
// 1..24 (min 1 — the UI never produces 0, so 0 is NOT a legal "every
// hour" spelling and 400s), schedulerWeeklyDay "0".."6".
// - daily's form is a bare time input and scheduleToCron's daily arm
// never reads scheduleValue, so daily validates only its time (a daily
// interval requirement would 400 every shipped daily task).
//
// The gate sits AFTER the backup/agent floor blocks (those keep their
// cost-class messages for the values they bound — non-numeric backup
// intervals still get the backup floor's message) and well above
// withSchedulerCreateLock (request-shape garbage never pays the quota or
// holds the mutex — the once-timestamp gate's doctrine).
//
// Technique (scheduler-cron-wrap-floor / scheduler-file-actions precedent):
// index.js boots servers on require and cannot be loaded in-process, so the
// REAL route gate block and the REAL parse helpers are sliced from source
// and evaluated with injected fakes; the fire-side leniency pins drive the
// REAL scheduleToCron/parseCronTimeFields and the REAL fire-floor mirror.
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 parse helpers + the REAL fire-time helpers, sliced whole (the
// window starts at the floor constant exactly like scheduler-cron-wrap-
// floor's, so the sliced code is the shipped code).
// ---------------------------------------------------------------------------
const {
scheduleToCron,
parseCronTimeFields,
parseStrictScheduleInteger,
isValidScheduleHhMm,
schedulerCronMinGapSeconds,
schedulerStoredRecurrenceFloorViolation,
SCHEDULER_MIN_INTERVAL_SECONDS: SLICED_MIN_INTERVAL_SECONDS,
} = new Function(
sliceFrom(indexSource, "const SCHEDULER_MIN_INTERVAL_SECONDS", "\nasync function shutdownScheduler(", "schedule parse helpers") +
"\nreturn { scheduleToCron, parseCronTimeFields, parseStrictScheduleInteger, isValidScheduleHhMm, schedulerCronMinGapSeconds, schedulerStoredRecurrenceFloorViolation, SCHEDULER_MIN_INTERVAL_SECONDS };"
)();
// ---------------------------------------------------------------------------
// The REAL create-route per-type gate, sliced from the route (start marker
// is the gate's first two lines — the scheduleToCron weekly branch has a
// different body, so this cannot match the fire-time helper) up to the
// jobdata-bounds shape gate that follows it. Rejected requests return the
// 400 json body; accepted ones return null.
// ---------------------------------------------------------------------------
const strictGateBody = sliceFrom(
indexCode,
'if (scheduleType === "weekly") {\n const weeklyDay = parseStrictScheduleInteger(scheduleValue);',
"if ((scheduleValue != null &&",
"create-route strict schedule gate"
);
const runStrictGate = new Function(
"scheduleType", "scheduleValue", "scheduleTime", "res",
"SCHEDULER_MIN_INTERVAL_SECONDS", "parseStrictScheduleInteger", "isValidScheduleHhMm",
`"use strict";
${strictGateBody}
return null;`
);
function gateCreate(scheduleType, scheduleValue, scheduleTime) {
const sent = {};
const res = {
status(code) {
sent.code = code;
return {
json(body) {
sent.body = body;
return body;
}
};
}
};
const result = runStrictGate(
scheduleType, scheduleValue, scheduleTime, res,
SLICED_MIN_INTERVAL_SECONDS, parseStrictScheduleInteger, isValidScheduleHhMm
);
return { result, sent };
}
function assertRejected(outcome, messagePattern, label) {
assert.strictEqual(outcome.sent.code, 400, `${label} must 400`);
assert.strictEqual(outcome.sent.body.ok, false, `${label} must not be ok`);
assert.match(outcome.sent.body.error, messagePattern, `${label} message`);
assert.strictEqual(outcome.result, outcome.sent.body, `${label} must not fall through the gate`);
}
function assertAccepted(outcome, label) {
assert.strictEqual(outcome.sent.code, undefined, `${label} must not 400`);
assert.strictEqual(outcome.result, null, `${label} must fall through to the next gate`);
}
// ---------------------------------------------------------------------------
// weekly: day integer 0-6 + real HH:MM time (the reported garbage cases)
// ---------------------------------------------------------------------------
test("weekly: garbage day 400s instead of silently becoming Saturday 23:59", () => {
for (const bad of ["garbage", "abc", "", " ", "3abc", "1e3", "7", "99", "-1", "+3", "3.9", "0x2"]) {
assertRejected(gateCreate("weekly", bad, "09:30"), /Invalid weekly day/, `weekly day ${JSON.stringify(bad)}`);
}
});
test("weekly: non-string and absent days 400 (the UI always sends the select value)", () => {
for (const bad of [undefined, null, 3, { day: 3 }, ["3"]]) {
assertRejected(gateCreate("weekly", bad, "09:30"), /Invalid weekly day/, `weekly day ${JSON.stringify(bad)}`);
}
});
test("weekly: every UI day option 0-6 is accepted (trim tolerated)", () => {
for (const good of ["0", "1", "2", "3", "4", "5", "6", " 3 "]) {
assertAccepted(gateCreate("weekly", good, "09:30"), `weekly day ${JSON.stringify(good)}`);
}
});
test("weekly: garbage time 400s instead of clamping to 23:59 / defaulting to 00:00", () => {
for (const bad of ["99:99", "24:00", "12:60", "12:5", "12:345", "12:34:56", "10", "", "abc", "09:30am", undefined, null, 930]) {
assertRejected(gateCreate("weekly", "3", bad), /Invalid weekly time/, `weekly time ${JSON.stringify(bad)}`);
}
});
test("weekly: real HH:MM times pass, including a single-digit hour", () => {
for (const good of ["00:00", "23:59", "09:05", "9:30", " 9:30 "]) {
assertAccepted(gateCreate("weekly", "3", good), `weekly time ${JSON.stringify(good)}`);
}
});
// ---------------------------------------------------------------------------
// daily: time-only (the UI's daily form sends NO scheduleValue — bot.js
// ~7101-7102 — and scheduleToCron's daily arm never reads one, so a daily
// interval requirement would 400 every shipped daily task)
// ---------------------------------------------------------------------------
test("daily: garbage or absent time 400s; a real HH:MM passes", () => {
for (const bad of ["99:99", "7:5", "", "abc", undefined, null]) {
assertRejected(gateCreate("daily", undefined, bad), /Invalid daily time/, `daily time ${JSON.stringify(bad)}`);
}
assertAccepted(gateCreate("daily", undefined, "09:30"), "daily valid time");
assertAccepted(gateCreate("daily", undefined, "00:00"), "daily midnight");
});
test("daily: scheduleValue is unconsumed and therefore NOT validated (documented decision)", () => {
// A daily task carrying a (meaningless) scheduleValue must still create —
// the shipped client sends none, and rejecting a present one would only
// break non-shipped clients without closing any mis-schedule: the daily
// fire pattern never reads the field.
assertAccepted(gateCreate("daily", "garbage", "09:30"), "daily ignores scheduleValue");
});
// ---------------------------------------------------------------------------
// hourly: the UI's minimum is 1 (bot.ejs schedulerHourlyInterval options
// start at "1", bot.js falls back to '1'), so 0 is NOT a legal "every hour"
// spelling — 0/NaN/negatives 400; 24 stays legal (scheduleToCron's
// daily-at-midnight special case) and >24 stays the wrap-floor gate's
// verdict (its message fires first for those, earlier in the route)
// ---------------------------------------------------------------------------
test("hourly: 0, negatives and garbage 400 instead of silently becoming every hour", () => {
for (const bad of ["0", "-2", "abc", "", " ", "2.5", "1e1", "1abc", undefined, null, 2]) {
assertRejected(gateCreate("hourly", bad, undefined), /Invalid hourly interval/, `hourly ${JSON.stringify(bad)}`);
}
});
test("hourly: the UI's full 1-24 option range passes", () => {
for (const good of ["1", "2", "3", "4", "6", "8", "12", "24", " 6 "]) {
assertAccepted(gateCreate("hourly", good, undefined), `hourly ${JSON.stringify(good)}`);
}
});
// ---------------------------------------------------------------------------
// minutes: 1-59 (the UI select spans 1..30; >59 has no faithful */N pattern
// and used to clamp to the twice-firing */59; garbage used to become */5)
// ---------------------------------------------------------------------------
test("minutes: 0, negatives, garbage and above the cron field 400", () => {
for (const bad of ["0", "-3", "abc", "", "60", "90", "5abc", undefined, null, 5]) {
assertRejected(gateCreate("minutes", bad, undefined), /Invalid minutes interval/, `minutes ${JSON.stringify(bad)}`);
}
});
test("minutes: 1-59 passes (the wrap-floor gate above still owns wrap semantics)", () => {
for (const good of ["1", "5", "30", "59", " 15 "]) {
assertAccepted(gateCreate("minutes", good, undefined), `minutes ${JSON.stringify(good)}`);
}
});
// ---------------------------------------------------------------------------
// seconds: integer at or above SCHEDULER_MIN_INTERVAL_SECONDS (the UI select
// floors at 10; "3" used to be silently stored as the 10s-floor interval)
// ---------------------------------------------------------------------------
test("seconds: sub-floor, zero, negative and garbage values 400", () => {
for (const bad of ["3", "9", "0", "-100", "abc", "", "10abc", undefined, null, 30]) {
assertRejected(gateCreate("seconds", bad, undefined), /Invalid seconds interval/, `seconds ${JSON.stringify(bad)}`);
}
});
test("seconds: the boundary is the SHIPPED floor constant, and UI values pass", () => {
assert.strictEqual(SLICED_MIN_INTERVAL_SECONDS, 10, "the generic floor must stay at 10 for this contract");
assertAccepted(gateCreate("seconds", "10", undefined), "seconds 10 (exact boundary)");
for (const good of ["15", "30", "45"]) {
assertAccepted(gateCreate("seconds", good, undefined), `seconds ${JSON.stringify(good)}`);
}
});
// ---------------------------------------------------------------------------
// once: untouched — its contract is the separately validated
// scheduledTimestamp, and the shipped client sends neither schedule field
// ---------------------------------------------------------------------------
test("once: no schedule-field validation (junk value/time fields do not 400 here)", () => {
assertAccepted(gateCreate("once", "garbage", "not-a-time"), "once keeps its own timestamp contract");
});
// ---------------------------------------------------------------------------
// Message family: same { ok:false } shape as the backup/agent floors, no
// echo of the raw input, no internal cron internals
// ---------------------------------------------------------------------------
test("every rejection uses the floor-message family and never echoes the input", () => {
const cases = [
["weekly", "garbage", "09:30", /Invalid weekly day/],
["weekly", "3", "99:99", /Invalid weekly time/],
["daily", undefined, "99:99", /Invalid daily time/],
["hourly", "0", undefined, /Invalid hourly interval/],
["minutes", "abc", undefined, /Invalid minutes interval/],
["seconds", "abc", undefined, /Invalid seconds interval/],
];
for (const [scheduleType, scheduleValue, scheduleTime, pattern] of cases) {
const { sent } = gateCreate(scheduleType, scheduleValue, scheduleTime);
assert.deepStrictEqual(Object.keys(sent.body).sort(), ["error", "ok"], `${scheduleType}: floor-family shape`);
assert.ok(!sent.body.error.includes(JSON.stringify(scheduleValue ?? scheduleTime)), `${scheduleType}: no raw echo`);
assert.match(sent.body.error, pattern);
}
});
// ---------------------------------------------------------------------------
// Wiring: the strict gate sits AFTER the backup/agent floors (their
// cost-class messages stay first for the values they bound) and ABOVE the
// create lock (request-shape garbage never pays the quota)
// ---------------------------------------------------------------------------
test("the strict gate is wired after the floors and above the create lock", () => {
const route = sliceFrom(
indexCode,
'app.post("/api/scheduler/:serverName/tasks"',
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
"scheduler create route"
);
const backupFloorAt = route.indexOf('if (actionType === "backup") {');
const wrapFloorAt = route.indexOf("schedulerCronMinGapSeconds(scheduleType, scheduleValue)");
const strictGateAt = route.indexOf('const weeklyDay = parseStrictScheduleInteger(scheduleValue);');
const lockAt = route.indexOf("withSchedulerCreateLock(");
assert.ok(backupFloorAt > -1 && wrapFloorAt > -1 && strictGateAt > -1 && lockAt > -1, "all anchors present");
assert.ok(backupFloorAt < strictGateAt, "the backup/agent floors run first (their messages stay canonical)");
assert.ok(wrapFloorAt < strictGateAt, "the wrap-floor gate runs first (>24 hourly keeps its message)");
assert.ok(strictGateAt < lockAt, "the strict gate sits above withSchedulerCreateLock");
});
test("the route gate delegates to the SAME helpers sliced above (no inline copy)", () => {
assert.ok(strictGateBody.includes("parseStrictScheduleInteger(scheduleValue)"), "day/interval parsing goes through the shared strict parser");
assert.ok(strictGateBody.includes("isValidScheduleHhMm(scheduleTime)"), "time parsing goes through the shared HH:MM validator");
assert.ok(!strictGateBody.includes("Math.min(6"), "no fire-time clamp arithmetic may be re-inlined in the route");
});
// ---------------------------------------------------------------------------
// FIRE side stays lenient — the contract that makes the create-side
// strictness safe: jobs stored BEFORE this gate (whose values only exist
// because of the old clamps) must keep firing their old pattern instead of
// failing into the disable streak. Tightening scheduleToCron would be a
// silent behavior change for working schedules.
// ---------------------------------------------------------------------------
test("fire-time parse is unchanged: pre-contract stored garbage keeps its clamped pattern", () => {
// THE finding example: a weekly task created with garbage scheduleValue +
// "99:99" clamped at create and has been firing on the clamped pattern —
// it must keep firing there after this deploy. The two weekly clamp paths:
// NaN-producing garbage takes the `|| 0` arm (Sunday), out-of-range
// numeric garbage ("9") takes the min/max clamp (Saturday); the time
// clamps to 23:59 either way.
assert.strictEqual(scheduleToCron("weekly", "garbage", "99:99"), "59 23 * * 0");
assert.strictEqual(scheduleToCron("weekly", "9", "99:99"), "59 23 * * 6");
assert.strictEqual(scheduleToCron("weekly", "-1", undefined), "0 0 * * 0");
assert.strictEqual(scheduleToCron("hourly", "0"), "0 */1 * * *");
assert.strictEqual(scheduleToCron("minutes", "abc"), "*/5 * * * *");
assert.strictEqual(scheduleToCron("seconds", "3").ms, 10 * 1000);
assert.deepStrictEqual(parseCronTimeFields("99:99"), [23, 59]);
});
test("fire-time floor mirror does not disable pre-contract stored schedules", () => {
const legacyJob = { data: { actionType: "console_command", scheduleType: "weekly", scheduleValue: "garbage" }, opts: { repeat: {} } };
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(legacyJob), null, "a stored clamped-value schedule must keep firing");
const legacyHourly = { data: { actionType: "server_start", scheduleType: "hourly", scheduleValue: "0" }, opts: { repeat: {} } };
assert.strictEqual(schedulerCronMinGapSeconds("hourly", "0"), 3600, "the helper's legacy clamp mirrors scheduleToCron");
assert.strictEqual(schedulerStoredRecurrenceFloorViolation(legacyHourly), null);
});
test("valid UI shapes still produce the same stored patterns (no drift from the gate)", () => {
assert.strictEqual(scheduleToCron("weekly", "3", "09:30"), "30 9 * * 3");
assert.strictEqual(scheduleToCron("daily", undefined, "09:30"), "30 9 * * *");
assert.strictEqual(scheduleToCron("hourly", "6"), "0 */6 * * *");
assert.strictEqual(scheduleToCron("hourly", "24"), "0 0 * * *");
assert.strictEqual(scheduleToCron("minutes", "30"), "*/30 * * * *");
assert.deepStrictEqual(scheduleToCron("seconds", "30"), { type: "interval", ms: 30000 });
});