Files
Kelx/tests/ai-tool-token-gate.test.js
T
2026-11-30 16:32:37 +00:00

451 lines
23 KiB
JavaScript

"use strict";
// adpanel:ai-tool-token-gate — the AI chat was the one browser-driven entry
// to the mutating backup operations whose sibling surfaces (the node relay
// routes) all verify session-bound action tokens, so a cookie-authenticated
// request from a CSRF_ALLOWED_HOSTS-trusted origin — the one vector
// sameOriginProtection deliberately permits — could drive the victim's
// session through POST /api/ai/chat into restore (deleteOldFiles wipe) or
// repeated backup deletes. The fix gates the AI-ONLY tool wrappers (never the
// shared performers — the relays already gate, and gating inside the
// performers would double-gate them) on the relay twins' EXACT mint/verify
// pairs. This file pins, in the slice-and-eval style of
// backup-create-cap-refusal.test.js (index.js and nodes.js boot servers on
// require and cannot be loaded in-process):
//
// * the tool→twin-gate matrix — exactly the backup trio is gated, each with
// the byte-identical action string its nodes.js relay verifies and the
// tokenKey GET /permissions mints for it; power_server / start_server /
// stop_server / kill_server / send_console_command are deliberately
// absent (their relay twins /action and /command mount NO token gate, so
// there is no twin contract to mirror), as are the five read-only tools;
// * the REAL gate function over the REAL issue/verify token machinery — a
// valid mint passes, a missing/foreign-action/wrong-server/expired/
// garbage token fails with the path-free recovery message, and the
// background agent-job req (which can never hold a session-bound token;
// its enqueue paths are already gated) is exempt;
// * the per-case wiring — each gated tool case calls the gate after the
// perms resolution and BEFORE its performer wrapper;
// * the non-negotiables — the chat route itself stays ungated (non-mutating
// chat must keep working) and the shared performers stay ungated;
// * the client half — the ONE chat sender attaches the page's mints under
// body.actionTokens, keyed and perm-matched to the server's mints.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const crypto = require("node:crypto");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const NODES_JS = path.join(ROOT, "nodes.js");
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const nodesSource = fs.readFileSync(NODES_JS, "utf8");
const botSource = fs.readFileSync(BOT_JS, "utf8");
// Strip full-line comments so prose mentioning the markers cannot satisfy the
// source-level assertions (same technique as backup-create-cap-refusal.test.js).
function stripFullLineComments(src) {
return src
.split("\n")
.filter((line) => !/^\s*\/\//.test(line))
.join("\n");
}
const indexCode = stripFullLineComments(indexSource);
const nodesCode = stripFullLineComments(nodesSource);
const botCode = stripFullLineComments(botSource);
function sliceFrom(source, startMarker, endMarker, label) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
// ---------------------------------------------------------------------------
// The REAL token machinery, sliced and evaluated with injected fakes for the
// durable-nonce claim only (that path is Redis-backed in the monolith and is
// not this fix's concern; everything else — HMAC signature, uid/sid binding,
// action string, expiry, resource binding — is the REAL verifier).
// ---------------------------------------------------------------------------
process.env.SESSION_SECRET = process.env.SESSION_SECRET || "ai-tool-token-gate-test-secret";
delete process.env.ACTION_TOKEN_SECRET;
const cryptoBlockSrc = sliceFrom(
indexSource,
"function safeCompare",
"function signSshTerminalPayload",
"index.js action-token crypto block"
);
const {
safeCompare, b64urlEncode, b64urlDecode, stableStringify, signActionPayload,
} = new Function(
"crypto",
`"use strict";
${cryptoBlockSrc}
return { safeCompare, b64urlEncode, b64urlDecode, stableStringify, signActionPayload };`
)(crypto);
const issueTokenSrc = sliceFrom(
indexSource,
"function issueActionToken",
"function getActionTokenFromRequest",
"index.js issueActionToken"
);
const issueActionToken = new Function(
"crypto", "b64urlEncode", "signActionPayload", "stableStringify",
`"use strict";
${issueTokenSrc}
return issueActionToken;`
)(crypto, b64urlEncode, signActionPayload, stableStringify);
const verifyTokenSrc = sliceFrom(
indexSource,
"async function verifyActionToken",
"async function requireActionTokenOr403",
"index.js verifyActionToken"
);
const mapReaderSrc = sliceFrom(
indexSource,
"function getActionTokenMapFromRequest",
"\nfunction markNonceUsed",
"index.js getActionTokenMapFromRequest"
);
const getActionTokenMapFromRequest = new Function(
`"use strict";
${mapReaderSrc}
return getActionTokenMapFromRequest;`
)();
const markerSrc = sliceFrom(
indexSource,
"function isBackgroundAgentJobRequest",
"\nasync function resolveBotToolServerOrError",
"index.js isBackgroundAgentJobRequest"
);
const isBackgroundAgentJobRequest = new Function(
`"use strict";
${markerSrc}
return isBackgroundAgentJobRequest;`
)();
function makeVerifyActionToken({ claimActionNonce, markNonceUsed }) {
return new Function(
"safeCompare", "b64urlDecode", "stableStringify", "signActionPayload", "claimActionNonce", "markNonceUsed",
`"use strict";
${verifyTokenSrc}
return verifyActionToken;`
)(safeCompare, b64urlDecode, stableStringify, signActionPayload, claimActionNonce, markNonceUsed);
}
const gateBlockSrc = sliceFrom(
indexSource,
"const AI_TOOL_ACTION_TOKEN_GATES",
"\nasync function listAiServerBackups",
"index.js ai tool action-token gate"
);
function makeGate({ verifyCalls = null } = {}) {
const verifyActionToken = makeVerifyActionToken({
claimActionNonce: async () => {
if (verifyCalls) verifyCalls.claims += 1;
return true;
},
markNonceUsed: () => {
if (verifyCalls) verifyCalls.marks += 1;
return true;
},
});
verifyActionToken.calls = () => {
if (verifyCalls) verifyCalls.verifies += 1;
return true;
};
const wrappedVerify = async (...args) => {
if (verifyCalls) verifyCalls.verifies += 1;
return verifyActionToken(...args);
};
return new Function(
"isBackgroundAgentJobRequest", "getActionTokenMapFromRequest", "verifyActionToken",
`"use strict";
${gateBlockSrc}
return { AI_TOOL_ACTION_TOKEN_GATES, AI_TOOL_ACTION_TOKEN_ERROR, aiToolActionTokenGateError };`
)(isBackgroundAgentJobRequest, getActionTokenMapFromRequest, wrappedVerify);
}
const { AI_TOOL_ACTION_TOKEN_GATES, AI_TOOL_ACTION_TOKEN_ERROR, aiToolActionTokenGateError } = makeGate();
const SESSION_USER = "owner@example.com";
const SESSION_ID = "sess-1";
const CANONICAL_SERVER = "srv01";
function makeMintReq() {
return { session: { user: SESSION_USER }, sessionID: SESSION_ID };
}
function makeChatReq({ path = "/api/ai/chat", actionTokens = null, body = null } = {}) {
return {
method: "POST",
path,
session: { user: SESSION_USER },
sessionID: SESSION_ID,
body: body !== null ? body : (actionTokens ? { actionTokens } : {}),
};
}
// ---------------------------------------------------------------------------
// 1. The tool→twin-gate matrix: exactly the backup trio, byte-identical action
// strings to the nodes.js relays, tokenKeys the permissions mint issues.
// ---------------------------------------------------------------------------
test("the gate covers exactly the three backup tools, keyed to the permissions mints", () => {
assert.deepStrictEqual(Object.keys(AI_TOOL_ACTION_TOKEN_GATES).sort(), [
"create_backup", "delete_backup", "restore_backup",
]);
assert.strictEqual(AI_TOOL_ACTION_TOKEN_GATES.create_backup.tokenKey, "backupCreate");
assert.strictEqual(AI_TOOL_ACTION_TOKEN_GATES.create_backup.action, "POST /backups");
assert.strictEqual(AI_TOOL_ACTION_TOKEN_GATES.restore_backup.tokenKey, "backupRestore");
assert.strictEqual(AI_TOOL_ACTION_TOKEN_GATES.restore_backup.action, "POST /backups/:id/restore");
assert.strictEqual(AI_TOOL_ACTION_TOKEN_GATES.delete_backup.tokenKey, "backupDelete");
assert.strictEqual(AI_TOOL_ACTION_TOKEN_GATES.delete_backup.action, "DELETE /backups/:id");
});
test("every gated action string is byte-identical to the twin's requireNodeFileActionToken gate in nodes.js", () => {
assert.ok(nodesCode.includes('requireNodeFileActionToken("POST /backups")'),
"create twin relay must gate on POST /backups");
assert.ok(nodesCode.includes('requireNodeFileActionToken("POST /backups/:id/restore")'),
"restore twin relay must gate on POST /backups/:id/restore");
assert.ok(nodesCode.includes('requireNodeFileActionToken("DELETE /backups/:id")'),
"delete twin relay must gate on DELETE /backups/:id");
// ...and the mints the client attaches are the same pairs (GET /permissions).
assert.ok(indexCode.includes('actionTokens.backupCreate = issueActionToken(req, "POST /backups", { serverName }, { ttlSeconds: 300 })'),
"permissions mint must bind backupCreate to POST /backups");
assert.ok(indexCode.includes('actionTokens.backupRestore = issueActionToken(req, "POST /backups/:id/restore", { serverName }, { ttlSeconds: 120, oneTime: true })'),
"permissions mint must bind backupRestore to POST /backups/:id/restore (one-time)");
assert.ok(indexCode.includes('actionTokens.backupDelete = issueActionToken(req, "DELETE /backups/:id", { serverName }, { ttlSeconds: 120, oneTime: true })'),
"permissions mint must bind backupDelete to DELETE /backups/:id (one-time)");
});
test("power/console tools are deliberately absent: their relay twins mount no token gate", () => {
const botAiTools = require("../utils/bot-ai-tools");
const allNames = botAiTools.BOT_TOOL_DEFINITIONS.map((tool) => tool.name);
for (const name of allNames) {
if (botAiTools.isBotReadonlyToolName(name)) {
assert.ok(!AI_TOOL_ACTION_TOKEN_GATES[name], `read-only tool must not be gated: ${name}`);
}
}
for (const mutatingUngated of ["power_server", "start_server", "stop_server", "kill_server", "send_console_command"]) {
assert.ok(!AI_TOOL_ACTION_TOKEN_GATES[mutatingUngated],
`${mutatingUngated} has no token-gated relay twin and must stay ungated`);
}
// The twins really are gate-free: the /action and /command relay routes
// mount no requireNodeFileActionToken (their gate-free state is the relay
// surface's documented contract — this fix must not fork a new scheme).
const actionRelay = sliceFrom(nodesSource, 'app.post("/api/nodes/server/:name/action"', 'app.post("/api/nodes/server/:name/eula/accept"', "action relay");
const commandRelay = sliceFrom(nodesSource, 'app.post("/api/nodes/server/:name/command"', 'app.post("/api/nodes/:id/server/action"', "command relay");
assert.ok(!actionRelay.includes("requireNodeFileActionToken"), "action relay must stay gate-free");
assert.ok(!commandRelay.includes("requireNodeFileActionToken"), "command relay must stay gate-free");
});
// ---------------------------------------------------------------------------
// 2. The REAL gate over the REAL token machinery.
// ---------------------------------------------------------------------------
test("a valid page mint passes the gate for its tool and canonical server", async () => {
const token = issueActionToken(makeMintReq(), "POST /backups", { serverName: CANONICAL_SERVER }, { ttlSeconds: 300 });
const result = await aiToolActionTokenGateError(
makeChatReq({ actionTokens: { backupCreate: token } }), "create_backup", CANONICAL_SERVER
);
assert.strictEqual(result, null);
});
test("a valid one-time restore mint passes the gate", async () => {
const verifyState = { claims: 0, marks: 0, verifies: 0 };
const gate = makeGate({ verifyCalls: verifyState });
const token = issueActionToken(makeMintReq(), "POST /backups/:id/restore", { serverName: CANONICAL_SERVER }, { ttlSeconds: 120, oneTime: true });
const result = await gate.aiToolActionTokenGateError(
makeChatReq({ actionTokens: { backupRestore: token } }), "restore_backup", CANONICAL_SERVER
);
assert.strictEqual(result, null);
assert.strictEqual(verifyState.claims, 1, "one-time mint must take the durable claim");
});
test("a missing token map fails the gate with the path-free recovery message", async () => {
const result = await aiToolActionTokenGateError(makeChatReq({ body: {} }), "create_backup", CANONICAL_SERVER);
assert.ok(result && result.ok === false);
assert.strictEqual(result.error, AI_TOOL_ACTION_TOKEN_ERROR);
assert.match(result.error, /[Rr]efresh the page/);
assert.ok(!result.error.includes("/"), "message must stay path-free");
assert.ok(!result.error.includes(CANONICAL_SERVER), "message must not leak the server name");
});
test("a map without the fired tool's token fails the gate", async () => {
const token = issueActionToken(makeMintReq(), "POST /backups", { serverName: CANONICAL_SERVER }, { ttlSeconds: 300 });
const result = await aiToolActionTokenGateError(
makeChatReq({ actionTokens: { backupCreate: token } }), "delete_backup", CANONICAL_SERVER
);
assert.ok(result && result.ok === false);
assert.strictEqual(result.error, AI_TOOL_ACTION_TOKEN_ERROR);
});
test("a token minted for a different action fails the gate without consuming a one-time nonce", async () => {
const verifyState = { claims: 0, marks: 0, verifies: 0 };
const gate = makeGate({ verifyCalls: verifyState });
// backupCreate is a repeatable mint; fired against restore_backup its
// action string mismatches BEFORE the nonce stage (it is not one-time, but
// restore's own one-time flow would be — the ordering is what matters).
const token = issueActionToken(makeMintReq(), "POST /backups", { serverName: CANONICAL_SERVER }, { ttlSeconds: 300, oneTime: true });
const result = await gate.aiToolActionTokenGateError(
makeChatReq({ actionTokens: { backupRestore: token } }), "restore_backup", CANONICAL_SERVER
);
assert.ok(result && result.ok === false);
assert.strictEqual(result.error, AI_TOOL_ACTION_TOKEN_ERROR);
assert.strictEqual(verifyState.claims, 0, "resource/action mismatch must not burn the nonce");
});
test("a token minted for a different server fails the gate", async () => {
const token = issueActionToken(makeMintReq(), "POST /backups", { serverName: "other-server" }, { ttlSeconds: 300 });
const result = await aiToolActionTokenGateError(
makeChatReq({ actionTokens: { backupCreate: token } }), "create_backup", CANONICAL_SERVER
);
assert.ok(result && result.ok === false);
assert.strictEqual(result.error, AI_TOOL_ACTION_TOKEN_ERROR);
});
test("an expired token fails the gate", async () => {
const token = issueActionToken(makeMintReq(), "POST /backups", { serverName: CANONICAL_SERVER }, { ttlSeconds: -10 });
const result = await aiToolActionTokenGateError(
makeChatReq({ actionTokens: { backupCreate: token } }), "create_backup", CANONICAL_SERVER
);
assert.ok(result && result.ok === false);
assert.strictEqual(result.error, AI_TOOL_ACTION_TOKEN_ERROR);
});
test("a garbage or foreign-signed token fails the gate", async () => {
const result = await aiToolActionTokenGateError(
makeChatReq({ actionTokens: { backupCreate: "not.a.real.token" } }), "create_backup", CANONICAL_SERVER
);
assert.ok(result && result.ok === false);
assert.strictEqual(result.error, AI_TOOL_ACTION_TOKEN_ERROR);
});
test("a token bound to another session fails the gate", async () => {
const mintReq = { session: { user: SESSION_USER }, sessionID: "someone-else" };
const token = issueActionToken(mintReq, "POST /backups", { serverName: CANONICAL_SERVER }, { ttlSeconds: 300 });
const result = await aiToolActionTokenGateError(
makeChatReq({ actionTokens: { backupCreate: token } }), "create_backup", CANONICAL_SERVER
);
assert.ok(result && result.ok === false);
assert.strictEqual(result.error, AI_TOOL_ACTION_TOKEN_ERROR);
});
test("background agent-job requests are exempt: they can never hold a session-bound token", async () => {
const req = {
method: "POST",
path: "/api/ai/background/scheduler_planner_next",
session: { user: SESSION_USER },
sessionID: "background:1",
body: {},
};
assert.strictEqual(isBackgroundAgentJobRequest(req), true);
const result = await aiToolActionTokenGateError(req, "restore_backup", CANONICAL_SERVER);
assert.strictEqual(result, null, "the enqueue paths already gate; the gate must not fail-only here");
});
test("non-mutating and unknown tools bypass the gate entirely (no verifier work)", async () => {
const verifyState = { claims: 0, marks: 0, verifies: 0 };
const gate = makeGate({ verifyCalls: verifyState });
for (const toolName of ["list_backups", "inspect_server", "query_console", "list_accessible_servers", "get_server_status", "no_such_tool"]) {
const result = await gate.aiToolActionTokenGateError(makeChatReq({ body: {} }), toolName, CANONICAL_SERVER);
assert.strictEqual(result, null, `${toolName} must be ungated`);
}
assert.strictEqual(verifyState.verifies, 0, "ungated tools must not reach the verifier");
});
test("the map reader accepts only a plain object map", () => {
assert.strictEqual(getActionTokenMapFromRequest({ body: {} }), null);
assert.strictEqual(getActionTokenMapFromRequest({ body: { actionTokens: "x" } }), null);
assert.strictEqual(getActionTokenMapFromRequest({ body: { actionTokens: ["a"] } }), null);
assert.strictEqual(getActionTokenMapFromRequest({ body: { actionTokens: null } }), null);
assert.strictEqual(getActionTokenMapFromRequest({}), null);
assert.deepStrictEqual(getActionTokenMapFromRequest({ body: { actionTokens: { backupCreate: "t" } } }), { backupCreate: "t" });
});
// ---------------------------------------------------------------------------
// 3. Per-case wiring: gate after perms resolution, before the performer call;
// the chat route itself stays ungated; the shared performers stay ungated.
// ---------------------------------------------------------------------------
test("each gated tool case calls the gate after the perms resolution and before its wrapper", () => {
const createCase = sliceFrom(indexCode, 'case "create_backup": {', 'case "restore_backup":', "create_backup case");
const gateCall = "aiToolActionTokenGateError(req, toolName, entry.name)";
assert.ok(createCase.includes(gateCall), "create_backup case must call the gate");
assert.ok(createCase.indexOf('if (error) return error;') < createCase.indexOf(gateCall),
"create_backup gate must fire after the perms resolution");
assert.ok(createCase.indexOf(gateCall) < createCase.indexOf("createAiServerBackup("),
"create_backup gate must fire before the performer wrapper");
const restoreDeleteCase = sliceFrom(indexCode, 'case "restore_backup":\n case "delete_backup": {', "\n default:", "restore/delete case");
assert.ok(restoreDeleteCase.includes(gateCall), "restore/delete case must call the gate");
assert.ok(restoreDeleteCase.indexOf('if (error) return error;') < restoreDeleteCase.indexOf(gateCall),
"restore/delete gate must fire after the perms resolution");
assert.ok(restoreDeleteCase.indexOf(gateCall) < restoreDeleteCase.indexOf("listAiServerBackups("),
"restore/delete gate must fire before any listing/daemon work");
});
test("the queued chat route keeps session and Agent entitlement without a tool action token", () => {
const chatRoute = fs.readFileSync(require.resolve("../routes/agent-live"), "utf8");
assert.ok(indexCode.includes('app.use("/api/ai", createAgentLiveRouter({'));
assert.ok(chatRoute.includes('router.post("/chat", authorize,'));
assert.ok(chatRoute.includes("isAuthenticated(req)"), "chat route keeps its session gate");
assert.ok(chatRoute.includes("hasAgentAccess(req)"), "chat route keeps its agent-access gate");
assert.ok(!chatRoute.includes("requireActionTokenOr403"), "chat route must NOT be token-gated globally");
assert.ok(!chatRoute.includes("verifyActionToken"), "chat route must NOT verify tokens itself");
});
test("the shared backup performers stay ungated (the relays gate; double-gating is forbidden)", () => {
const createPerformer = sliceFrom(nodesCode, "async function performPanelCreateBackup", "\nasync function performPanelRestoreBackup", "create performer");
const restorePerformer = sliceFrom(nodesCode, "async function performPanelRestoreBackup", "\nasync function performPanelDeleteBackup", "restore performer");
const deletePerformer = sliceFrom(nodesCode, "async function performPanelDeleteBackup", "\nfunction relayPanelResult", "delete performer");
for (const [label, slice] of [["create", createPerformer], ["restore", restorePerformer], ["delete", deletePerformer]]) {
assert.ok(!slice.includes("requireNodeFileActionToken"), `${label} performer must stay ungated`);
assert.ok(!slice.includes("requireActionTokenOr403"), `${label} performer must stay ungated`);
assert.ok(!slice.includes("verifyActionToken"), `${label} performer must stay ungated`);
}
});
// ---------------------------------------------------------------------------
// 4. The client half: the ONE chat sender attaches the page's mints.
// ---------------------------------------------------------------------------
test("callAiBackendProxy collects the action tokens before building the chat body", () => {
const sender = sliceFrom(botCode, "async function callAiBackendProxy", "function parseAiResponse", "chat sender");
assert.ok(sender.includes("const actionTokens = await collectAiChatActionTokens();"),
"the sender must collect the tokens first");
assert.ok(sender.indexOf("collectAiChatActionTokens()") < sender.indexOf("body: JSON.stringify("),
"collection must happen before the body is built");
assert.ok(sender.includes("actionTokens,"), "the body must carry the actionTokens map");
assert.ok(sender.includes("'/api/ai/chat'"), "still the one chat endpoint");
});
test("the collector maps each token key to the perm that mints it, and degrades without throwing", () => {
const collector = sliceFrom(botCode, "const AI_CHAT_ACTION_TOKEN_KEYS = [", "async function callAiBackendProxy", "token collector");
assert.ok(collector.includes("{ tokenKey: 'backupRestore', perm: 'backups_create' }"),
"backupRestore is minted under backups_create (same mint block as backupCreate)");
assert.ok(collector.includes("{ tokenKey: 'backupCreate', perm: 'backups_create' }"),
"backupCreate is minted under backups_create");
assert.ok(collector.includes("{ tokenKey: 'backupDelete', perm: 'backups_delete' }"),
"backupDelete is minted under backups_delete");
assert.ok(collector.includes("ensureServerActionToken("), "collection goes through the existing token store");
assert.ok(collector.includes("if (token) tokens[entry.tokenKey] = token;"),
"missing mints degrade to sending without the token");
// Skipping without a fetch when the user's perms exclude the mint.
assert.ok(collector.includes("!hasPerm(entry.perm)"), "perm-excluded keys must be skipped");
});