| 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 { test } from "node:test"; |
| 6 | import assert from "node:assert/strict"; |
| 7 | import fs from "node:fs"; |
| 8 | import os from "node:os"; |
| 9 | import path from "node:path"; |
| 10 | import url from "node:url"; |
| 11 | import { spawn } from "node:child_process"; |
| 12 | import * as consent from "../src/consent.mjs"; |
| 13 | import { dockerAvailable } from "../src/spawn.mjs"; |
| 14 | |
| 15 | const ROOT = path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), ".."); |
| 16 | const DOCKER = await dockerAvailable(); |
| 17 | const NEED_DOCKER = { skip: !DOCKER && "docker daemon not available" }; |
| 18 | |
| 19 | let tmpSeq = 0; |
| 20 | function freshDir() { |
| 21 | const dir = fs.mkdtempSync(path.join(os.tmpdir(), `cu-consent-${tmpSeq++}-`)); |
| 22 | process.env.CODEWHALE_CU_STATE_DIR = dir; |
| 23 | return dir; |
| 24 | } |
| 25 | // Every test gets a clean store and a clean session map key space. |
| 26 | let cidSeq = 0; |
| 27 | const cid = () => `c${cidSeq++}`; |
| 28 | |
| 29 | // ---------- unit: the ledger ---------- |
| 30 | |
| 31 | test("appKeys normalize identity; parseAppArg reads every spelling", () => { |
| 32 | assert.deepEqual(consent.appKeys({ name: "Safari", bundle_id: "Com.Apple.Safari", pid: 42 }), |
| 33 | ["bundle:com.apple.safari", "name:safari", "pid:42"]); |
| 34 | assert.deepEqual(consent.appKeys({}), []); |
| 35 | assert.deepEqual(consent.appKeys(null), []); |
| 36 | assert.deepEqual(consent.parseAppArg({ app: "pid:77" }), ["pid:77"]); |
| 37 | assert.deepEqual(consent.parseAppArg({ app: "77" }), ["pid:77"]); |
| 38 | assert.deepEqual(consent.parseAppArg({ app: "com.apple.Safari" }), ["bundle:com.apple.safari"]); |
| 39 | assert.deepEqual(consent.parseAppArg({ app: "Safari.app" }), ["name:safari"]); |
| 40 | assert.deepEqual(consent.parseAppArg({ app: "My App" }), ["name:my app"]); |
| 41 | // Explicit fields win over the app string entirely. |
| 42 | assert.deepEqual(consent.parseAppArg({ app: "Other", name: "Chosen" }), ["name:chosen"]); |
| 43 | }); |
| 44 | |
| 45 | test("record + decisionFor: allow/deny per computer, newest decision wins", () => { |
| 46 | freshDir(); |
| 47 | const id = cid(); |
| 48 | assert.equal(consent.decisionFor(id, ["name:calc"]).state, "undecided"); |
| 49 | consent.record(id, ["name:calc"], "allow"); |
| 50 | assert.equal(consent.decisionFor(id, ["name:calc"]).state, "allowed"); |
| 51 | // A different computer sees nothing. |
| 52 | assert.equal(consent.decisionFor(cid(), ["name:calc"]).state, "undecided"); |
| 53 | consent.record(id, ["name:calc"], "deny"); |
| 54 | assert.equal(consent.decisionFor(id, ["name:calc"]).state, "denied"); |
| 55 | }); |
| 56 | |
| 57 | test("session and persisted layers overlay: a later session decision wins over 'always'", () => { |
| 58 | freshDir(); |
| 59 | const id = cid(); |
| 60 | consent.record(id, ["name:mail"], "deny", { remember: true }); |
| 61 | assert.equal(consent.decisionFor(id, ["name:mail"]).state, "denied"); |
| 62 | // A session allow recorded later outranks the persisted deny. |
| 63 | consent.record(id, ["name:mail"], "allow"); |
| 64 | const d = consent.decisionFor(id, ["name:mail"]); |
| 65 | assert.equal(d.state, "allowed"); |
| 66 | assert.equal(d.persisted, false); |
| 67 | }); |
| 68 | |
| 69 | test("pid keys are session-only — a pid never persists to consent.json", () => { |
| 70 | const dir = freshDir(); |
| 71 | const id = cid(); |
| 72 | consent.record(id, ["name:thing", "pid:4242"], "allow", { remember: true }); |
| 73 | const file = JSON.parse(fs.readFileSync(path.join(dir, "consent.json"), "utf8")); |
| 74 | assert.ok(file.computers[id].apps["name:thing"]); |
| 75 | assert.equal(file.computers[id].apps["pid:4242"], undefined, "pid must not persist"); |
| 76 | assert.ok(consent.decisionFor(id, ["pid:4242"]).state === "allowed", "session still sees the pid key"); |
| 77 | }); |
| 78 | |
| 79 | test("alias folds a resolved identity's other spellings into the same decision", () => { |
| 80 | freshDir(); |
| 81 | const id = cid(); |
| 82 | consent.record(id, ["name:safari"], "allow"); |
| 83 | // open_application resolved com.apple.Safari — the same allow now covers it. |
| 84 | consent.alias(id, ["bundle:com.apple.safari", "pid:501"], { persisted: false, name: "Safari" }); |
| 85 | assert.equal(consent.decisionFor(id, ["bundle:com.apple.safari"]).state, "allowed"); |
| 86 | assert.equal(consent.decisionFor(id, ["pid:501"]).state, "allowed"); |
| 87 | }); |
| 88 | |
| 89 | test("revoke removes decisions at both layers; dropSession keeps persisted", () => { |
| 90 | const dir = freshDir(); |
| 91 | const id = cid(); |
| 92 | consent.record(id, ["name:a"], "allow", { remember: true }); |
| 93 | consent.record(id, ["name:b"], "allow"); |
| 94 | consent.revoke(id, ["name:a", "name:b"]); |
| 95 | assert.equal(consent.decisionFor(id, ["name:a"]).state, "undecided"); |
| 96 | assert.equal(consent.decisionFor(id, ["name:b"]).state, "undecided"); |
| 97 | consent.record(id, ["name:c"], "allow", { remember: true }); |
| 98 | consent.record(id, ["name:d"], "allow"); |
| 99 | consent.dropSession(id); |
| 100 | assert.equal(consent.decisionFor(id, ["name:c"]).state, "allowed", "persisted survives a route teardown"); |
| 101 | assert.equal(consent.decisionFor(id, ["name:d"]).state, "undecided", "session decision dies with the route"); |
| 102 | assert.ok(fs.existsSync(path.join(dir, "consent.json"))); |
| 103 | }); |
| 104 | |
| 105 | test("foreground is its own scope: record, deny, revoke, status", () => { |
| 106 | freshDir(); |
| 107 | const id = cid(); |
| 108 | assert.equal(consent.foregroundDecision(id).state, "undecided"); |
| 109 | consent.recordForeground(id, "allow"); |
| 110 | assert.equal(consent.foregroundDecision(id).state, "allowed"); |
| 111 | consent.recordForeground(id, "deny", { remember: true }); |
| 112 | assert.equal(consent.foregroundDecision(id).state, "denied"); |
| 113 | consent.revokeForeground(id); |
| 114 | assert.equal(consent.foregroundDecision(id).state, "undecided"); |
| 115 | const st = consent.status(id); |
| 116 | assert.equal(st.foreground, null); |
| 117 | assert.deepEqual(Object.keys(st.apps), []); |
| 118 | }); |
| 119 | |
| 120 | test("status merges persisted and session entries and labels their source", () => { |
| 121 | freshDir(); |
| 122 | const id = cid(); |
| 123 | consent.record(id, ["name:persisted-app"], "allow", { remember: true, name: "Persisted App" }); |
| 124 | consent.record(id, ["name:session-app"], "deny", { name: "Session App" }); |
| 125 | consent.recordForeground(id, "allow"); |
| 126 | const st = consent.status(id); |
| 127 | assert.equal(st.apps["name:persisted-app"].source, "persisted"); |
| 128 | assert.equal(st.apps["name:session-app"].source, "session"); |
| 129 | assert.equal(st.apps["name:session-app"].decision, "deny"); |
| 130 | assert.equal(st.foreground.state, "allowed"); |
| 131 | }); |
| 132 | |
| 133 | // ---------- wire: the gate, over the real server ---------- |
| 134 | |
| 135 | async function boot(t, env = {}) { |
| 136 | const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "cu-consent-srv-")); |
| 137 | const recDir = fs.mkdtempSync(path.join(os.tmpdir(), "cu-consent-rec-")); |
| 138 | const child = spawn("node", [path.join(ROOT, "mcp", "server.mjs")], { |
| 139 | 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 }, |
| 140 | stdio: ["pipe", "pipe", "pipe"], |
| 141 | }); |
| 142 | t.after(() => { try { child.stdin.end(); } catch {} child.kill("SIGTERM"); fs.rmSync(stateDir, { recursive: true, force: true }); fs.rmSync(recDir, { recursive: true, force: true }); }); |
| 143 | let buf = ""; |
| 144 | const pending = new Map(); |
| 145 | let nextId = 1; |
| 146 | child.stdout.on("data", (c) => { |
| 147 | buf += c.toString(); |
| 148 | let i; |
| 149 | while ((i = buf.indexOf("\n")) !== -1) { |
| 150 | const line = buf.slice(0, i).trim(); |
| 151 | buf = buf.slice(i + 1); |
| 152 | if (!line) continue; |
| 153 | const msg = JSON.parse(line); |
| 154 | if (msg.id != null && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } |
| 155 | } |
| 156 | }); |
| 157 | const rpc = (method, params, timeoutMs = 20_000) => { |
| 158 | const id = nextId++; |
| 159 | return new Promise((resolve, reject) => { |
| 160 | const timer = setTimeout(() => { pending.delete(id); reject(new Error(`timeout: ${method}`)); }, timeoutMs); |
| 161 | pending.set(id, (msg) => { clearTimeout(timer); resolve(msg); }); |
| 162 | child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n"); |
| 163 | }); |
| 164 | }; |
| 165 | const tool = async (name, args = {}, timeoutMs) => JSON.parse((await rpc("tools/call", { name, arguments: args }, timeoutMs)).result.content[0].text); |
| 166 | return { rpc, tool, stateDir }; |
| 167 | } |
| 168 | |
| 169 | test("first app contact refuses consent_required before any backend work", async (t) => { |
| 170 | const s = await boot(t); |
| 171 | const r = await s.tool("open_application", { name: "FakeApp" }); |
| 172 | assert.equal(r.ok, false); |
| 173 | assert.equal(r.error.code, "consent_required"); |
| 174 | assert.match(r.error.message, /consent \{action:"allow"\|"deny"/); |
| 175 | const st = await s.tool("consent", { action: "status" }); |
| 176 | assert.equal(st.ok, true); |
| 177 | assert.deepEqual(st.apps, {}); |
| 178 | }); |
| 179 | |
| 180 | test("a deny cannot be sidestepped by re-spelling the same app", async (t) => { |
| 181 | const s = await boot(t); |
| 182 | // The recording backend resolves the alias without opening a real app. |
| 183 | await s.tool("consent", { action: "allow", app: "FakeApp" }); |
| 184 | const opened = await s.tool("open_application", { name: "FakeApp" }); |
| 185 | assert.equal(opened.ok, true); |
| 186 | const denied = await s.tool("consent", { action: "deny", app: "FakeApp" }); |
| 187 | assert.equal(denied.ok, true); |
| 188 | assert.equal(denied.decision, "deny"); |
| 189 | for (const args of [{ name: "FakeApp" }, { bundle_id: "com.fake.app" }, { name: "FakeApp.app" }]) { |
| 190 | const r = await s.tool("open_application", args); |
| 191 | assert.equal(r.error?.code, "app_denied", JSON.stringify(args)); |
| 192 | } |
| 193 | // A destructive tool honors the same deny — it cannot terminate the app. |
| 194 | const kill = await s.tool("kill_app", { name: "FakeApp" }); |
| 195 | assert.equal(kill.error?.code, "app_denied"); |
| 196 | }); |
| 197 | |
| 198 | test("allow opens; activate:true is a separate foreground consent", async (t) => { |
| 199 | const s = await boot(t); |
| 200 | await s.tool("consent", { action: "allow", app: "FakeApp" }); |
| 201 | const fg = await s.tool("open_application", { name: "FakeApp", activate: true }); |
| 202 | assert.equal(fg.error?.code, "foreground_consent_required"); |
| 203 | const deniedFg = await s.tool("consent", { action: "deny", scope: "foreground" }); |
| 204 | assert.equal(deniedFg.scope, "foreground"); |
| 205 | const again = await s.tool("open_application", { name: "FakeApp", activate: true }); |
| 206 | assert.equal(again.error?.code, "foreground_denied"); |
| 207 | await s.tool("consent", { action: "allow", scope: "foreground" }); |
| 208 | const opened = await s.tool("open_application", { name: "FakeApp", activate: true }); |
| 209 | assert.equal(opened.ok, true); |
| 210 | assert.equal(opened.shared_pointer, true); |
| 211 | // Background re-open needs no foreground consent — the bound app carries it. |
| 212 | const bg = await s.tool("open_application", { name: "FakeApp", activate: false }); |
| 213 | assert.equal(bg.ok, true); |
| 214 | }); |
| 215 | |
| 216 | test("foreground consent gates activate:true on every local platform, not just macOS", async (t) => { |
| 217 | const s = await boot(t, { CODEWHALE_CU_TEST_BACKEND: path.join(ROOT, "tests", "fixtures", "fake-backend.mjs") }); |
| 218 | await s.tool("consent", { action: "allow", app: "FakeApp" }); |
| 219 | const fg = await s.tool("open_application", { name: "FakeApp", activate: true }); |
| 220 | assert.equal(fg.error?.code, "foreground_consent_required", "the shared-surface escalation asks on every platform"); |
| 221 | await s.tool("consent", { action: "allow", scope: "foreground" }); |
| 222 | const opened = await s.tool("open_application", { name: "FakeApp", activate: true }); |
| 223 | assert.equal(opened.ok, true, JSON.stringify(opened)); |
| 224 | assert.equal(opened.shared_pointer, true); |
| 225 | }); |
| 226 | |
| 227 | test("remember:true persists; consent status shows the ledger", async (t) => { |
| 228 | const s = await boot(t); |
| 229 | const r = await s.tool("consent", { action: "allow", app: "Finder", remember: true }); |
| 230 | assert.equal(r.persisted, true); |
| 231 | const file = JSON.parse(fs.readFileSync(path.join(s.stateDir, "consent.json"), "utf8")); |
| 232 | assert.equal(file.computers.local.apps["name:finder"].decision, "allow"); |
| 233 | const st = await s.tool("consent", { action: "status" }); |
| 234 | assert.equal(st.apps["name:finder"].source, "persisted"); |
| 235 | const revoked = await s.tool("consent", { action: "revoke", app: "Finder" }); |
| 236 | assert.equal(revoked.ok, true); |
| 237 | assert.equal(consent.decisionFor("local", ["name:finder"]).state, "undecided"); |
| 238 | }); |
| 239 | |
| 240 | test("remote computers are covered by the transport, not the app ledger", async (t) => { |
| 241 | const s = await boot(t); |
| 242 | const reg = await s.tool("computer", { action: "register", id: "faraway", transport: "ssh", host: "192.0.2.1", installAgent: false }); |
| 243 | assert.equal(reg.ok, true); |
| 244 | const st = await s.tool("consent", { action: "status", computer: "faraway" }); |
| 245 | assert.equal(st.ok, true); |
| 246 | // open_application may fail at transport level — never at consent. |
| 247 | const r = await s.tool("open_application", { name: "x", computer: "faraway" }, 40_000); |
| 248 | assert.notEqual(r.error?.code, "consent_required"); |
| 249 | assert.notEqual(r.error?.code, "app_denied"); |
| 250 | }); |
| 251 | |
| 252 | test("spawned computers are task-owned — the app ledger never gates them", { skip: NEED_DOCKER.skip }, async (t) => { |
| 253 | const s = await boot(t); |
| 254 | const id = `consent-${Date.now()}`; |
| 255 | const spawned = await s.tool("computer", { action: "spawn", id, transport: "docker" }, 60_000); |
| 256 | assert.equal(spawned.ok, true, JSON.stringify(spawned)); |
| 257 | const r = await s.tool("open_application", { name: "xterm" }); |
| 258 | assert.notEqual(r.error?.code, "consent_required", "an owned computer must never consult the user's app ledger"); |
| 259 | const st = await s.tool("consent", { action: "status", computer: id }); |
| 260 | assert.equal(st.ok, true); |
| 261 | }); |
| 262 |