返回 CodeWhale
consent.test.mjs
根目录 / crates / tui / plugins / computer-use / tests / consent.test.mjs
1 // Per-app consent: the app, not the tool, is the unit of trust on the local
2 // computer. Unit tests pin the ledger; server tests prove the gate refuses
3 // before backend dispatch, cannot be sidestepped by re-spelling the app, and
4 // that foreground control is a separate consent from app access.
5 import { hostKeysLine, attest, attestParams, TEST_LEDGER_KEY, ledgerMac } from "./fixtures/host-decision.mjs";
6 import { test } from "node:test";
7 import assert from "node:assert/strict";
8 import fs from "node:fs";
9 import os from "node:os";
10 import path from "node:path";
11 import url from "node:url";
12 import { spawn } from "node:child_process";
13 import * as consent from "../src/consent.mjs";
14 import { dockerAvailable } from "../src/spawn.mjs";
15
16 const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), "..");
17 const DOCKER = await dockerAvailable();
18 const NEED_DOCKER = { skip: !DOCKER && "docker daemon not available" };
19
20 let tmpSeq = 0;
21 function freshDir() {
22 const dir = fs.mkdtempSync(path.join(os.tmpdir(), `cu-consent-${tmpSeq++}-`));
23 process.env.CODEWHALE_CU_STATE_DIR = dir;
24 return dir;
25 }
26 // The unit tests run as the host would configure the plugin: remembered
27 // allows are signed with the ledger key.
28 consent.setLedgerKey(Buffer.from(TEST_LEDGER_KEY, "hex"));
29 // Every test gets a clean store and a clean session map key space.
30 let cidSeq = 0;
31 const cid = () => `c${cidSeq++}`;
32
33 // ---------- unit: the ledger ----------
34
35 test("appKeys normalize identity; parseAppArg reads every spelling", () => {
36 assert.deepEqual(consent.appKeys({ name: "Safari", bundle_id: "Com.Apple.Safari", pid: 42 }),
37 ["bundle:com.apple.safari", "name:safari", "pid:42"]);
38 assert.deepEqual(consent.appKeys({}), []);
39 assert.deepEqual(consent.appKeys(null), []);
40 assert.deepEqual(consent.parseAppArg({ app: "pid:77" }), ["pid:77"]);
41 assert.deepEqual(consent.parseAppArg({ app: "77" }), ["pid:77"]);
42 assert.deepEqual(consent.parseAppArg({ app: "com.apple.Safari" }), ["bundle:com.apple.safari"]);
43 assert.deepEqual(consent.parseAppArg({ app: "Safari.app" }), ["name:safari"]);
44 assert.deepEqual(consent.parseAppArg({ app: "My App" }), ["name:my app"]);
45 // Explicit fields win over the app string entirely.
46 assert.deepEqual(consent.parseAppArg({ app: "Other", name: "Chosen" }), ["name:chosen"]);
47 });
48
49 test("record + decisionFor: allow/deny per computer, newest decision wins", () => {
50 freshDir();
51 const id = cid();
52 assert.equal(consent.decisionFor(id, ["name:calc"]).state, "undecided");
53 consent.record(id, ["name:calc"], "allow");
54 assert.equal(consent.decisionFor(id, ["name:calc"]).state, "allowed");
55 // A different computer sees nothing.
56 assert.equal(consent.decisionFor(cid(), ["name:calc"]).state, "undecided");
57 consent.record(id, ["name:calc"], "deny");
58 assert.equal(consent.decisionFor(id, ["name:calc"]).state, "denied");
59 });
60
61 test("session and persisted layers overlay: a later session decision wins over 'always'", () => {
62 freshDir();
63 const id = cid();
64 consent.record(id, ["name:mail"], "deny", { remember: true });
65 assert.equal(consent.decisionFor(id, ["name:mail"]).state, "denied");
66 // A session allow recorded later outranks the persisted deny.
67 consent.record(id, ["name:mail"], "allow");
68 const d = consent.decisionFor(id, ["name:mail"]);
69 assert.equal(d.state, "allowed");
70 assert.equal(d.persisted, false);
71 });
72
73 test("pid keys are session-only — a pid never persists to consent.json", () => {
74 const dir = freshDir();
75 const id = cid();
76 consent.record(id, ["name:thing", "pid:4242"], "allow", { remember: true });
77 const file = JSON.parse(fs.readFileSync(path.join(dir, "consent.json"), "utf8"));
78 assert.ok(file.computers[id].apps["name:thing"]);
79 assert.equal(file.computers[id].apps["pid:4242"], undefined, "pid must not persist");
80 assert.ok(consent.decisionFor(id, ["pid:4242"]).state === "allowed", "session still sees the pid key");
81 });
82
83 test("alias folds a resolved identity's other spellings into the same decision", () => {
84 freshDir();
85 const id = cid();
86 consent.record(id, ["name:safari"], "allow");
87 // open_application resolved com.apple.Safari — the same allow now covers it.
88 consent.alias(id, ["bundle:com.apple.safari", "pid:501"], { persisted: false, name: "Safari" });
89 assert.equal(consent.decisionFor(id, ["bundle:com.apple.safari"]).state, "allowed");
90 assert.equal(consent.decisionFor(id, ["pid:501"]).state, "allowed");
91 });
92
93 test("revoke removes decisions at both layers; dropSession keeps persisted", () => {
94 const dir = freshDir();
95 const id = cid();
96 consent.record(id, ["name:a"], "allow", { remember: true });
97 consent.record(id, ["name:b"], "allow");
98 consent.revoke(id, ["name:a", "name:b"]);
99 assert.equal(consent.decisionFor(id, ["name:a"]).state, "undecided");
100 assert.equal(consent.decisionFor(id, ["name:b"]).state, "undecided");
101 consent.record(id, ["name:c"], "allow", { remember: true });
102 consent.record(id, ["name:d"], "allow");
103 consent.dropSession(id);
104 assert.equal(consent.decisionFor(id, ["name:c"]).state, "allowed", "persisted survives a route teardown");
105 assert.equal(consent.decisionFor(id, ["name:d"]).state, "undecided", "session decision dies with the route");
106 assert.ok(fs.existsSync(path.join(dir, "consent.json")));
107 });
108
109 test("foreground is its own scope: record, deny, revoke, status", () => {
110 freshDir();
111 const id = cid();
112 assert.equal(consent.foregroundDecision(id).state, "undecided");
113 consent.recordForeground(id, "allow");
114 assert.equal(consent.foregroundDecision(id).state, "allowed");
115 consent.recordForeground(id, "deny", { remember: true });
116 assert.equal(consent.foregroundDecision(id).state, "denied");
117 consent.revokeForeground(id);
118 assert.equal(consent.foregroundDecision(id).state, "undecided");
119 const st = consent.status(id);
120 assert.equal(st.foreground, null);
121 assert.deepEqual(Object.keys(st.apps), []);
122 });
123
124 test("status merges persisted and session entries and labels their source", () => {
125 freshDir();
126 const id = cid();
127 consent.record(id, ["name:persisted-app"], "allow", { remember: true, name: "Persisted App" });
128 consent.record(id, ["name:session-app"], "deny", { name: "Session App" });
129 consent.recordForeground(id, "allow");
130 const st = consent.status(id);
131 assert.equal(st.apps["name:persisted-app"].source, "persisted");
132 assert.equal(st.apps["name:session-app"].source, "session");
133 assert.equal(st.apps["name:session-app"].decision, "deny");
134 assert.equal(st.foreground.state, "allowed");
135 });
136
137 // ---------- wire: the gate, over the real server ----------
138
139 async function boot(t, env = {}, { hostKeys = true, attested = true, elicitation = null } = {}) {
140 const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "cu-consent-srv-"));
141 const recDir = fs.mkdtempSync(path.join(os.tmpdir(), "cu-consent-rec-"));
142 const child = spawn("node", [path.join(ROOT, "mcp", "server.mjs")], {
143 env: { ...process.env, CODEWHALE_CU_STATE_DIR: stateDir, CODEWHALE_CU_RECORDINGS_DIR: recDir, CODEWHALE_CU_APP: "off", CODEWHALE_CU_TEST_BACKEND: path.join(ROOT, "tests", "fixtures", "fake-backend.mjs"), ...env },
144 stdio: ["pipe", "pipe", "pipe"],
145 });
146 if (hostKeys) child.stdin.write(hostKeysLine());
147 t.after(() => { try { child.stdin.end(); } catch {} child.kill("SIGTERM"); fs.rmSync(stateDir, { recursive: true, force: true }); fs.rmSync(recDir, { recursive: true, force: true }); });
148 let buf = "";
149 const pending = new Map();
150 let nextId = 1;
151 child.stdout.on("data", (c) => {
152 buf += c.toString();
153 let i;
154 while ((i = buf.indexOf("\n")) !== -1) {
155 const line = buf.slice(0, i).trim();
156 buf = buf.slice(i + 1);
157 if (!line) continue;
158 const msg = JSON.parse(line);
159 if (msg.method === "elicitation/create" && elicitation) {
160 if (typeof elicitation === "function") elicitation(msg);
161 else child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: msg.id, result: { action: elicitation } }) + "\n");
162 continue;
163 }
164 if (msg.id != null && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
165 }
166 });
167 const rpc = (method, params, timeoutMs = 20_000) => {
168 const id = nextId++;
169 return new Promise((resolve, reject) => {
170 const timer = setTimeout(() => { pending.delete(id); reject(new Error(`timeout: ${method}`)); }, timeoutMs);
171 pending.set(id, (msg) => { clearTimeout(timer); resolve(msg); });
172 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params: attested ? attestParams(method, params) : params }) + "\n");
173 });
174 };
175 const tool = async (name, args = {}, timeoutMs) => JSON.parse((await rpc("tools/call", { name, arguments: args }, timeoutMs)).result.content[0].text);
176 const send = (params) => rpc("tools/call", params).then((r) => JSON.parse(r.result.content[0].text));
177 const sendWire = message => child.stdin.write(JSON.stringify(message) + "\n");
178 return { rpc, tool, send, sendWire, stateDir };
179 }
180
181 test("first app contact refuses consent_required before any backend work", async (t) => {
182 const s = await boot(t);
183 const r = await s.tool("open_application", { name: "FakeApp" });
184 assert.equal(r.ok, false);
185 assert.equal(r.error.code, "consent_required");
186 assert.match(r.error.message, /consent \{action:"allow"\|"deny"/);
187 const st = await s.tool("consent", { action: "status" });
188 assert.equal(st.ok, true);
189 assert.deepEqual(st.apps, {});
190 });
191
192 test("a deny cannot be sidestepped by re-spelling the same app", async (t) => {
193 const s = await boot(t);
194 // The recording backend resolves the alias without opening a real app.
195 await s.tool("consent", { action: "allow", app: "FakeApp" });
196 const opened = await s.tool("open_application", { name: "FakeApp" });
197 assert.equal(opened.ok, true);
198 const denied = await s.tool("consent", { action: "deny", app: "FakeApp" });
199 assert.equal(denied.ok, true);
200 assert.equal(denied.decision, "deny");
201 for (const args of [{ name: "FakeApp" }, { bundle_id: "com.fake.app" }, { name: "FakeApp.app" }]) {
202 const r = await s.tool("open_application", args);
203 assert.equal(r.error?.code, "app_denied", JSON.stringify(args));
204 }
205 // A destructive tool honors the same deny — it cannot terminate the app.
206 const kill = await s.tool("kill_app", { name: "FakeApp" });
207 assert.equal(kill.error?.code, "app_denied");
208 });
209
210 test("allow opens; activate:true is a separate foreground consent", async (t) => {
211 const s = await boot(t);
212 await s.tool("consent", { action: "allow", app: "FakeApp" });
213 const fg = await s.tool("open_application", { name: "FakeApp", activate: true });
214 assert.equal(fg.error?.code, "foreground_consent_required");
215 const deniedFg = await s.tool("consent", { action: "deny", scope: "foreground" });
216 assert.equal(deniedFg.scope, "foreground");
217 const again = await s.tool("open_application", { name: "FakeApp", activate: true });
218 assert.equal(again.error?.code, "foreground_denied");
219 await s.tool("consent", { action: "allow", scope: "foreground" });
220 const opened = await s.tool("open_application", { name: "FakeApp", activate: true });
221 assert.equal(opened.ok, true);
222 assert.equal(opened.shared_pointer, true);
223 // Background re-open needs no foreground consent — the bound app carries it.
224 const bg = await s.tool("open_application", { name: "FakeApp", activate: false });
225 assert.equal(bg.ok, true);
226 });
227
228 test("foreground consent gates activate:true on every local platform, not just macOS", async (t) => {
229 const s = await boot(t, { CODEWHALE_CU_TEST_BACKEND: path.join(ROOT, "tests", "fixtures", "fake-backend.mjs") });
230 await s.tool("consent", { action: "allow", app: "FakeApp" });
231 const fg = await s.tool("open_application", { name: "FakeApp", activate: true });
232 assert.equal(fg.error?.code, "foreground_consent_required", "the shared-surface escalation asks on every platform");
233 await s.tool("consent", { action: "allow", scope: "foreground" });
234 const opened = await s.tool("open_application", { name: "FakeApp", activate: true });
235 assert.equal(opened.ok, true, JSON.stringify(opened));
236 assert.equal(opened.shared_pointer, true);
237 });
238
239 test("remember:true persists; consent status shows the ledger", async (t) => {
240 const s = await boot(t);
241 const r = await s.tool("consent", { action: "allow", app: "Finder", remember: true });
242 assert.equal(r.persisted, true);
243 const file = JSON.parse(fs.readFileSync(path.join(s.stateDir, "consent.json"), "utf8"));
244 assert.equal(file.computers.local.apps["name:finder"].decision, "allow");
245 const st = await s.tool("consent", { action: "status" });
246 assert.equal(st.apps["name:finder"].source, "persisted");
247 const revoked = await s.tool("consent", { action: "revoke", app: "Finder" });
248 assert.equal(revoked.ok, true);
249 assert.equal(consent.decisionFor("local", ["name:finder"]).state, "undecided");
250 });
251
252 test("remote computers are covered by the transport, not the app ledger", async (t) => {
253 const s = await boot(t);
254 const reg = await s.tool("computer", { action: "register", id: "faraway", transport: "ssh", host: "192.0.2.1", installAgent: false });
255 assert.equal(reg.ok, true);
256 const st = await s.tool("consent", { action: "status", computer: "faraway" });
257 assert.equal(st.ok, true);
258 // open_application may fail at transport level — never at consent.
259 const r = await s.tool("open_application", { name: "x", computer: "faraway" }, 40_000);
260 assert.notEqual(r.error?.code, "consent_required");
261 assert.notEqual(r.error?.code, "app_denied");
262 });
263
264 test("spawned computers are task-owned — the app ledger never gates them", { skip: NEED_DOCKER.skip }, async (t) => {
265 const s = await boot(t);
266 const id = `consent-${Date.now()}`;
267 const spawned = await s.tool("computer", { action: "spawn", id, transport: "docker" }, 60_000);
268 assert.equal(spawned.ok, true, JSON.stringify(spawned));
269 const r = await s.tool("open_application", { name: "xterm" });
270 assert.notEqual(r.error?.code, "consent_required", "an owned computer must never consult the user's app ledger");
271 const st = await s.tool("consent", { action: "status", computer: id });
272 assert.equal(st.ok, true);
273 });
274
275 // ---------- the user's own decision ----------
276
277 test("consent allow without a host decision is refused", async (t) => {
278 const s = await boot(t, {}, { attested: false });
279 const r = await s.tool("consent", { action: "allow", app: "FakeApp" });
280 assert.equal(r.ok, false);
281 assert.equal(r.error.code, "consent_needs_user");
282 for (const [name, args] of [["consent_allow", { app: "FakeApp" }], ["consent", { action: "revoke", app: "FakeApp" }], ["app_script", { script: "return 1" }], ["computer_register", { computer: "box", transport: "local" }]]) {
283 const refused = await s.tool(name, args);
284 assert.equal(refused.error?.code, "consent_needs_user", name);
285 }
286 // Narrowing needs no decision.
287 assert.equal((await s.tool("consent", { action: "deny", app: "OtherApp" })).ok, true);
288 const opened = await s.tool("open_application", { name: "FakeApp" });
289 assert.equal(opened.error?.code, "consent_required");
290 });
291
292 test("consent allow with a valid decision MAC succeeds; replayed nonce is refused", async (t) => {
293 const s = await boot(t, {}, { attested: false });
294 const params = attest({ name: "consent", arguments: { action: "allow", app: "FakeApp" } });
295 assert.equal((await s.send(params)).ok, true);
296 const replayed = await s.send(params);
297 assert.equal(replayed.error?.code, "consent_needs_user");
298 // A MAC for other arguments does not cover these.
299 const forged = attest({ name: "consent", arguments: { action: "allow", app: "OtherApp" } });
300 forged.arguments = { action: "allow", app: "Terminal" };
301 assert.equal((await s.send(forged)).error?.code, "consent_needs_user");
302 // A MAC under another key does not verify.
303 const wrongKey = attest({ name: "consent", arguments: { action: "allow", app: "Terminal" } }, "33".repeat(32));
304 assert.equal((await s.send(wrongKey)).error?.code, "consent_needs_user");
305 });
306
307 test("a decision is refused when the host sent no key, and keys are read only from the first message", async (t) => {
308 const s = await boot(t, {}, { hostKeys: false });
309 // Keys arriving after the first message are ignored.
310 await s.rpc("ping", {});
311 const late = await s.rpc("codewhale/host_keys", { decision_key: "11".repeat(32) }, 300).catch(() => null);
312 void late;
313 const r = await s.tool("consent", { action: "allow", app: "FakeApp" });
314 assert.equal(r.error?.code, "consent_needs_user");
315 });
316
317 test("a client with elicitation decides for other hosts", async (t) => {
318 for (const [answer, ok] of [["accept", true], ["decline", false]]) {
319 const s = await boot(t, {}, { hostKeys: false, attested: false, elicitation: answer });
320 await s.rpc("initialize", { protocolVersion: "2025-06-18", capabilities: { elicitation: {} } });
321 const r = await s.tool("consent", { action: "allow", app: "FakeApp" });
322 assert.equal(r.ok, ok, `${answer}: ${JSON.stringify(r)}`);
323 if (!ok) assert.equal(r.error.code, "consent_declined");
324 }
325 });
326
327 test("planted consent.json allow entry without MAC is ignored; deny is honored", () => {
328 const dir = freshDir();
329 const id = cid();
330 const at = new Date().toISOString();
331 const good = { decision: "allow", at };
332 fs.writeFileSync(path.join(dir, "consent.json"), JSON.stringify({ version: 1, computers: { [id]: {
333 apps: {
334 "name:planted": { decision: "allow", at },
335 "name:forged": { decision: "allow", at, mac: "00".repeat(32) },
336 "name:signed": { ...good, mac: ledgerMac(id, "name:signed", good) },
337 "name:blocked": { decision: "deny", at },
338 },
339 foreground: { decision: "allow", at },
340 } } }));
341 assert.equal(consent.decisionFor(id, ["name:planted"]).state, "undecided");
342 assert.equal(consent.decisionFor(id, ["name:forged"]).state, "undecided");
343 assert.equal(consent.decisionFor(id, ["name:signed"]).state, "allowed");
344 assert.equal(consent.decisionFor(id, ["name:blocked"]).state, "denied");
345 assert.equal(consent.foregroundDecision(id).state, "undecided");
346 });
347
348 test("confirm token requires a host decision", async (t) => {
349 const s = await boot(t, {}, { attested: false });
350 const r = await s.tool("consent", { action: "allow", confirm: "confirm-000000000000000000" });
351 assert.equal(r.error?.code, "consent_needs_user");
352 });
353
354 test("run_actions app_script step needs a host decision", async (t) => {
355 const s = await boot(t);
356 const r = await s.tool("run_actions", { steps: [{ tool: "app_script", arguments: { script: "return 1" } }] });
357 assert.equal(r.ok, false);
358 assert.equal(r.error.code, "consent_needs_user");
359 });
360
361
362 test("cancelled user elicitation releases dispatch and cannot grant consent later", async (t) => {
363 let sawPrompt;
364 const prompt = new Promise(resolve => { sawPrompt = resolve; });
365 const s = await boot(t, {}, { hostKeys: false, attested: false, elicitation: sawPrompt });
366 await s.rpc("initialize", { protocolVersion: "2025-06-18", capabilities: { elicitation: {} } });
367 s.sendWire({ jsonrpc: "2.0", id: "cancelled-consent", method: "tools/call", params: { name: "consent", arguments: { action: "allow", app: "FakeApp" } } });
368 const request = await Promise.race([prompt, new Promise((_, reject) => setTimeout(() => reject(new Error("elicitation was not shown")), 2_000))]);
369 s.sendWire({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: "cancelled-consent" } });
370 // The unanswered card no longer holds the serialized tool queue.
371 const before = await s.tool("consent", { action: "status" }, 1_000);
372 assert.deepEqual(before.apps, {});
373 s.sendWire({ jsonrpc: "2.0", id: request.id, result: { action: "accept" } });
374 const after = await s.tool("consent", { action: "status" }, 1_000);
375 assert.deepEqual(after.apps, {}, "a late accept cannot grant the cancelled request");
376 });
377
377 lines Plain Text