Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,689 @@
|
||||
"use strict";
|
||||
|
||||
// Source-level pins for the scheduler planner->agent FIRE-TIME capability
|
||||
// clamp (adpanel:planner-agent-perms, phase 2).
|
||||
//
|
||||
// The enqueue-time file envelope (pinned by utils/planner-agent-perms.test.js)
|
||||
// removed the file-operations privilege delta, but the agent's tool surface is
|
||||
// larger than files: send_console_command, power/stop/kill, and backup
|
||||
// create/restore/delete were still gated purely on the SCHEDULE CREATOR's
|
||||
// perms, so a planner_access-only author's prompt text could trigger arbitrary
|
||||
// in-container shell execution with the creator's (often admin's) authority,
|
||||
// unattended, via the scheduler's planner_next_to_agent task. This file pins
|
||||
// the gating fix (never a prompt sanitization — the planner text is meant to
|
||||
// be a direct prompt):
|
||||
//
|
||||
// 1. applyAiAgentPermClamp is the single choke point: it returns the
|
||||
// creator's perms untouched when the req carries no clamp (interactive
|
||||
// chats and every non-planner job source are unchanged), resolves the
|
||||
// planner item author's contribution per TARGET server (memoized), and
|
||||
// composes intersectPerms + the persisted file envelope via
|
||||
// computeSchedulerPlannerClampedPerms;
|
||||
// 2. resolveBotToolServerOrError — the funnel EVERY bot tool goes through —
|
||||
// takes the req and applies the clamp BEFORE the missingPerms check;
|
||||
// all 9 tool call sites inside runBotAssistantTool thread the req
|
||||
// through, which covers the direct console-command path, the custom
|
||||
// tool loop, and all four native provider loops;
|
||||
// 3. processAiAgentJob attaches the clamp ONLY for the planner job sources
|
||||
// (PLANNER_AGENT_JOB_SOURCES: scheduler_planner_next AND planner_send —
|
||||
// manual-send parity, adpanel:planner-agent-perms), resolving the author
|
||||
// with the same id + server_name scoping as
|
||||
// markPlannerItemDoneAfterAgentJob;
|
||||
// 4. completeAiChatConversation clamps currentServerPerms so the system
|
||||
// prompt advertises the clamped truth, not the creator's raw perms;
|
||||
// 5. maybeExecuteDirectBotConsoleCommand keeps routing execution through
|
||||
// runBotAssistantTool (no separate perms resolution that would bypass
|
||||
// the clamp);
|
||||
// 6. resolveSchedulerPlannerPermsOverride intersects the author at fire
|
||||
// time for the job's own server, keeping the FILE_* directive path gated
|
||||
// on the same or stricter projection than the executor;
|
||||
// 7. the fire-time author identity is resolved by
|
||||
// resolveSchedulerPlannerAuthorForJob, which (adpanel:planner-agent-
|
||||
// author-pin) prefers the author_email PINNED on the persisted envelope
|
||||
// at enqueue over the live created_by_email — a mid-queue content edit
|
||||
// cannot re-point the clamp — and falls back to live created_by_email
|
||||
// only for legacy un-pinned rows; the planner PUT route's re-stamp of
|
||||
// created_by_email to the editor on every content rewrite (title/prompt)
|
||||
// matters only for that fallback, keeping it the person who last wrote
|
||||
// the text that will execute (an isDone-only toggle or a reorder does
|
||||
// not rewrite content and keeps the original author); and
|
||||
// 8. the fire-time clamp attaches the canonicalized (findServer-resolved)
|
||||
// server name, so the persisted-file-envelope-only-on-job-server
|
||||
// comparison in applyAiAgentPermClamp cannot miss on an alias/legacy
|
||||
// raw row name.
|
||||
//
|
||||
// index.js is a ~54k-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
|
||||
// tests/planner-access-gate.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");
|
||||
const CONVERSATION_SRC = fs.readFileSync(path.join(ROOT, "AgentWorker", "conversation.js"), "utf8")
|
||||
.replace(/^ {2}(?=\S)/gm, "");
|
||||
|
||||
// Slice from an anchor to the function's closing brace at column zero — the
|
||||
// same window discipline planner-access-gate.test.js uses, hardened for the
|
||||
// multi-line destructured signatures this area of index.js has: a parameter
|
||||
// list closing at column zero ("\n}) {") must not terminate the window, so a
|
||||
// "\n}" followed by ")" is skipped.
|
||||
function functionWindow(src, anchor, label) {
|
||||
const start = src.indexOf(anchor);
|
||||
assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`);
|
||||
let end = src.indexOf("\n}", start);
|
||||
assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`);
|
||||
while (end !== -1 && src[end + 2] === ")") {
|
||||
end = src.indexOf("\n}", end + 1);
|
||||
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;
|
||||
}
|
||||
|
||||
// The PUT handler closes with "\n});" — a column-zero brace followed by a
|
||||
// paren — which functionWindow's scan deliberately skips, so the route window
|
||||
// is sliced between the PUT and DELETE anchors instead (the same discipline
|
||||
// tests/planner-reorder-edit-integrity.test.js uses for this route).
|
||||
function plannerPutRouteWindow(label) {
|
||||
const start = INDEX_SRC.indexOf('app.put("/api/servers/:name/planner/:id"');
|
||||
assert.notStrictEqual(start, -1, `${label}: planner PUT route anchor not found`);
|
||||
const end = INDEX_SRC.indexOf('app.delete("/api/servers/:name/planner/:id"', start);
|
||||
assert.notStrictEqual(end, -1, `${label}: planner DELETE route anchor not found after the PUT route`);
|
||||
return INDEX_SRC.slice(start, end);
|
||||
}
|
||||
|
||||
// ─── applyAiAgentPermClamp (the single clamp choke point) ───────────────────
|
||||
|
||||
test("applyAiAgentPermClamp is defined once and is a no-op without a clamp", () => {
|
||||
assert.strictEqual(
|
||||
countOccurrences(INDEX_SRC, "async function applyAiAgentPermClamp"),
|
||||
1,
|
||||
"the clamp helper must be defined exactly once"
|
||||
);
|
||||
const body = functionWindow(INDEX_SRC, "async function applyAiAgentPermClamp", "applyAiAgentPermClamp");
|
||||
assert.ok(
|
||||
body.includes("if (!clamp) return creatorPerms;"),
|
||||
"reqs without a clamp (interactive chats, scheduler_prompt/planner_send/manual jobs) must get the creator's perms untouched"
|
||||
);
|
||||
});
|
||||
|
||||
test("applyAiAgentPermClamp rechecks the current author permissions per target", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function applyAiAgentPermClamp", "applyAiAgentPermClamp");
|
||||
assert.ok(
|
||||
body.includes("await resolveSchedulerPlannerAuthorPermsOnServer(clamp.authorId, targetServer)"),
|
||||
"check the author's current account and permissions on the requested target"
|
||||
);
|
||||
assert.ok(
|
||||
!body.includes("_authorPermsCache"),
|
||||
"a long run must not preserve a previously granted author permission"
|
||||
);
|
||||
});
|
||||
|
||||
test("applyAiAgentPermClamp applies the persisted file envelope only on the job's own server and fails closed on unverified authors", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function applyAiAgentPermClamp", "applyAiAgentPermClamp");
|
||||
const envelopeGuardAt = body.indexOf('targetServer === String(clamp.serverName || "").trim().toLowerCase()');
|
||||
assert.notStrictEqual(
|
||||
envelopeGuardAt,
|
||||
-1,
|
||||
"the persisted enqueue-time envelope must be gated to the job's own server (per-server semantics)"
|
||||
);
|
||||
// adpanel:planner-agent-envelope-closure — the raw column value must be
|
||||
// CLASSIFIED before use, not normalized: the normalizer's null collapses a
|
||||
// PRESENT-but-unparseable envelope into the same value as an ABSENT one and
|
||||
// the file axis would silently fall back to the creator's perms (fail open).
|
||||
// The classifier returns null only for absent and an ALL-FALSE envelope for
|
||||
// unparseable, mirroring the author axis's fail-closed behavior.
|
||||
assert.ok(
|
||||
body.includes("classifyFilePermEnvelope(clamp.fileEnvelope).envelope"),
|
||||
"the raw column value must be classified before use — absent stays legacy, unparseable fails closed"
|
||||
);
|
||||
assert.ok(
|
||||
!body.includes("normalizeFilePermEnvelope("),
|
||||
"the read-time clamp must not regress to the null-collapse normalizer"
|
||||
);
|
||||
const composeAt = body.indexOf("computeSchedulerPlannerClampedPerms({");
|
||||
assert.notStrictEqual(composeAt, -1, "the clamp must compose through the pure decision core");
|
||||
assert.ok(
|
||||
body.includes("!!clamp.authorResolved && resolution.resolved"),
|
||||
"an author unverified at attach time OR unresolvable at fire time must take the fail-closed/legacy-fallback branch"
|
||||
);
|
||||
const compose = body.slice(composeAt);
|
||||
assert.ok(
|
||||
compose.includes("authorPerms: resolution.perms") && compose.includes("authorIsAdmin: resolution.isAdmin"),
|
||||
"the author contribution resolved per server must feed the decision core"
|
||||
);
|
||||
});
|
||||
|
||||
test("resolveSchedulerPlannerAuthorForJob scopes the planner item lookup by id AND server_name and fails closed", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function resolveSchedulerPlannerAuthorForJob", "resolveSchedulerPlannerAuthorForJob");
|
||||
assert.ok(
|
||||
body.includes('"SELECT prompt_author_id, prompt, is_done FROM server_planner_items WHERE id = ? AND server_name = ? LIMIT 1"'),
|
||||
"the author lookup must use the same id + server_name scoping discipline as markPlannerItemDoneAfterAgentJob"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("Number(item.prompt_author_id) !== authorId"),
|
||||
"a stored job may not switch to a different prompt author's identity"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("const unresolved = { authorId: null, authorResolved: false };") && body.includes("return unresolved;"),
|
||||
"missing evidence and a failed lookup must fail closed"
|
||||
);
|
||||
});
|
||||
|
||||
test("queued planner jobs require a pinned author ID and matching active prompt", async () => {
|
||||
const pin = functionWindow(INDEX_SRC, "function pinnedPlannerAuthorIdFromEnvelope", "planner author ID parser");
|
||||
const resolve = functionWindow(INDEX_SRC, "async function resolveSchedulerPlannerAuthorForJob", "planner job provenance check");
|
||||
const item = { prompt_author_id: 12, prompt: "Inspect the selected file.", is_done: 0 };
|
||||
const db = { query: async (_sql, values) => { assert.deepStrictEqual(values, [7, "srv"]); return [item]; } };
|
||||
const resolveAuthor = new Function("db", "sanitizeAiAgentPrompt", "buildPlannerAgentPrompt", `${pin}\n${resolve}\nreturn resolveSchedulerPlannerAuthorForJob;`)(
|
||||
db, String, (row) => row.prompt
|
||||
);
|
||||
const job = { source_ref: "7", server_name: "srv", prompt: item.prompt, perm_file_envelope: '{"author_id":12}' };
|
||||
assert.deepStrictEqual(await resolveAuthor(job), { authorId: 12, authorResolved: true });
|
||||
assert.strictEqual((await resolveAuthor({ ...job, perm_file_envelope: '{"author_email":"old@example.test"}' })).authorResolved, false);
|
||||
assert.strictEqual((await resolveAuthor({ ...job, prompt: "Earlier prompt." })).authorResolved, false);
|
||||
item.prompt_author_id = 18;
|
||||
assert.strictEqual((await resolveAuthor(job)).authorResolved, false);
|
||||
item.prompt_author_id = 12;
|
||||
item.is_done = 1;
|
||||
assert.strictEqual((await resolveAuthor(job)).authorResolved, false);
|
||||
});
|
||||
|
||||
test("resolveSchedulerPlannerAuthorPermsOnServer mirrors the enqueue-time verification order", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function resolveSchedulerPlannerAuthorPermsOnServer", "resolveSchedulerPlannerAuthorPermsOnServer");
|
||||
const suspendedAt = body.indexOf("if (!author || author.suspended)");
|
||||
const adminAt = body.indexOf("if (author.admin)");
|
||||
const aclAt = body.indexOf("userHasAccessToServer(author.email, serverName)");
|
||||
const permsAt = body.indexOf("getEffectivePermsForUserOnServer(author.email, serverName)");
|
||||
assert.notStrictEqual(suspendedAt, -1, "a missing or suspended author must fail closed");
|
||||
assert.notStrictEqual(adminAt, -1, "an admin author must be detected (identity contribution)");
|
||||
assert.notStrictEqual(aclAt, -1, "the explicit ACL check must mirror the enqueue-time logic");
|
||||
assert.notStrictEqual(permsAt, -1, "the author's effective perms must be resolved on the target server");
|
||||
assert.ok(suspendedAt < adminAt && adminAt < aclAt && aclAt < permsAt, "verification order: account -> admin -> ACL -> effective perms");
|
||||
});
|
||||
|
||||
// ─── resolveBotToolServerOrError + runBotAssistantTool (tool gate) ──────────
|
||||
|
||||
test("resolveBotToolServerOrError takes req and applies the clamp before the missingPerms check", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function resolveBotToolServerOrError", "resolveBotToolServerOrError");
|
||||
const signatureAt = body.indexOf("async function resolveBotToolServerOrError({ req,");
|
||||
assert.notStrictEqual(signatureAt, 0 - 1, "the destructure must include req");
|
||||
const lookupAt = body.indexOf("await getEffectivePermsForUserOnServer(userEmail, resolved.entry.name)");
|
||||
const clampAt = body.indexOf("perms = await applyAiAgentPermClamp(req, perms, resolved.entry.name)");
|
||||
const missingAt = body.indexOf("const missingPerms = requiredPerms.filter");
|
||||
assert.notStrictEqual(lookupAt, -1, "the creator-perms lookup is missing");
|
||||
assert.notStrictEqual(clampAt, -1, "the clamp application is missing");
|
||||
assert.notStrictEqual(missingAt, -1, "the missingPerms check is missing");
|
||||
assert.ok(
|
||||
lookupAt < clampAt && clampAt < missingAt,
|
||||
"the clamp must run AFTER the perms lookup and BEFORE the missingPerms check, or a denied perm leaks through"
|
||||
);
|
||||
assert.ok(
|
||||
/let perms = req\?\.readAiAgentJobPermissions\s*\? await req\.readAiAgentJobPermissions\(resolved\.entry\.name, resolved\.entry\.id\)\s*:\s*await getEffectivePermsForUserOnServer/.test(body),
|
||||
"background jobs must verify live authorization for the resolved target before applying the clamp"
|
||||
);
|
||||
});
|
||||
|
||||
test("runBotAssistantTool passes req to every resolveBotToolServerOrError call site (all 9 tools)", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function runBotAssistantTool", "runBotAssistantTool");
|
||||
const callAnchor = "await resolveBotToolServerOrError({";
|
||||
const callCount = countOccurrences(body, callAnchor);
|
||||
assert.strictEqual(callCount, 9, "every bot tool must resolve its server/perms through the single funnel");
|
||||
let at = body.indexOf(callAnchor);
|
||||
let checked = 0;
|
||||
while (at !== -1) {
|
||||
const closeAt = body.indexOf("\n });", at);
|
||||
assert.notStrictEqual(closeAt, -1, `call site ${checked + 1}: no closing brace found`);
|
||||
const callArgs = body.slice(at, closeAt);
|
||||
assert.ok(
|
||||
callArgs.split("\n").some((line) => line.trim() === "req,"),
|
||||
`call site ${checked + 1} must pass req, or that tool escapes the fire-time clamp`
|
||||
);
|
||||
checked += 1;
|
||||
at = body.indexOf(callAnchor, closeAt);
|
||||
}
|
||||
assert.strictEqual(checked, 9);
|
||||
});
|
||||
|
||||
test("maybeExecuteDirectBotConsoleCommand still routes execution through runBotAssistantTool (no clamp bypass)", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function maybeExecuteDirectBotConsoleCommand", "maybeExecuteDirectBotConsoleCommand");
|
||||
assert.ok(
|
||||
body.includes("await runBotAssistantTool({"),
|
||||
"the explicit console-command shortcut must execute through the same tool funnel as everything else"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes('name: "send_console_command"'),
|
||||
"the shortcut must run the send_console_command tool (console_write gated)"
|
||||
);
|
||||
assert.ok(
|
||||
body.split("\n").some((line) => line.trim() === "req,"),
|
||||
"the shortcut must forward the (possibly clamped) req"
|
||||
);
|
||||
assert.ok(
|
||||
!body.includes("getEffectivePermsForUserOnServer") && !body.includes("userHasAccessToServer"),
|
||||
"the shortcut must not resolve permissions separately — that would bypass the clamp"
|
||||
);
|
||||
});
|
||||
|
||||
// ─── clamp attachment (processAiAgentJob / buildBackgroundAgentRequest) ─────
|
||||
|
||||
test("buildBackgroundAgentRequest accepts and attaches the clamp, defaulting safely for other callers", () => {
|
||||
const body = functionWindow(INDEX_SRC, "function buildBackgroundAgentRequest", "buildBackgroundAgentRequest");
|
||||
assert.ok(
|
||||
body.includes("function buildBackgroundAgentRequest(user, source = \"ai-agent-job\", permClamp = null)"),
|
||||
"the new third parameter must default to null so existing two-arg callers stay safe"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("aiAgentPermClamp: permClamp || null,"),
|
||||
"the clamp context must be attached to the fake req"
|
||||
);
|
||||
});
|
||||
|
||||
test("processAiAgentJob attaches the clamp only for the planner job sources (scheduler_planner_next AND planner_send)", () => {
|
||||
// adpanel:planner-agent-perms (manual-send parity): planner_send jobs run
|
||||
// planner text authored by another user under the SENDER's identity, exactly
|
||||
// like scheduler_planner_next runs it under the schedule creator's — so the
|
||||
// fire-time clamp's source guard is now the PLANNER_AGENT_JOB_SOURCES
|
||||
// allowlist covering both. Interactive chats, scheduler_prompt and manual
|
||||
// jobs are NOT in the set and still never get a clamp.
|
||||
const body = functionWindow(INDEX_SRC, "async function authorizeAgentJobClaim", "authorizeAgentJobClaim");
|
||||
const guardAt = body.indexOf('if (PLANNER_AGENT_JOB_SOURCES.has(String(row.source || ""))) {');
|
||||
assert.notStrictEqual(
|
||||
guardAt,
|
||||
-1,
|
||||
"a strict PLANNER_AGENT_JOB_SOURCES allowlist guard must exist so interactive/scheduler_prompt/manual jobs never get a clamp while both planner sources always do"
|
||||
);
|
||||
const resolveAuthorAt = body.indexOf("await resolveSchedulerPlannerAuthorForJob(row, serverName)");
|
||||
const attachAt = body.indexOf("aiAgentPermClamp = {");
|
||||
const buildReqAt = body.indexOf("buildBackgroundAgentRequest(user, row.source, aiAgentPermClamp)");
|
||||
assert.notStrictEqual(resolveAuthorAt, -1, "the author must be resolved from the planner item at fire time");
|
||||
assert.notStrictEqual(attachAt, -1, "the clamp object must be attached in the same window");
|
||||
assert.notStrictEqual(buildReqAt, -1, "the req must be built with the clamp as the third argument");
|
||||
assert.ok(guardAt < resolveAuthorAt && resolveAuthorAt < attachAt && attachAt < buildReqAt, "order: source guard -> author resolution -> attachment -> req build");
|
||||
const attach = body.slice(attachAt, buildReqAt);
|
||||
for (const field of ["authorId", "authorResolved", "serverName", "fileEnvelope"]) {
|
||||
assert.ok(attach.includes(field), `the clamp object must carry ${field}`);
|
||||
}
|
||||
assert.match(body, /isSourceCurrent: aiAgentPermClamp \? async \(\) => \(await resolveSchedulerPlannerAuthorForJob\(row, serverName\)\)\.authorResolved/);
|
||||
});
|
||||
|
||||
test("processAiAgentJob attaches the canonicalized serverName to the clamp (never the raw row value)", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function authorizeAgentJobClaim", "authorizeAgentJobClaim");
|
||||
const canonicalAt = body.indexOf('const serverName = String(entry?.name || row.server_name || "").trim();');
|
||||
assert.notStrictEqual(canonicalAt, -1, "the findServer-resolved serverName must be computed in processAiAgentJob");
|
||||
const attachAt = body.indexOf("aiAgentPermClamp = {");
|
||||
const buildReqAt = body.indexOf("buildBackgroundAgentRequest(user, row.source, aiAgentPermClamp)");
|
||||
assert.notStrictEqual(attachAt, -1, "the clamp attachment is missing");
|
||||
assert.notStrictEqual(buildReqAt, -1, "the req build is missing");
|
||||
assert.ok(
|
||||
canonicalAt < attachAt && attachAt < buildReqAt,
|
||||
"order: canonical serverName resolved -> clamp attached -> req built"
|
||||
);
|
||||
const attach = body.slice(attachAt, buildReqAt);
|
||||
// Comments inside the attachment are documentation, not behavior — strip
|
||||
// them so the pin tests the code that runs.
|
||||
const code = attach.split("\n").filter((line) => !line.trim().startsWith("//")).join("\n");
|
||||
assert.ok(
|
||||
code.split("\n").some((line) => line.trim() === "serverName,"),
|
||||
"the clamp must carry the canonicalized serverName variable (shorthand)"
|
||||
);
|
||||
assert.ok(
|
||||
!code.includes("row.server_name"),
|
||||
"a raw row name can be an alias/legacy spelling and would make the persisted-file-envelope-only-on-job-server comparison in applyAiAgentPermClamp miss"
|
||||
);
|
||||
});
|
||||
|
||||
// ─── planner PUT route: authorship follows the last content editor ──────────
|
||||
//
|
||||
// Both halves of the envelope trust created_by_email as "the item author":
|
||||
// queueSchedulerPlannerNextToAgent snapshots the file perms of whoever holds
|
||||
// it, and resolveSchedulerPlannerAuthorForJob re-resolves it at fire time. On
|
||||
// a shared board where any planner_access user can edit any item, an editor
|
||||
// must not be able to launder their prompt text under a more-privileged
|
||||
// colleague's identity (the clamp would then intersect creator x colleague
|
||||
// and let the editor's text keep capabilities like console_write the editor
|
||||
// never had). The PUT route is the only writer that changes item text, so it
|
||||
// must re-stamp created_by_email on every content rewrite.
|
||||
|
||||
test("planner PUT route loads created_by_email and re-stamps it on BOTH update paths", () => {
|
||||
const route = plannerPutRouteWindow("planner PUT route");
|
||||
assert.ok(
|
||||
route.includes("SELECT id, title, prompt, is_done, sort_order, updated_at, created_by_email, ${PLANNER_EDIT_VERSION_SQL} AS edit_version FROM server_planner_items WHERE id = ? AND server_name = ? LIMIT 1"),
|
||||
"the row load must fetch the current author so non-content edits can preserve it"
|
||||
);
|
||||
// Re-point (adpanel:planner-lost-update): each UPDATE statement gained a
|
||||
// conditional isDone-only shape (no title/prompt write, so a toggle cannot
|
||||
// revert a teammate's edit that committed inside the SELECT→UPDATE window)
|
||||
// — all FOUR shapes still re-stamp created_by_email, so the invariant this
|
||||
// pin guards (authorship follows the last content editor on every write
|
||||
// path) is intact.
|
||||
assert.strictEqual(
|
||||
countOccurrences(route, "created_by_email = ?"),
|
||||
4,
|
||||
"all four UPDATE shapes (content/isDone-only x done-flip/plain) must re-stamp created_by_email"
|
||||
);
|
||||
assert.strictEqual(
|
||||
countOccurrences(route, "nextCreatedBy"),
|
||||
4,
|
||||
"nextCreatedBy must be declared once from the stored author, re-stamped at exactly one contentChanged point, and threaded into both parameter arrays"
|
||||
);
|
||||
});
|
||||
|
||||
test("planner PUT changes the authority only when the executable prompt changes", () => {
|
||||
const route = plannerPutRouteWindow("planner PUT route");
|
||||
const hasTitleAt = route.indexOf("const hasTitle = Object.prototype.hasOwnProperty.call(body, 'title');");
|
||||
const hasPromptAt = route.indexOf("const hasPrompt = Object.prototype.hasOwnProperty.call(body, 'prompt');");
|
||||
const hasDoneAt = route.indexOf("const hasDone = Object.prototype.hasOwnProperty.call(body, 'isDone');");
|
||||
const declAt = route.indexOf("let nextCreatedBy = String(current.created_by_email || '');");
|
||||
const promptChangedAt = route.indexOf('const promptChanged = hasPrompt && nextPrompt !== String(current.prompt || "");');
|
||||
const restampAt = route.indexOf("if (promptChanged) nextCreatedBy = ctx.userEmail;");
|
||||
assert.notStrictEqual(hasTitleAt, -1, "title field detection is missing");
|
||||
assert.notStrictEqual(hasPromptAt, -1, "prompt field detection is missing");
|
||||
assert.notStrictEqual(hasDoneAt, -1, "isDone field detection is missing");
|
||||
assert.notStrictEqual(declAt, -1, "the author-preserving declaration is missing");
|
||||
assert.notStrictEqual(promptChangedAt, -1, "the prompt-only byte comparison is missing");
|
||||
assert.notStrictEqual(restampAt, -1, "the prompt-change author re-stamp is missing");
|
||||
assert.ok(
|
||||
hasTitleAt < declAt && hasPromptAt < declAt && hasDoneAt < declAt && declAt < promptChangedAt && promptChangedAt < restampAt,
|
||||
"read the prior author before comparing the actual prompt and restamping"
|
||||
);
|
||||
assert.match(route, /const promptAssignment = promptChanged \? "prompt = \?, prompt_author_id = \?, " : "";/);
|
||||
assert.match(route, /const promptValues = promptChanged \? \[nextPrompt, req\.currentUser\.id\] : \[\];/);
|
||||
assert.strictEqual(countOccurrences(route, '${promptAssignment}is_done = ?'), 2);
|
||||
assert.strictEqual(countOccurrences(route, '[nextTitle, ...promptValues]'), 2);
|
||||
assert.strictEqual(
|
||||
countOccurrences(route, "nextCreatedBy = ctx.userEmail"),
|
||||
1,
|
||||
"authorship must move to the saver at exactly one point, the promptChanged guard"
|
||||
);
|
||||
assert.ok(
|
||||
!route.slice(declAt, promptChangedAt).includes("ctx.userEmail"),
|
||||
"the declaration must not stamp the saver before the prompt comparison"
|
||||
);
|
||||
});
|
||||
|
||||
// ─── system prompt truthfulness (completeAiChatConversation) ────────────────
|
||||
|
||||
test("completeAiChatConversation clamps currentServerPerms before building the system prompt", () => {
|
||||
// Specific anchor: a bare "async function completeAiChatConversation" would
|
||||
// prefix-match completeAiChatConversationWithOpenAiNativeTools, defined earlier.
|
||||
const body = functionWindow(CONVERSATION_SRC, "async function completeAiChatConversation({ req,", "completeAiChatConversation");
|
||||
const lookupAt = body.indexOf("await getEffectivePermsForUserOnServer(userEmail, currentServerEntry.name)");
|
||||
const clampAt = body.indexOf("currentServerPerms = await applyAiAgentPermClamp(req, currentServerPerms, currentServerEntry.name)");
|
||||
const promptAt = body.indexOf("buildBotAssistantSystemPrompt({");
|
||||
assert.notStrictEqual(lookupAt, -1, "the creator-perms lookup is missing");
|
||||
assert.notStrictEqual(clampAt, -1, "the clamp of currentServerPerms is missing");
|
||||
assert.notStrictEqual(promptAt, -1, "the system prompt build is missing");
|
||||
assert.ok(
|
||||
lookupAt < clampAt && clampAt < promptAt,
|
||||
"the model must be told the clamped truth: clamp after lookup, before the system prompt is built"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("let currentServerPerms"),
|
||||
"currentServerPerms must be reassignable"
|
||||
);
|
||||
});
|
||||
|
||||
// ─── direct-console fast path: interactive only ─────────────────────────────
|
||||
|
||||
test("the direct-console fast path is skipped for background agent jobs (second-hand text)", () => {
|
||||
// adpanel:direct-console-fast-path — the fast path regex-scrapes a console
|
||||
// command out of the latest user message and executes send_console_command
|
||||
// BEFORE the model loop, bypassing the <adpanel_tool_plan> provenance guard.
|
||||
// Its trust assumption is that the user typed that text; for background
|
||||
// agent jobs the latest message is queued planner/schedule text authored by
|
||||
// someone else, so destructive execution must fall through to the tool loop
|
||||
// (provenance guard + perms clamp). The gate keys on the /api/ai/background/
|
||||
// path prefix that buildBackgroundAgentRequest is the only producer of.
|
||||
const body = functionWindow(CONVERSATION_SRC, "async function completeAiChatConversation({ req,", "completeAiChatConversation");
|
||||
// adpanel:ai-tool-token-gate — the marker check moved into the shared
|
||||
// isBackgroundAgentJobRequest helper (the AI tool token gate reads the same
|
||||
// one home); the pin tracks the call, and the helper's own body is pinned
|
||||
// to the exact prefix below so the marker semantics cannot drift.
|
||||
const gateAt = body.indexOf("const isBackgroundAgentJob = isBackgroundAgentJobRequest(req);");
|
||||
const fastPathAt = body.indexOf("await maybeExecuteDirectBotConsoleCommand({");
|
||||
assert.notStrictEqual(gateAt, -1, "the background-job gate on the fast path is missing");
|
||||
assert.notStrictEqual(fastPathAt, -1, "the fast path call is missing");
|
||||
assert.ok(gateAt < fastPathAt, "the background gate must precede the fast path call");
|
||||
assert.ok(
|
||||
body.slice(gateAt, fastPathAt).includes("if (!isBackgroundAgentJob) {"),
|
||||
"the fast path must be inside the not-background branch — a background job must reach the model's tool loop"
|
||||
);
|
||||
const markerHelperAt = INDEX_SRC.indexOf("function isBackgroundAgentJobRequest(req) {");
|
||||
assert.notStrictEqual(markerHelperAt, -1, "the shared background marker helper is missing");
|
||||
assert.ok(
|
||||
INDEX_SRC.slice(markerHelperAt, INDEX_SRC.indexOf("\n}", markerHelperAt)).includes('String(req?.path || "").startsWith("/api/ai/background/")'),
|
||||
"the marker helper must key on the /api/ai/background/ prefix"
|
||||
);
|
||||
// The marker path must never become a real route: the gate keys on it.
|
||||
assert.ok(
|
||||
!/app\.(get|post|put|delete|use)\("\/api\/ai\/background/.test(INDEX_SRC),
|
||||
"no express route may serve /api/ai/background/* — buildBackgroundAgentRequest is its only producer and the fast-path gate keys on that prefix"
|
||||
);
|
||||
});
|
||||
|
||||
test("tools and job file permissions reuse the same planner clamp", () => {
|
||||
assert.strictEqual(
|
||||
countOccurrences(INDEX_SRC + CONVERSATION_SRC, "await applyAiAgentPermClamp(req,"),
|
||||
2,
|
||||
"every capability gate must reach the clamp through resolveBotToolServerOrError or the system-prompt build — no third, unsynced path"
|
||||
);
|
||||
assert.match(INDEX_SRC, /req\.readAiAgentFilePermissions = async \(\) => applyAiAgentPermClamp\(req, await req\.readAiAgentJobPermissions\(\), serverName\)/);
|
||||
});
|
||||
|
||||
test("the shared clamp classifies persisted envelopes and never grants authority when the author is unresolved", () => {
|
||||
const clampBody = functionWindow(INDEX_SRC, "async function applyAiAgentPermClamp", "applyAiAgentPermClamp");
|
||||
assert.ok(
|
||||
clampBody.includes("classifyFilePermEnvelope(clamp.fileEnvelope).envelope"),
|
||||
"the fire-time capability clamp must classify the persisted envelope (absent -> legacy fallback, unparseable -> all-false)"
|
||||
);
|
||||
assert.doesNotMatch(clampBody, /normalizeFilePermEnvelope\(/);
|
||||
assert.match(clampBody, /authorResolved: !!clamp\.authorResolved && resolution\.resolved/);
|
||||
assert.doesNotMatch(INDEX_SRC, /function resolveSchedulerPlannerPermsOverride\(/);
|
||||
// The write-time consumer (insertAiAgentChatJob) keeps the normalizer: it
|
||||
// normalizes the IN-PROCESS envelope before persisting, never a readback.
|
||||
const insertBody = functionWindow(INDEX_SRC, "async function insertAiAgentChatJob", "insertAiAgentChatJob");
|
||||
assert.ok(
|
||||
insertBody.includes("normalizeFilePermEnvelope(permFileEnvelope)"),
|
||||
"the only writer must keep normalizing the in-process envelope it is about to persist"
|
||||
);
|
||||
});
|
||||
|
||||
// ─── enqueue-time behavior must remain untouched ────────────────────────────
|
||||
|
||||
test("queueSchedulerPlannerNextToAgent still snapshots the file-only envelope at enqueue time (through the ONE shared capture helper)", () => {
|
||||
// adpanel:planner-agent-perms (manual-send parity): the enqueue-time
|
||||
// capture moved into buildPlannerItemFilePermEnvelope so the send-agent
|
||||
// route (planner_send) builds the IDENTICAL envelope instead of a drifting
|
||||
// copy. The scheduler side must call that helper with the same
|
||||
// storedServerName the whole enqueue path keys on and pass the result as
|
||||
// permFileEnvelope.
|
||||
const body = functionWindow(INDEX_SRC, "async function queueSchedulerPlannerNextToAgent", "queueSchedulerPlannerNextToAgent");
|
||||
const helperAt = body.indexOf("const permFileEnvelope = await buildPlannerItemFilePermEnvelope({");
|
||||
assert.notStrictEqual(
|
||||
helperAt,
|
||||
-1,
|
||||
"the enqueue-time file-only snapshot must be captured through the shared helper, not a copied author-verification block"
|
||||
);
|
||||
const helperCall = body.slice(helperAt, body.indexOf("});", helperAt));
|
||||
assert.ok(
|
||||
helperCall.includes("serverName: storedServerName,"),
|
||||
"the capture must key on storedServerName (the resolved entry.name the whole enqueue path keys on — adpanel:planner-job-retract)"
|
||||
);
|
||||
assert.ok(
|
||||
helperCall.includes("authorId: plannerItem.prompt_author_id"),
|
||||
"the capture must use the item's immutable prompt-author ID"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("permFileEnvelope,"),
|
||||
"the persisted envelope must ride the insert payload"
|
||||
);
|
||||
assert.ok(
|
||||
!body.includes("aiAgentPermClamp"),
|
||||
"enqueue must not pre-resolve the fire-time clamp — the author is re-verified at execution time"
|
||||
);
|
||||
});
|
||||
|
||||
test("buildPlannerItemFilePermEnvelope uses the shared author verification and pins the immutable ID", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function buildPlannerItemFilePermEnvelope", "buildPlannerItemFilePermEnvelope");
|
||||
const verificationAt = body.indexOf("await resolveSchedulerPlannerAuthorPermsOnServer(accountId, serverName)");
|
||||
assert.notStrictEqual(
|
||||
verificationAt,
|
||||
-1,
|
||||
"the enqueue-time author verification must use the same account and ACL checks as dispatch"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("intersectFilePerms(creatorPerms, author.isAdmin ? creatorPerms : author.perms)"),
|
||||
"the envelope stays the per-flag AND of creator and author FILE perms (the legacy file-only contract)"
|
||||
);
|
||||
const pinAt = body.indexOf("envelope.author_id = accountId;");
|
||||
assert.notStrictEqual(pinAt, -1, "the author identity must be pinned on the envelope (adpanel:planner-agent-author-pin)");
|
||||
assert.ok(pinAt > verificationAt, "the pin rides the envelope built from the verified author");
|
||||
});
|
||||
|
||||
test("insertAiAgentChatJob still persists the same envelope column and signature", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function insertAiAgentChatJob", "insertAiAgentChatJob");
|
||||
assert.ok(
|
||||
body.includes("permFileEnvelope = null"),
|
||||
"the signature must keep the optional envelope parameter"
|
||||
);
|
||||
const admission = functionWindow(fs.readFileSync(require.resolve("../AgentWorker/admission"), "utf8"),
|
||||
"async function storeAgentSubmission", "storeAgentSubmission");
|
||||
assert.match(admission, /source_ref,\s*perm_file_envelope,\s*feature_generation/,
|
||||
"the envelope column must stay between the source reference and generation");
|
||||
assert.match(admission, /reviewParent\s*\?\s*`\$\{REVIEW_SOURCE_REF_PREFIX\}\$\{reviewParent\.id\}`\s*:\s*sourceRef,\s*envelope,\s*automaticFileEdits \? null : state\.generation,/,
|
||||
"ordinary Planner jobs must bind their source reference, envelope, and generation in column order");
|
||||
assert.match(body, /const authorId = pinnedPlannerAuthorIdFromEnvelope\(permFileEnvelope\)/);
|
||||
assert.match(body, /JSON\.stringify\(\{ \.\.\.normalizedEnvelope, \.\.\.\(authorId && \{ author_id: authorId \}\) \}\)/);
|
||||
assert.ok(
|
||||
!body.includes("aiAgentPermClamp"),
|
||||
"the job row carries only the file envelope; the clamp context is fire-time only"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 9. Author VISIBILITY gate for the no-permission information tools.
|
||||
//
|
||||
// The capability clamp cannot bound tools that require NO permission: for
|
||||
// list_accessible_servers / inspect_server / get_server_status the clamped
|
||||
// projection is computed but nothing consumes it, so a background planner job
|
||||
// could enumerate (or status-poll) servers its author has no ACL on, and
|
||||
// exfiltrate the model's reply through file operations the clamp legitimately
|
||||
// grants the author (files_read + files_create on the job's own server). The
|
||||
// gate below bounds VISIBILITY on the author of record, mirroring the
|
||||
// interactive rule (an ACL entry on the server = can see it).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("resolveAiAgentClampAuthorAccess checks live access and fails closed on an unresolvable author", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function resolveAiAgentClampAuthorAccess", "resolveAiAgentClampAuthorAccess");
|
||||
assert.ok(
|
||||
!body.includes("_authorPermsCache"),
|
||||
"revocation must also apply to server inventory visibility"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("resolveSchedulerPlannerAuthorPermsOnServer"),
|
||||
"the visibility decision must resolve the author through the same verification the capability clamp uses"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("clamp.authorResolved") && body.includes("resolution.isAdmin"),
|
||||
"an admin author must count as having access (identity branch), an unresolvable author must fail closed"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("if (!clamp) return { clamped: false, authorHasAccess: true };"),
|
||||
"no clamp on the req (interactive chats, every other job source) must be a no-op"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("resolution.perms !== null || resolution.isAdmin === true"),
|
||||
"the access expression itself is load-bearing: inverting it (=== null) would flip the fail-closed direction into deny-admin / allow-unresolvable"
|
||||
);
|
||||
});
|
||||
|
||||
test("the system prompt's server-name inventory is author-filtered for planner jobs", () => {
|
||||
// Specific anchor: a bare "async function completeAiChatConversation" would
|
||||
// prefix-match completeAiChatConversationWithOpenAiNativeTools, defined earlier.
|
||||
const body = functionWindow(CONVERSATION_SRC, "async function completeAiChatConversation({ req,", "completeAiChatConversation");
|
||||
assert.ok(
|
||||
body.includes("promptAccessibleServers"),
|
||||
"the prompt's server list must be a separate, filterable variable — the tool universe stays unfiltered"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("req.aiAgentPermClamp") && body.includes("resolveAiAgentClampAuthorAccess"),
|
||||
"the filter must key on the clamp and reuse the shared author-access decision"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("accessibleServers: promptAccessibleServers"),
|
||||
"buildBotAssistantSystemPrompt must receive the filtered list — server names embedded in the prompt are exfiltratable through file operations the author holds"
|
||||
);
|
||||
});
|
||||
|
||||
test("resolveBotToolServerOrError applies the author-visibility gate AFTER the permission check", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function resolveBotToolServerOrError", "resolveBotToolServerOrError");
|
||||
assert.ok(
|
||||
body.includes("requireClampedServerAccess = false"),
|
||||
"the visibility gate must be strictly opt-in so every existing call site keeps its behavior"
|
||||
);
|
||||
const gateAt = body.indexOf("if (requireClampedServerAccess)");
|
||||
const missingAt = body.indexOf("const missingPerms = requiredPerms.filter");
|
||||
assert.notStrictEqual(gateAt, -1, "visibility gate missing from the funnel");
|
||||
assert.notStrictEqual(missingAt, -1, "missingPerms check missing from the funnel");
|
||||
assert.ok(
|
||||
gateAt > missingAt,
|
||||
"the visibility gate must run after the capability check so clamped permission errors keep priority"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("clampAccess.clamped && !clampAccess.authorHasAccess"),
|
||||
"the gate must deny only when a clamp is present AND the author has no ACL access on the target server"
|
||||
);
|
||||
});
|
||||
|
||||
test("exactly the two information tools opt into the author-visibility gate", () => {
|
||||
const body = functionWindow(INDEX_SRC, "async function runBotAssistantTool", "runBotAssistantTool");
|
||||
assert.strictEqual(
|
||||
countOccurrences(body, "requireClampedServerAccess: true"),
|
||||
2,
|
||||
"inspect_server and get_server_status are the only no-permission tools; every capability tool must keep gating on requiredPerms alone"
|
||||
);
|
||||
const inspectAt = body.indexOf('case "inspect_server"');
|
||||
const firstGateAt = body.indexOf("requireClampedServerAccess: true");
|
||||
const statusAt = body.indexOf('case "get_server_status"');
|
||||
const secondGateAt = body.indexOf("requireClampedServerAccess: true", firstGateAt + 1);
|
||||
assert.ok(
|
||||
inspectAt !== -1 && firstGateAt > inspectAt && firstGateAt < body.indexOf('case "power_server"'),
|
||||
"the first visibility-gated call site must be inspect_server"
|
||||
);
|
||||
assert.ok(
|
||||
statusAt !== -1 && secondGateAt > statusAt,
|
||||
"the second visibility-gated call site must be get_server_status"
|
||||
);
|
||||
});
|
||||
|
||||
test("list_accessible_servers filters the creator's list through the author-visibility gate for planner jobs", () => {
|
||||
const body = functionWindow(INDEX_SRC, 'case "list_accessible_servers"', "list_accessible_servers");
|
||||
assert.ok(
|
||||
body.includes("req.aiAgentPermClamp"),
|
||||
"the filter must key on the clamp so interactive chats keep the creator's full list"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("resolveAiAgentClampAuthorAccess"),
|
||||
"the filter must use the shared author-access decision, not a bespoke lookup"
|
||||
);
|
||||
assert.ok(
|
||||
body.includes("visibleServers = visibleServers.filter"),
|
||||
"the filter must remove servers the author has no ACL on instead of denying the whole call"
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user