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

@@ -0,0 +1,248 @@
"use strict";
// Regression tests for the backup-specific scheduler recurrence floor.
//
// Bug (security audit): the generic floor SCHEDULER_MIN_INTERVAL_SECONDS
// (10s) also applied to actionType "backup" tasks — and every backup fire
// is a full server-directory copy on the node, so a tenant could register a
// backup recurring every 10 seconds as a disk/IO abuse vector, bounded only
// by their maxSchedules quota.
//
// Fix: SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS (300) is enforced in the
// create route (POST /api/scheduler/:serverName/tasks) on the raw body
// values that build the schedule: scheduleType "seconds" needs an interval
// >= 300s, "minutes" needs >= 5 minutes; hourly/daily/weekly are inherently
// >= 1h and "once" is a single run, so both stay unrestricted. Non-numeric
// values are rejected too, because scheduleToCron's legacy fallbacks (30s /
// 5m) would otherwise slip a backup under or onto the floor by default.
// The gate lives in the route — NOT in scheduleToCron — because that helper
// never sees actionType and every other action must keep the 10s floor.
//
// index.js boots servers on require and cannot be loaded in-process, so —
// same technique as scheduler-interval-floor / scheduler-hardening — the
// REAL gate block and scheduleToCron 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);
}
function createRouteSlice(source) {
return sliceFrom(
source,
'app.post("/api/scheduler/:serverName/tasks"',
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
"scheduler create route"
);
}
// The shipped floor value, read from source — not a test-local copy.
const BACKUP_FLOOR_MATCH = indexCode.match(/const SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS = (\d+);/);
assert.ok(BACKUP_FLOOR_MATCH, "SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS must be declared in index.js");
const SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS = parseInt(BACKUP_FLOOR_MATCH[1], 10);
// Slice the REAL gate block (the `if (actionType === "backup") {...}` form
// validation inside the create route) and evaluate it with injected fakes:
// a rejected (actionType, scheduleType, scheduleValue) returns the 400's
// json payload, an accepted one returns { allowed: true }.
// adpanel:scheduler-cron-wrap-floor — the slice window now ALSO contains the
// wrap-floor re-check that follows the per-action floor blocks, so the
// harness injects the real schedulerCronMinGapSeconds helper (sliced from
// source, not a copy) and the two other floor constants that block reads.
const gateBody = sliceFrom(
createRouteSlice(indexCode),
'if (actionType === "backup") {',
"const rawTaskName = String(",
"backup recurrence gate"
);
const { schedulerCronMinGapSeconds } = new Function(
sliceFrom(indexSource, "function schedulerCronMinGapSeconds(", "\nfunction scheduleToCron(", "schedulerCronMinGapSeconds") +
"\nreturn { schedulerCronMinGapSeconds };"
)();
const AGENT_FLOOR_MATCH = indexCode.match(/const SCHEDULER_AGENT_MIN_INTERVAL_SECONDS = (\d+);/);
assert.ok(AGENT_FLOOR_MATCH, "SCHEDULER_AGENT_MIN_INTERVAL_SECONDS must be declared in index.js");
const runGate = new Function(
"actionType", "scheduleType", "scheduleValue", "SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS", "res",
"SCHEDULER_AGENT_MIN_INTERVAL_SECONDS", "SCHEDULER_MIN_INTERVAL_SECONDS", "schedulerCronMinGapSeconds",
`"use strict";
${gateBody}
return { allowed: true };`
);
function fakeRes() {
const sent = {};
const res = {
status(code) {
sent.code = code;
return {
json(body) {
sent.body = body;
return { sent: true, code, body };
}
};
}
};
return { res, sent };
}
function gate(actionType, scheduleType, scheduleValue) {
const { res, sent } = fakeRes();
const result = runGate(
actionType, scheduleType, scheduleValue, SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS, res,
parseInt(AGENT_FLOOR_MATCH[1], 10), SCHEDULER_MIN_INTERVAL_SECONDS, schedulerCronMinGapSeconds
);
return { result, sent };
}
// The real scheduleToCron (constant + helper sliced together, same as
// scheduler-interval-floor), so accepted backups can be proven to build a
// recurrence >= the floor.
const { SCHEDULER_MIN_INTERVAL_SECONDS, scheduleToCron } = new Function(
sliceFrom(indexSource, "const SCHEDULER_MIN_INTERVAL_SECONDS", "\nasync function shutdownScheduler(", "scheduleToCron") +
"\nreturn { SCHEDULER_MIN_INTERVAL_SECONDS, scheduleToCron };"
)();
// ---------------------------------------------------------------------------
// The reported hole: backups recurring faster than every 5 minutes
// ---------------------------------------------------------------------------
test("backup seconds intervals below 300s are rejected with a 400 before any job is created", () => {
for (const bad of ["1", "10", "30", "60", "299"]) {
const { result, sent } = gate("backup", "seconds", bad);
assert.strictEqual(sent.code, 400, `scheduleValue ${bad} must 400`);
assert.strictEqual(sent.body.ok, false, `scheduleValue ${bad} must not be ok`);
assert.match(sent.body.error, /backup tasks must run at most every 5 minutes/);
assert.strictEqual(result.sent, true, `scheduleValue ${bad} must not fall through the gate`);
}
});
test("backup minute intervals below 5 minutes are rejected with a 400", () => {
for (const bad of ["1", "2", "4"]) {
const { result, sent } = gate("backup", "minutes", bad);
assert.strictEqual(sent.code, 400, `scheduleValue ${bad} must 400`);
assert.match(sent.body.error, /backup tasks must run at most every 5 minutes/);
assert.strictEqual(result.sent, true, `scheduleValue ${bad} must not fall through the gate`);
}
});
test("non-numeric backup intervals are rejected, not silently defaulted under the floor", () => {
// scheduleToCron's legacy fallback for garbage seconds is 30s — under the
// backup floor — so the gate must fail closed instead of letting the
// default through.
for (const bad of ["abc", "", undefined, null]) {
const { sent } = gate("backup", "seconds", bad);
assert.strictEqual(sent.code, 400, JSON.stringify(bad));
const minutesRes = gate("backup", "minutes", bad);
assert.strictEqual(minutesRes.sent.code, 400, JSON.stringify(bad));
}
});
test("backup intervals at or above the floor pass the gate AND build a recurrence >= 300s", () => {
for (const good of ["300", "600", "3600"]) {
const { result, sent } = gate("backup", "seconds", good);
assert.deepStrictEqual(sent, {}, `scheduleValue ${good} must not be rejected`);
assert.deepStrictEqual(result, { allowed: true });
assert.strictEqual(scheduleToCron("seconds", good).ms, parseInt(good, 10) * 1000);
assert.ok(scheduleToCron("seconds", good).ms >= 300000, `scheduleValue ${good} must recur >= 300s`);
}
for (const good of ["5", "15", "30"]) {
const { result, sent } = gate("backup", "minutes", good);
assert.deepStrictEqual(sent, {}, `scheduleValue ${good} must not be rejected`);
assert.deepStrictEqual(result, { allowed: true });
assert.strictEqual(scheduleToCron("minutes", good), `*/${good} * * * *`);
}
});
// adpanel:scheduler-cron-wrap-floor — the raw minutes check above passes any
// value ≥ 5, but a cron step WRAPS at the hour boundary: */59 fires at :00
// AND :59 (two full backup copies an hour, 1 minute apart) and */7 loses 3
// minutes on every wrap. The route re-checks the 5-minute floor against the
// smallest ACTUAL gap (schedulerCronMinGapSeconds) and rejects.
test("backup minute values whose cron pattern wraps below 5 minutes are rejected with the wrap message", () => {
// 59 → fires :00 and :59 (wrap gap 1 min); 7 → gaps 7×8 then 4; 56 → wrap 4; 28 → wrap 4.
for (const bad of ["59", "7", "56", "28"]) {
const { result, sent } = gate("backup", "minutes", bad);
assert.strictEqual(sent.code, 400, `scheduleValue ${bad} must 400 (raw ${parseInt(bad, 10) * 60}s ≥ 300 but the wrap gap is smaller)`);
assert.match(sent.body.error, /wraps at the hour boundary/);
assert.match(sent.body.error, /pick a value whose gaps all stay at least 5 minutes/);
assert.strictEqual(result.sent, true, `scheduleValue ${bad} must not fall through the gate`);
}
// The wrap message names the actual smallest gap in minutes.
const { sent } = gate("backup", "minutes", "59");
assert.match(sent.body.error, /smallest actual gap is 1 minute\(s\)/);
const seven = gate("backup", "minutes", "7");
assert.match(seven.sent.body.error, /smallest actual gap is 4 minute\(s\)/);
});
test("hourly/daily/weekly backups pass (inherently >= 1h) and one-time backups are unrestricted", () => {
for (const scheduleType of ["hourly", "daily", "weekly", "once"]) {
const { result, sent } = gate("backup", scheduleType, "1");
assert.deepStrictEqual(sent, {}, `${scheduleType} backups must not be rejected`);
assert.deepStrictEqual(result, { allowed: true });
}
});
test("non-backup actions keep the generic 10s floor (only backups are bounded to 5 minutes)", () => {
for (const actionType of ["console_command", "server_stop", "create_file"]) {
const { result, sent } = gate(actionType, "seconds", "10");
assert.deepStrictEqual(sent, {}, `${actionType} must keep the 10s floor`);
assert.deepStrictEqual(result, { allowed: true });
}
assert.strictEqual(SCHEDULER_MIN_INTERVAL_SECONDS, 10, "the generic floor itself must stay at 10");
});
// ---------------------------------------------------------------------------
// Source-level: the gate is wired into the create route, unbypassably
// ---------------------------------------------------------------------------
test("the create route enforces the gate through the named backup floor constant", () => {
const route = createRouteSlice(indexCode);
assert.ok(
route.includes("SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS"),
"the create route must clamp through the named constant, not a magic number"
);
assert.ok(
indexCode.includes("const SCHEDULER_BACKUP_MIN_INTERVAL_SECONDS = 300;"),
"the backup floor must be declared at 300 (5 minutes)"
);
assert.ok(
route.includes('if (actionType === "backup") {'),
"the gate must key on the validated actionType, not a UI assumption"
);
});
test("the gate reads the raw body values after both whitelists and before quota/job creation", () => {
const route = createRouteSlice(indexCode);
const gatePos = route.indexOf('if (actionType === "backup") {');
assert.ok(gatePos > route.indexOf("if (!validActions.includes(actionType))"), "gate must run after the actionType whitelist");
assert.ok(gatePos > route.indexOf("if (!validScheduleTypes.includes(scheduleType))"), "gate must run after the scheduleType whitelist");
assert.ok(gatePos < route.indexOf("resolveSchedulerMaxSchedules(serverEntry)"), "gate must run before the quota's Redis roundtrips");
assert.ok(gatePos < route.indexOf("schedulerQueue.add("), "gate must reject BEFORE any job is created");
});