480 lines
25 KiB
JavaScript
480 lines
25 KiB
JavaScript
"use strict";
|
|
|
|
// Regression tests for adpanel:scheduler-route-canonical-authz — the three
|
|
// scheduler routes resolved the PRE-canonical name for their access checks.
|
|
//
|
|
// Bug (security review): GET/POST/DELETE /api/scheduler/:serverName/tasks ran
|
|
// userHasAccessToServer + getEffectivePermsForUserOnServer against the
|
|
// sanitized URL form BEFORE findServer canonicalization and never fed the
|
|
// canonical name back. Access rows are keyed on the STORED server name,
|
|
// which on legacy rows is not a fixed point of sanitizeServerToken ("My Bot"
|
|
// vs the URL's "My-Bot") — so a valid subuser of a legacy-named server got
|
|
// 403 on all three routes while admin (the admin bypass inside
|
|
// userHasAccessToServer) saw and managed the same schedules.
|
|
//
|
|
// Fix (all three routes): the findServer lookup is hoisted ABOVE the
|
|
// access/permission checks and resolves the names the checks run against,
|
|
// mirroring the fire-time twin (ensureScheduledJobStillAuthorized,
|
|
// adpanel:scheduler-canonical-authz):
|
|
// - accessServerName = String(serverEntry?.name || serverName || "").trim()
|
|
// — the STORED name for the checks, falling back to the raw sanitized
|
|
// name on a findServer miss/throw (fail closed for legacy names, never a
|
|
// 404 on lookup throw);
|
|
// - canonicalServer (the sanitizeServerToken form job data is stored
|
|
// under) keeps feeding job matching / job data / the action-token
|
|
// resource, exactly as before;
|
|
// - exactly ONE findServer lookup per route (the POST quota's duplicate
|
|
// in-lock lookup is gone; it reads the hoisted row's maxSchedules).
|
|
//
|
|
// Everything else keeps its order: authentication 401s first; the GET
|
|
// route's 503 scheduler-unavailable check stays after the perms check; the
|
|
// POST/DELETE action-token anchoring stays AFTER canonicalization; the
|
|
// POST timestamp/floor gates all stay above the create lock.
|
|
//
|
|
// index.js boots servers on require and cannot be loaded in-process, so —
|
|
// same technique as scheduler-delete-hardening.test.js — each REAL route
|
|
// handler is sliced from source and evaluated with injected fakes, 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);
|
|
}
|
|
|
|
const getRouteSource = sliceFrom(
|
|
indexSource,
|
|
'app.get("/api/scheduler/:serverName/tasks"',
|
|
'app.post("/api/scheduler/:serverName/tasks"',
|
|
"scheduler get route"
|
|
);
|
|
const postRouteSource = sliceFrom(
|
|
indexSource,
|
|
'app.post("/api/scheduler/:serverName/tasks"',
|
|
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
|
|
"scheduler create route"
|
|
);
|
|
const deleteRouteSource = sliceFrom(
|
|
indexSource,
|
|
'app.delete("/api/scheduler/:serverName/tasks/:taskId"',
|
|
'app.get("/api/scheduler/status"',
|
|
"scheduler delete route"
|
|
);
|
|
|
|
// The legacy-name scenario the fix targets: the URL sanitizes to "My-Bot",
|
|
// findServer resolves the row through an alias, and the row's STORED name —
|
|
// what access rows are keyed on — is "My Bot".
|
|
const LEGACY_ROW = { id: 7, name: "My Bot", bot: "My-Bot" };
|
|
|
|
// Builds the fakes for one route evaluation. findServerImpl decides
|
|
// resolution (row / null / throw); accessNames is the user's access list
|
|
// (lowercased compare, like userHasAccessToServer); perms is the effective
|
|
// projection getEffectivePermsForUserOnServer returns. Every check records
|
|
// the exact (name, order) it was called with.
|
|
function makeRouteHarness(routeSource, method, { findServerImpl, accessNames = [], perms = {} }) {
|
|
const calls = [];
|
|
const responses = [];
|
|
const app = { [method](_path, ...handlers) { app.handler = handlers[handlers.length - 1]; } };
|
|
const sanitizeServerName = (raw) => String(raw || "").trim().replace(/\s+/g, "-");
|
|
const handler = new Function(
|
|
"app", "isAuthenticated", "sanitizeServerName", "userHasAccessToServer",
|
|
"getEffectivePermsForUserOnServer", "schedulerQueue", "findServer",
|
|
"getCanonicalServerName", "schedulerMutateRateLimiter", "requireActionTokenOr403",
|
|
"fetchAllSchedulerJobsInStates", "rejectCrossSiteRead", "schedulerTasksReadRateLimiter", "SCHEDULER_CREATE_REDIS_DEADLINE_MS", "console",
|
|
`"use strict";\n${routeSource}\nreturn app.handler;`
|
|
)(
|
|
app,
|
|
async () => true,
|
|
sanitizeServerName,
|
|
async (_email, name) => {
|
|
calls.push({ fn: "userHasAccessToServer", name });
|
|
const lower = String(name).toLowerCase();
|
|
return accessNames.map((n) => String(n).toLowerCase()).includes(lower);
|
|
},
|
|
async (_email, name) => {
|
|
calls.push({ fn: "getEffectivePermsForUserOnServer", name });
|
|
return perms;
|
|
},
|
|
null, // schedulerQueue null → the routes stop at the 503 check once the checks pass
|
|
(name) => {
|
|
calls.push({ fn: "findServer", name });
|
|
return findServerImpl(name);
|
|
},
|
|
// The REAL shipped sanitizer (utils/server-name.js) — no test-local copy.
|
|
require("../utils/server-name").getCanonicalServerName,
|
|
(_req, _res, next) => next(),
|
|
async () => true,
|
|
async () => [],
|
|
// The GET route mounts these two before the handler; the app stub above
|
|
// captures the LAST handler, so the guards themselves never run here.
|
|
(_req, _res, next) => next(),
|
|
(_req, _res, next) => next(),
|
|
15000,
|
|
{ error() {} }
|
|
);
|
|
const res = {
|
|
json(payload) { responses.push({ code: 200, payload }); return payload; },
|
|
status(code) { return { json(payload) { responses.push({ code, payload }); return payload; } }; }
|
|
};
|
|
return {
|
|
async run(serverName = "My-Bot") {
|
|
calls.length = 0;
|
|
responses.length = 0;
|
|
await handler({ params: { serverName }, session: { user: "sub@example.com" } }, res);
|
|
return responses;
|
|
},
|
|
calls,
|
|
responses
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// GET /api/scheduler/:serverName/tasks
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const getHarness = (opts) => makeRouteHarness(getRouteSource, "get", opts);
|
|
|
|
test("GET: a legacy-named server resolves BEFORE the access check — the subuser's grant on the stored name now passes", async () => {
|
|
const h = getHarness({
|
|
findServerImpl: async () => LEGACY_ROW,
|
|
accessNames: ["My Bot"], // the access row as stored — "my-bot" was never in it
|
|
perms: { scheduler_access: true }
|
|
});
|
|
const responses = await h.run("My-Bot");
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "findServer"), { fn: "findServer", name: "My-Bot" });
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "userHasAccessToServer"), { fn: "userHasAccessToServer", name: "My Bot" },
|
|
"the access check must run against the STORED name, not the sanitized URL form");
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "getEffectivePermsForUserOnServer"), { fn: "getEffectivePermsForUserOnServer", name: "My Bot" });
|
|
// The checks passed, so the route reached its scheduler-unavailable 503 —
|
|
// NOT the 403s that used to swallow valid subusers.
|
|
assert.deepStrictEqual(responses, [{ code: 503, payload: { ok: false, error: "scheduler not available", detail: "Redis not configured" } }]);
|
|
});
|
|
|
|
test("GET: findServer order precedes the access check, and the route pays exactly ONE lookup", async () => {
|
|
const h = getHarness({
|
|
findServerImpl: async () => LEGACY_ROW,
|
|
accessNames: ["My Bot"],
|
|
perms: { scheduler_access: true }
|
|
});
|
|
await h.run();
|
|
const fns = h.calls.map((c) => c.fn);
|
|
assert.strictEqual(fns.filter((f) => f === "findServer").length, 1, "one findServer lookup per route");
|
|
assert.ok(fns.indexOf("findServer") < fns.indexOf("userHasAccessToServer"), "canonical resolution must precede the access check");
|
|
assert.ok(fns.indexOf("userHasAccessToServer") < fns.indexOf("getEffectivePermsForUserOnServer"), "access precedes perms");
|
|
});
|
|
|
|
test("GET: findServer miss falls back to the raw sanitized name for the checks (fail closed, 403 — not 404/500)", async () => {
|
|
const h = getHarness({ findServerImpl: async () => null, accessNames: ["My Bot"] });
|
|
const responses = await h.run("My-Bot");
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "userHasAccessToServer"), { fn: "userHasAccessToServer", name: "My-Bot" });
|
|
assert.deepStrictEqual(responses, [{ code: 403, payload: { ok: false, error: "access denied" } }]);
|
|
});
|
|
|
|
test("GET: findServer THROW is caught, not fatal — the raw-name fallback runs and answers 403", async () => {
|
|
const h = getHarness({ findServerImpl: async () => { throw new Error("db down"); }, accessNames: ["My Bot"] });
|
|
const responses = await h.run("My-Bot");
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "userHasAccessToServer"), { fn: "userHasAccessToServer", name: "My-Bot" });
|
|
assert.deepStrictEqual(responses, [{ code: 403, payload: { ok: false, error: "access denied" } }]);
|
|
});
|
|
|
|
function makeLegacyTaskListHarness(jobs, queue = { getRepeatableJobs: async () => [] }, agentEnabled = true) {
|
|
const app = { get(_path, ...handlers) { app.handler = handlers[handlers.length - 1]; } };
|
|
const calls = [];
|
|
const { getCanonicalServerName } = require("../utils/server-name");
|
|
const { schedulerJobBelongsToServer, resolveSchedulerRepeatablesForServer } = require("../services/scheduler-task-scope");
|
|
const { isAgentSchedule } = require("../AgentWorker/feature-http");
|
|
const handler = new Function(
|
|
"app", "isAuthenticated", "sanitizeServerName", "userHasAccessToServer",
|
|
"getEffectivePermsForUserOnServer", "schedulerQueue", "findServer",
|
|
"getCanonicalServerName", "schedulerTasksReadRateLimiter", "rejectCrossSiteRead",
|
|
"fetchAllSchedulerJobsInStates", "agentFeature", "isAgentSchedule", "schedulerJobBelongsToServer", "resolveSchedulerRepeatablesForServer",
|
|
`"use strict";\n${getRouteSource}\nreturn app.handler;`
|
|
)(
|
|
app,
|
|
async () => true,
|
|
(raw) => String(raw || "").trim().replace(/\s+/g, "-"),
|
|
async (_email, name) => {
|
|
calls.push({ fn: "userHasAccessToServer", name });
|
|
return String(name).toLowerCase() === "my bot";
|
|
},
|
|
async () => ({ scheduler_access: true }),
|
|
queue,
|
|
async () => LEGACY_ROW,
|
|
getCanonicalServerName,
|
|
(_req, _res, next) => next(),
|
|
(_req, _res, next) => next(),
|
|
async () => jobs.map((job) => ({ ...job, data: { serverName: getCanonicalServerName(LEGACY_ROW), serverId: LEGACY_ROW.id, ...job.data } })),
|
|
{ enabled: agentEnabled }, isAgentSchedule, schedulerJobBelongsToServer, resolveSchedulerRepeatablesForServer
|
|
);
|
|
return {
|
|
calls,
|
|
async run(accountId) {
|
|
let status = 200;
|
|
const res = { status(code) { status = code; return this; }, json(payload) { return { code: status, payload }; } };
|
|
return handler({ params: { serverName: "My-Bot" }, session: { user: "sub@example.com" }, currentUser: { id: accountId } }, res);
|
|
},
|
|
};
|
|
}
|
|
|
|
test("GET: a legacy server's one-time task keeps its scheduled time after running", async () => {
|
|
const timestamp = 1_700_000_000_000;
|
|
const delay = 600_000;
|
|
const job = { id: "once-task", data: { scheduleType: "once" }, timestamp, delay, opts: { delay } };
|
|
const { run, calls } = makeLegacyTaskListHarness([job]);
|
|
|
|
const pending = await run(7);
|
|
job.delay = 0;
|
|
job.processedOn = timestamp + delay + 1000;
|
|
job.finishedOn = job.processedOn + 1000;
|
|
const completed = await run(7);
|
|
|
|
assert.deepStrictEqual(calls.map(({ name }) => name), ["My Bot", "My Bot"]);
|
|
assert.deepStrictEqual([pending.code, completed.code], [200, 200]);
|
|
const tasks = [pending.payload.tasks[0], completed.payload.tasks[0]];
|
|
assert.deepStrictEqual(tasks.map(({ status }) => status), ["pending", "completed"]);
|
|
assert.deepStrictEqual(tasks.map(({ scheduledFor }) => scheduledFor), [timestamp + delay, timestamp + delay]);
|
|
});
|
|
|
|
test("GET: failure details belong to the original account, not its reused email", async () => {
|
|
const failedReason = "Fixture task failed";
|
|
const jobs = [7, undefined].map((userId) => ({
|
|
data: { scheduleType: "once", userName: "sub@example.com", userId },
|
|
timestamp: 1_700_000_000_000,
|
|
finishedOn: 1_700_000_001_000,
|
|
failedReason,
|
|
}));
|
|
const { run } = makeLegacyTaskListHarness(jobs);
|
|
const owner = await run("7");
|
|
const replacement = await run(8);
|
|
assert.deepStrictEqual(owner.payload.tasks.map((task) => task.failedReason), [failedReason, null]);
|
|
assert.deepStrictEqual(replacement.payload.tasks.map((task) => task.failedReason), [null, null]);
|
|
});
|
|
|
|
test("GET: one-time history is scoped to the current server identity", async () => {
|
|
const jobs = [7, "7", 8, undefined].map((serverId, index) => ({
|
|
id: `job-${index}`,
|
|
data: { serverId },
|
|
timestamp: 1_700_000_000_000,
|
|
finishedOn: 1_700_000_001_000,
|
|
}));
|
|
const { payload } = await makeLegacyTaskListHarness(jobs).run(7);
|
|
assert.deepStrictEqual(payload.tasks.map((task) => task.id), ["job-0", "job-1"]);
|
|
});
|
|
|
|
test("GET: recurring templates must prove ownership through their binding or current occurrence", async () => {
|
|
const { getCanonicalServerName } = require("../utils/server-name");
|
|
const serverName = getCanonicalServerName(LEGACY_ROW);
|
|
const next = 1_700_000_000_000;
|
|
const templates = [
|
|
["bound-current", "7"], ["bound-old", 8], ["legacy-current"], ["legacy-old"], ["legacy-missing"],
|
|
].map(([key, serverId]) => ({ key, next, name: JSON.stringify({ serverName, serverId, name: "Fixture" }) }));
|
|
const occurrences = new Map([["legacy-current", 7], ["legacy-old", 8]].map(([repeatJobKey, serverId]) => [
|
|
`repeat:${repeatJobKey}:${next}`, { repeatJobKey, opts: { prevMillis: next }, data: { serverId, serverName } },
|
|
]));
|
|
const queue = {
|
|
getRepeatableJobs: async () => templates,
|
|
repeat: Promise.resolve(require("bullmq").Repeat.prototype),
|
|
getJob: async (id) => occurrences.get(id),
|
|
};
|
|
const { code, payload } = await makeLegacyTaskListHarness([], queue).run(7);
|
|
assert.equal(code, 200);
|
|
assert.deepStrictEqual(payload.recurring.map((task) => task.id), ["bound-current", "legacy-current"]);
|
|
});
|
|
|
|
test("GET: Agent tasks remain manageable without disclosing their payloads when Agent is disabled", async () => {
|
|
const { getCanonicalServerName } = require("../utils/server-name");
|
|
const serverName = getCanonicalServerName(LEGACY_ROW);
|
|
const jobs = [{ id: "agent-once", timestamp: 1_700_000_000_000, data: { actionType: "agent_prompt", payload: { prompt: "fixture prompt" } } }];
|
|
const queue = {
|
|
getRepeatableJobs: async () => [{
|
|
key: "planner-recurring",
|
|
name: JSON.stringify({ serverName, serverId: LEGACY_ROW.id, actionType: "planner_next_to_agent" }),
|
|
}],
|
|
};
|
|
const { code, payload } = await makeLegacyTaskListHarness(jobs, queue, false).run(7);
|
|
assert.equal(code, 200);
|
|
assert.deepStrictEqual(payload.tasks.map((task) => task.id), ["agent-once"]);
|
|
assert.deepStrictEqual(payload.recurring.map((task) => task.id), ["planner-recurring"]);
|
|
assert.ok(payload.tasks.every((task) => !Object.hasOwn(task, "payload")));
|
|
});
|
|
|
|
test("GET: skipped runs are not reported as completed and do not expose worker results", async () => {
|
|
const finishedJob = { timestamp: 1_700_000_000_000, finishedOn: 1_700_000_001_000 };
|
|
const { payload } = await makeLegacyTaskListHarness([
|
|
{ ...finishedJob, id: "completed", returnvalue: { success: true } },
|
|
{ ...finishedJob, id: "skipped", returnvalue: { success: true, skipped: true, reason: "agent_disabled" } },
|
|
{ ...finishedJob, id: "failed", failedReason: "fixture failure" },
|
|
]).run(7);
|
|
assert.deepStrictEqual(payload.tasks.map((task) => task.status), ["completed", "skipped", "failed"]);
|
|
assert.ok(payload.tasks.every((task) => !Object.hasOwn(task, "returnvalue") && !Object.hasOwn(task, "reason")));
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// POST /api/scheduler/:serverName/tasks
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const postHarness = (opts) => makeRouteHarness(postRouteSource, "post", opts);
|
|
|
|
test("POST: a legacy-named server resolves BEFORE the access check — the subuser reaches the route body", async () => {
|
|
const h = postHarness({
|
|
findServerImpl: async () => LEGACY_ROW,
|
|
accessNames: ["My Bot"],
|
|
perms: { scheduler_create: true }
|
|
});
|
|
const responses = await h.run("My-Bot");
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "userHasAccessToServer"), { fn: "userHasAccessToServer", name: "My Bot" });
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "getEffectivePermsForUserOnServer"), { fn: "getEffectivePermsForUserOnServer", name: "My Bot" });
|
|
// Checks passed → the route proceeds past them and stops at the 503
|
|
// (schedulerQueue is null in this harness) — the pre-fix behavior was a
|
|
// 403 "access denied" long before this point.
|
|
assert.deepStrictEqual(responses, [{ code: 503, payload: { ok: false, error: "scheduler not available", detail: "Redis not configured" } }]);
|
|
});
|
|
|
|
test("POST: one findServer lookup, hoisted before the access check (the in-lock duplicate is gone)", async () => {
|
|
const h = postHarness({
|
|
findServerImpl: async () => LEGACY_ROW,
|
|
accessNames: ["My Bot"],
|
|
perms: { scheduler_create: true }
|
|
});
|
|
await h.run();
|
|
const fns = h.calls.map((c) => c.fn);
|
|
assert.strictEqual(fns.filter((f) => f === "findServer").length, 1, "one findServer lookup per route");
|
|
assert.ok(fns.indexOf("findServer") < fns.indexOf("userHasAccessToServer"));
|
|
});
|
|
|
|
test("POST: a missing server cannot create an unbound task and a lookup error is not a miss", async () => {
|
|
const denied = postHarness({ findServerImpl: async () => null, accessNames: ["My Bot"] });
|
|
assert.deepStrictEqual(await denied.run(), [{ code: 403, payload: { ok: false, error: "access denied" } }]);
|
|
const authorized = { accessNames: ["My-Bot"], perms: { scheduler_create: true } };
|
|
const missing = postHarness({ ...authorized, findServerImpl: async () => null });
|
|
assert.deepStrictEqual(await missing.run(), [{ code: 404, payload: { ok: false, error: "server not found" } }]);
|
|
const failed = postHarness({ ...authorized, findServerImpl: async () => { throw new Error("fixture DB unavailable"); } });
|
|
assert.deepStrictEqual(await failed.run(), [{ code: 500, payload: { ok: false, error: "internal error" } }]);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// DELETE /api/scheduler/:serverName/tasks/:taskId
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const deleteHarness = (opts) => makeRouteHarness(deleteRouteSource, "delete", opts);
|
|
|
|
test("DELETE: a legacy-named server resolves BEFORE the access check — the subuser reaches the route body", async () => {
|
|
const h = deleteHarness({
|
|
findServerImpl: async () => LEGACY_ROW,
|
|
accessNames: ["My Bot"],
|
|
perms: { scheduler_delete: true }
|
|
});
|
|
const responses = await h.run("My-Bot");
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "userHasAccessToServer"), { fn: "userHasAccessToServer", name: "My Bot" });
|
|
assert.deepStrictEqual(h.calls.find((c) => c.fn === "getEffectivePermsForUserOnServer"), { fn: "getEffectivePermsForUserOnServer", name: "My Bot" });
|
|
assert.deepStrictEqual(responses, [{ code: 503, payload: { ok: false, error: "scheduler not available" } }]);
|
|
});
|
|
|
|
test("DELETE: one findServer lookup, hoisted before the access check; miss/throw fail closed on the raw name", async () => {
|
|
const h = deleteHarness({
|
|
findServerImpl: async () => LEGACY_ROW,
|
|
accessNames: ["My Bot"],
|
|
perms: { scheduler_delete: true }
|
|
});
|
|
await h.run();
|
|
const fns = h.calls.map((c) => c.fn);
|
|
assert.strictEqual(fns.filter((f) => f === "findServer").length, 1, "one findServer lookup per route");
|
|
assert.ok(fns.indexOf("findServer") < fns.indexOf("userHasAccessToServer"));
|
|
|
|
for (const findServerImpl of [async () => null, async () => { throw new Error("db down"); }]) {
|
|
const miss = deleteHarness({ findServerImpl, accessNames: ["My Bot"] });
|
|
const responses = await miss.run("My-Bot");
|
|
assert.deepStrictEqual(miss.calls.find((c) => c.fn === "userHasAccessToServer"), { fn: "userHasAccessToServer", name: "My-Bot" });
|
|
assert.deepStrictEqual(responses, [{ code: 403, payload: { ok: false, error: "access denied" } }]);
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source-level wiring: the reorder preserved each route's settled order
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("each route carries the constraint comment and runs the checks on accessServerName", () => {
|
|
for (const [label, rawRoute, codeRoute] of [
|
|
["GET", getRouteSource, getRouteCode()],
|
|
["POST", postRouteSource, postRouteCode()],
|
|
["DELETE", deleteRouteSource, deleteRouteCode()]
|
|
]) {
|
|
// Comment pins run on the RAW source (stripping would erase them).
|
|
assert.ok(rawRoute.includes("adpanel:scheduler-route-canonical-authz"), `${label}: constraint comment missing`);
|
|
assert.ok(rawRoute.includes("adpanel:scheduler-canonical-authz"), `${label}: fire-time doctrine cross-reference missing`);
|
|
assert.ok(codeRoute.includes('String(serverEntry?.name || serverName || "").trim()'), `${label}: stored-name fallback expression missing`);
|
|
assert.ok(codeRoute.includes("userHasAccessToServer(email, accessServerName)"), `${label}: access check must run on the resolved name`);
|
|
assert.ok(codeRoute.includes("getEffectivePermsForUserOnServer(email, accessServerName)"), `${label}: perms check must run on the resolved name`);
|
|
assert.ok(!codeRoute.includes("userHasAccessToServer(email, serverName)"), `${label}: the pre-canonical access check must be gone`);
|
|
assert.ok(!codeRoute.includes("getEffectivePermsForUserOnServer(email, serverName)"), `${label}: the pre-canonical perms check must be gone`);
|
|
}
|
|
});
|
|
|
|
function getRouteCode() { return stripFullLineComments(getRouteSource); }
|
|
function postRouteCode() { return stripFullLineComments(postRouteSource); }
|
|
function deleteRouteCode() { return stripFullLineComments(deleteRouteSource); }
|
|
|
|
test("exactly one findServer lookup per route, hoisted above its access check", () => {
|
|
for (const [label, route] of [["GET", getRouteCode()], ["POST", postRouteCode()], ["DELETE", deleteRouteCode()]]) {
|
|
const lookupCount = (route.match(/await findServer\(serverName\)/g) || []).length;
|
|
assert.strictEqual(lookupCount, 1, `${label}: one findServer lookup per route`);
|
|
const findAt = route.indexOf("await findServer(serverName)");
|
|
const accessAt = route.indexOf("userHasAccessToServer(email, accessServerName)");
|
|
assert.ok(findAt > -1 && accessAt > findAt, `${label}: canonical resolution must precede the access check`);
|
|
assert.strictEqual(route.includes("await findServer(serverName).catch(() => null)"), label !== "POST", `${label}: create must propagate lookup failures`);
|
|
}
|
|
// The POST quota's old in-lock duplicate is gone: the lock callback reads
|
|
// the hoisted row.
|
|
const postRoute = postRouteCode();
|
|
const lockAt = postRoute.indexOf("withSchedulerCreateLock(");
|
|
const maxAt = postRoute.indexOf("resolveSchedulerMaxSchedules(serverEntry)");
|
|
assert.ok(lockAt > -1 && maxAt > lockAt, "the quota reads the hoisted serverEntry inside the lock callback");
|
|
assert.ok(!/withSchedulerCreateLock\([\s\S]*findServer\(serverName\)/.test(postRoute), "no second findServer inside the lock callback");
|
|
});
|
|
|
|
test("POST: the action-token anchoring stays AFTER canonicalization, and the timestamp/floor gates stay above the lock", () => {
|
|
const route = postRouteCode();
|
|
const findAt = route.indexOf("await findServer(serverName)");
|
|
const tokenAt = route.indexOf("requireActionTokenOr403(req, res");
|
|
assert.ok(tokenAt > findAt, "the action-token gate must anchor on the canonicalized resource");
|
|
const tsGateAt = route.indexOf('scheduleType === "once" && scheduledTimestamp !== undefined');
|
|
const wrapGateAt = route.indexOf("schedulerCronMinGapSeconds(scheduleType, scheduleValue)");
|
|
const lockAt = route.indexOf("withSchedulerCreateLock(");
|
|
assert.ok(tsGateAt > 0 && tsGateAt < lockAt, "the hoisted once-timestamp gate stays above the create lock");
|
|
assert.ok(wrapGateAt > 0 && wrapGateAt < lockAt, "the wrap-floor gate stays above the create lock");
|
|
});
|
|
|
|
test("GET keeps its 503 scheduler-unavailable check after the perms check; DELETE mirrors the POST structure", () => {
|
|
const getRoute = getRouteCode();
|
|
const getPermsAt = getRoute.indexOf("getEffectivePermsForUserOnServer(email, accessServerName)");
|
|
const get503At = getRoute.indexOf('error: "scheduler not available"');
|
|
assert.ok(getPermsAt > -1 && get503At > getPermsAt, "GET: 503 stays after the perms check");
|
|
|
|
const deleteRoute = deleteRouteCode();
|
|
const delTokenAt = deleteRoute.indexOf("requireActionTokenOr403(req, res");
|
|
const delFindAt = deleteRoute.indexOf("await findServer(serverName)");
|
|
assert.ok(delTokenAt > delFindAt, "DELETE: the action-token gate stays after canonicalization");
|
|
});
|