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

+269
View File
@@ -0,0 +1,269 @@
"use strict";
// Source-level pins for the subuser `planner_access` permission gate.
//
// The planner was the last per-server feature whose routes checked only
// server-level ACL access: a subuser with ANY grant on the server could read
// and mutate the planner queue, and a queued "next step to agent" hand-off
// re-verified with no planner-specific permission at all. This file pins the
// parity fix so deleting any piece of it fails a suite:
//
// 1. "planner_access" is a real grantable key (ALLOWED_PERM_KEYS), so it
// survives the grant route's boolean coercion and the settings UI;
// 2. getEffectivePermsForUserOnServer's permsTemplate defaults it to false
// — deny-by-default for grants that predate the key;
// 3. resolvePlannerContext, the shared gate of the six planner routes,
// re-checks the effective permission for non-admins and answers 403;
// 4. the scheduler re-verification maps "planner_next_to_agent" to
// "planner_access" (execution-time parity with the interactive gate)
// while "agent_prompt" keeps requiring "scheduler_access".
// 5. resolvePlannerContext gates suspension AFTER the planner_access check
// — state follows authorization, so a suspended server refuses the
// planner board (read AND write) exactly like every other per-server
// surface, without leaking its state to unauthorized callers.
//
// The route→gate wiring itself (all six planner routes calling
// resolvePlannerContext) is already pinned by tests/preflight-guard-sweep
// .test.js and intentionally not duplicated here.
//
// index.js is a ~51k-line application bundle (module side effects, DB and
// network at require time), so these tests pin the fixes structurally on
// well-anchored source windows, matching the convention of the other
// route-level tests in this directory (e.g. preflight-guard-sweep.test.js).
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_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8");
// Slice from an anchor to the function's closing brace at column zero — the
// same window discipline preflight-guard-sweep.test.js uses.
function functionWindow(src, anchor, label) {
const start = src.indexOf(anchor);
assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`);
const end = src.indexOf("\n}", start);
assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`);
return src.slice(start, end + 2);
}
function countOccurrences(haystack, needle) {
let count = 0;
let at = haystack.indexOf(needle);
while (at !== -1) {
count += 1;
at = haystack.indexOf(needle, at + needle.length);
}
return count;
}
test("ALLOWED_PERM_KEYS contains planner_access", () => {
const start = INDEX_SRC.indexOf("const ALLOWED_PERM_KEYS = [");
assert.notStrictEqual(start, -1, "ALLOWED_PERM_KEYS declaration not found");
const end = INDEX_SRC.indexOf("];", start);
assert.notStrictEqual(end, -1, "ALLOWED_PERM_KEYS closing bracket not found");
const keysBlock = INDEX_SRC.slice(start, end);
const keys = keysBlock.match(/"[a-z_]+"/g) || [];
assert.ok(
keys.includes('"planner_access"'),
`planner_access must be a grantable permission key; got: ${keys.join(", ")}`
);
// Exactly once: a duplicate entry would be harmless but signals a merge accident.
assert.strictEqual(
countOccurrences(keysBlock, '"planner_access"'),
1,
"planner_access must appear exactly once in ALLOWED_PERM_KEYS"
);
});
test("getEffectivePermsForUserOnServer defaults planner_access to false", () => {
const body = functionWindow(
INDEX_SRC,
"async function getEffectivePermsForUserOnServer",
"getEffectivePermsForUserOnServer"
);
assert.ok(body.includes("const permsTemplate = {"), "permsTemplate declaration not found");
assert.ok(
body.includes("planner_access: false"),
"permsTemplate must default planner_access to false (deny-by-default for grants that predate the key)"
);
});
test("resolvePlannerContext enforces the planner_access gate with a 403 for non-admins", () => {
const body = functionWindow(INDEX_SRC, "async function resolvePlannerContext", "resolvePlannerContext");
const gateAt = body.indexOf("if (!(await isAdmin(req))) {");
assert.notStrictEqual(gateAt, -1, "the non-admin branch is missing");
const permsCallAt = body.indexOf("getEffectivePermsForUserOnServer(userEmail, serverName)");
assert.notStrictEqual(permsCallAt, -1, "the effective-perms lookup is missing");
const checkAt = body.indexOf("if (!perms || !perms.planner_access) {");
assert.notStrictEqual(checkAt, -1, "the planner_access check is missing");
const forbiddenAt = body.indexOf("res.status(403)", checkAt);
assert.notStrictEqual(forbiddenAt, -1, "the planner_access denial must answer 403");
assert.ok(
gateAt < permsCallAt && permsCallAt < checkAt && checkAt < forbiddenAt,
"gate order must be: non-admin branch -> effective-perms lookup -> planner_access check -> 403"
);
const returnsNullAt = body.indexOf("return null;", forbiddenAt);
assert.notStrictEqual(returnsNullAt, -1, "the denial must return null so the route body never runs");
});
// adpanel:planner-suspension-gate — resolvePlannerContext is the shared gate of
// all six planner routes; without the suspension check a suspended server's
// board stayed fully usable while every other per-server surface refused. The
// gate must sit AFTER the planner_access denial (a caller without the
// permission must not learn the server's state — the fs routes'
// perms-before-suspension order) and BEFORE the context is returned to the
// route, so both the GET and every mutation see it.
test("resolvePlannerContext gates suspension after the planner_access check and before returning the context", () => {
const body = functionWindow(INDEX_SRC, "async function resolvePlannerContext", "resolvePlannerContext");
const checkAt = body.indexOf("if (!perms || !perms.planner_access) {");
assert.notStrictEqual(checkAt, -1, "the planner_access check is missing");
const forbiddenAt = body.indexOf("res.status(403)", checkAt);
assert.notStrictEqual(forbiddenAt, -1, "the planner_access denial must answer 403");
const gateAt = body.indexOf("if (isServerSuspended(entry)) {");
assert.notStrictEqual(
gateAt,
-1,
"the suspension gate is missing — a suspended server's planner board (read AND write) must refuse exactly like every other per-server surface"
);
const returnAt = body.indexOf("return { serverName, userEmail, serverRowId: entry.rowId };");
assert.notStrictEqual(returnAt, -1, "the context return is missing");
assert.ok(
forbiddenAt < gateAt && gateAt < returnAt,
"order must be: planner_access denial (authorization) -> isServerSuspended gate (state) -> context return, matching the fs routes' perms-before-suspension order"
);
});
test("the Planner suspension response never becomes a usable route context", async () => {
const body = functionWindow(INDEX_SRC, "async function resolvePlannerContext", "resolvePlannerContext");
const entry = { name: "fixture-server", rowId: 7, suspended: true };
const calls = [];
const dependencies = {
isAuthenticated: async () => true,
db: { query() {} },
plannerTablesReady: true,
sanitizeServerName: (name) => name,
findServer: async () => entry,
isAdmin: async () => false,
userHasAccessToServer: async () => true,
getEffectivePermsForUserOnServer: async () => ({ planner_access: true }),
isServerSuspended: (server) => server.suspended,
sendSuspendedServerJson: (res, server) => {
calls.push(server);
return res;
},
};
const resolve = new Function(...Object.keys(dependencies), `${body}\nreturn resolvePlannerContext;`)(...Object.values(dependencies));
const req = { session: { user: "planner@example.test" } };
assert.equal(await resolve(req, {}, entry.name), null);
assert.deepEqual(calls, [entry]);
entry.suspended = false;
assert.deepEqual(await resolve(req, {}, entry.name), { serverName: entry.name, userEmail: req.session.user, serverRowId: entry.rowId });
});
// adpanel:planner-existence-oracle — resolvePlannerContext used to answer
// 404 "Server not found" BEFORE the access check; since findServer matches
// name/legacy_id/bot, any authenticated user could enumerate existing servers
// AND their legacy aliases across all six planner routes (404 = exists, 403 =
// exists but denied). The oracle-safe order is pinned here: the access gate
// (403) must precede the 404, and the gate must cover BOTH the URL form and
// the resolved canonical form so a grant stored under either authorizes.
test("resolvePlannerContext answers the access gate before the 404 (no existence oracle)", () => {
const body = functionWindow(INDEX_SRC, "async function resolvePlannerContext", "resolvePlannerContext");
const urlFormAt = body.indexOf("userHasAccessToServer(userEmail, requestedServerName)");
assert.notStrictEqual(urlFormAt, -1, "the access gate must check the URL form of the name");
const canonicalAt = body.indexOf("userHasAccessToServer(userEmail, serverName)");
assert.notStrictEqual(canonicalAt, -1, "the access gate must also check the resolved canonical form");
const gateAt = Math.min(urlFormAt, canonicalAt);
const forbiddenAt = body.indexOf("res.status(403)", gateAt);
assert.notStrictEqual(forbiddenAt, -1, "unauthorized callers must be denied with 403");
const notFoundAt = body.indexOf('res.status(404).json({ error: \'Server not found\' })', forbiddenAt);
assert.notStrictEqual(
notFoundAt,
-1,
"the 404 must still exist for authorized callers (real typo feedback)"
);
assert.ok(
forbiddenAt < notFoundAt,
"SERVER CONTRACT BROKEN: the 404 'Server not found' must come AFTER the access gate — a 404-before-403 order is an existence oracle that lets any authenticated user enumerate servers and their aliases"
);
const emailAt = body.indexOf("const userEmail = String(req.session?.user || '').trim().toLowerCase();");
assert.notStrictEqual(emailAt, -1, "userEmail computation missing");
assert.ok(
emailAt < gateAt,
"userEmail must be resolved before the access gate consumes it"
);
});
test("schedulerRequiredPermissionForAction maps planner_next_to_agent to planner_access", () => {
const body = functionWindow(
INDEX_SRC,
"function schedulerRequiredPermissionForAction",
"schedulerRequiredPermissionForAction"
);
assert.ok(
body.includes('case "planner_next_to_agent": return "planner_access";'),
'queued planner hand-offs must re-verify "planner_access" at execution time'
);
assert.ok(
body.includes('case "agent_prompt": return "scheduler_access";'),
'"agent_prompt" must keep requiring "scheduler_access"'
);
assert.ok(body.includes("default: return null;"), "unmapped actions must stay un-permissioned (null)");
});
// adpanel:planner-init-retry-cooldown — initPlannerTables swallows its own
// failure and resolvePlannerContext used to re-invoke it on EVERY planner
// request while not ready: a persistently failing DDL (permissions, disk) was
// replayed per request (latency amplification plus error spam, then a raw 500
// at query time). The retry is now bounded: the failure arms a not-before
// timestamp, requests inside the cooldown get a clean 503 WITHOUT re-invoking,
// and the first request past the cooldown retries the init exactly once (a
// recovered database is picked up, never stranded).
test("resolvePlannerContext bounds initPlannerTables retries with a cooldown and answers a clean 503 while storage is unavailable", () => {
const body = functionWindow(INDEX_SRC, "async function resolvePlannerContext", "resolvePlannerContext");
// The cooldown gate must sit inside the not-ready branch, BEFORE the init
// call — inside the cooldown the failing DDL is not replayed at all.
const notReadyAt = body.indexOf("if (!plannerTablesReady) {");
const cooldownAt = body.indexOf("if (Date.now() < plannerTablesRetryNotBeforeMs) {");
const initAt = body.indexOf("await initPlannerTables();");
assert.notStrictEqual(notReadyAt, -1, "the not-ready branch is missing");
assert.notStrictEqual(cooldownAt, -1, "the cooldown gate is missing — without it a persistently failing DDL is replayed per request");
assert.notStrictEqual(initAt, -1, "the init retry must still exist — after the cooldown the next request retries once");
assert.ok(
notReadyAt < cooldownAt && cooldownAt < initAt,
"order must be: not-ready branch -> cooldown 503 gate -> the single init retry"
);
// Both failure shapes answer the same clean 503 (inside the cooldown, and a
// retry that failed again) and return null so the route body never runs —
// a raw 500 from querying a missing table must stay unreachable.
assert.strictEqual(
countOccurrences(body, "res.status(503).json({ error: 'planner storage is temporarily unavailable' });"),
2,
"the cooldown path and the failed-retry path must both answer the clean 503 and fail closed"
);
assert.ok(
body.includes("return null;", body.indexOf("planner storage is temporarily unavailable")) ||
body.includes("return null;"),
"the 503 paths must return null so the route body never runs"
);
// The state lives beside the readiness flag and the cooldown is a named
// constant; the init failure arms it while KEEPING the swallowed-failure
// error log (the constraint comment rides the catch).
const stateAt = INDEX_SRC.indexOf("let plannerTablesRetryNotBeforeMs = 0;");
const flagAt = INDEX_SRC.indexOf("let plannerTablesReady = false;");
const constAt = INDEX_SRC.indexOf("const PLANNER_TABLES_RETRY_COOLDOWN_MS = 10 * 1000;");
assert.ok(
flagAt !== -1 && stateAt !== -1 && constAt !== -1 && flagAt < stateAt && stateAt < constAt,
"the cooldown state and its named 10s constant must be declared beside plannerTablesReady"
);
const initBody = functionWindow(INDEX_SRC, "async function initPlannerTables", "initPlannerTables");
const armAt = initBody.indexOf("plannerTablesRetryNotBeforeMs = Date.now() + PLANNER_TABLES_RETRY_COOLDOWN_MS;");
const logAt = initBody.indexOf("console.error('[planner] Failed to init tables:', err.message);");
assert.notStrictEqual(armAt, -1, "the failure path must arm the cooldown");
assert.notStrictEqual(logAt, -1, "the swallowed-failure error log must stay");
assert.ok(armAt < logAt, "the cooldown arms inside the catch, beside the kept failure log");
});