bash-adb-admission.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. import {
  2. chmod,
  3. copyFile,
  4. mkdir,
  5. mkdtemp,
  6. readFile,
  7. realpath,
  8. rm,
  9. symlink,
  10. writeFile,
  11. } from "node:fs/promises";
  12. import { createRequire } from "node:module";
  13. import { tmpdir } from "node:os";
  14. import { delimiter, join } from "node:path";
  15. import { describe, expect, it, vi } from "vitest";
  16. import { CoreErrorType, createSessionId, createToolCallId, createTraceId } from "@zcode/contracts";
  17. import type {
  18. BashOutput,
  19. ExecutionPort,
  20. ExecutionRequest,
  21. ExecutionShellSelection,
  22. } from "@zcode/contracts";
  23. import { NodeExecutionAdapter } from "../../adapters/src/exec/node-execution-adapter.js";
  24. import { resolveWindowsGitBashShell } from "../../adapters/src/exec/bash-shell-provider.js";
  25. import { PermissionService } from "../src/permission/service.js";
  26. import { createToolExecutor } from "../src/tool/executor.js";
  27. import { bashHandler, bashToolEntry } from "../src/tool/handlers/bash.js";
  28. import { createToolRegistry } from "../src/tool/registry.js";
  29. import type { ToolExecutionContext } from "../src/tool/types.js";
  30. type Dialect = ExecutionShellSelection["dialect"];
  31. const invocations: Array<[Dialect, string]> = [
  32. ["posix", "adb devices"],
  33. ["posix", "./adb.exe devices"],
  34. ["posix", "'/workspace/my tools/adb' devices"],
  35. ["posix", "echo before && ./adb devices"],
  36. ["posix", "./adb devices | cat"],
  37. ["posix", "echo before; adb devices"],
  38. ["posix", "ADB_TRACE=all adb devices"],
  39. ["posix", "env -u HOME adb devices"],
  40. ["posix", "sudo -u developer /opt/sdk/adb devices"],
  41. ["posix", "time -p adb devices"],
  42. ["posix", "command -- adb devices"],
  43. ["posix", "exec ./adb.exe devices"],
  44. ["git-bash", '"C:/project/ADB.EXE" devices'],
  45. ["cmd", ".\\adb.exe devices"],
  46. ["cmd", '"C:\\project with spaces\\AdB.ExE" devices'],
  47. ["cmd", "type # & .\\adb.exe devices"],
  48. ["cmd", "call .\\adb.cmd devices"],
  49. ["cmd", "a^db.exe devices"],
  50. ["cmd", "@adb.exe devices"],
  51. ["cmd", "@adb.exe devices & echo ok"],
  52. ["cmd", "@ adb.exe devices"],
  53. ["cmd", "@@ADB.EXE devices"],
  54. ["cmd", "@call @ adb.exe devices"],
  55. // legacy-shell 只是 POSIX 下的 /bin/sh 回落,Windows 不再产出,按 POSIX 语义校验工作区 adb。
  56. ["legacy-shell", "./adb devices"],
  57. ];
  58. function selection(dialect: Dialect): ExecutionShellSelection {
  59. return { dialect, source: "user-config", display: { name: dialect } };
  60. }
  61. function context(executionPort: ExecutionPort, cwd: string, shell: ExecutionShellSelection) {
  62. return {
  63. toolCallId: createToolCallId("adb-admission"),
  64. traceId: createTraceId(),
  65. abortSignal: new AbortController().signal,
  66. executionPort,
  67. workingDirectory: cwd,
  68. workspaceRoot: cwd,
  69. sessionId: createSessionId("adb-admission"),
  70. bashShellSelection: shell,
  71. emitEvent: async () => {},
  72. } satisfies ToolExecutionContext;
  73. }
  74. function port(result: { status: "resolved"; path: string } | { status: "workspace" | "missing" }) {
  75. const reached = new Error("execution reached");
  76. return {
  77. reached,
  78. resolveAdbExecutable: vi.fn(async () => result),
  79. run: vi.fn<ExecutionPort["run"]>(async () => {
  80. throw reached;
  81. }),
  82. runBashWithBackgroundLifecycle: vi.fn(async (_request: ExecutionRequest) => {
  83. throw reached;
  84. }),
  85. };
  86. }
  87. describe("Bash adb workspace admission", () => {
  88. it.each(invocations)("rejects workspace resolution in %s: %s", async (dialect, command) => {
  89. const execution = port({ status: "workspace" });
  90. for (const run_in_background of [false, true]) {
  91. await expect(
  92. bashHandler(
  93. { command, run_in_background },
  94. context(execution, process.cwd(), selection(dialect)),
  95. ),
  96. ).rejects.toMatchObject({
  97. type: CoreErrorType.PermissionDenied,
  98. context: { reason: "workspace-adb-blocked" },
  99. });
  100. }
  101. expect(execution.resolveAdbExecutable).toHaveBeenCalled();
  102. expect(execution.run).not.toHaveBeenCalled();
  103. expect(execution.runBashWithBackgroundLifecycle).not.toHaveBeenCalled();
  104. });
  105. it.each([
  106. ["posix", "adb devices", "'/opt/Android SDK/adb' devices"],
  107. ["posix", "echo ok && '/opt/SDK/adb' devices", "echo ok && '/opt/Android SDK/adb' devices"],
  108. ["posix", "env ADB_TRACE=all adb devices", "env ADB_TRACE=all '/opt/Android SDK/adb' devices"],
  109. ["posix", "command adb -v", "command '/opt/Android SDK/adb' -v"],
  110. ["legacy-shell", "adb devices", "'/opt/Android SDK/adb' devices"],
  111. ["cmd", "@adb.exe devices & echo ok", '@"C:\\Android SDK\\adb.exe" devices & echo ok'],
  112. ["cmd", "@call @ adb.exe devices", '@call @ "C:\\Android SDK\\adb.exe" devices'],
  113. ["git-bash", '"C:/SDK/adb.exe" devices', "'C:/Android SDK/adb.exe' devices"],
  114. ] as const)("pins allowed %s adb without MCP: %s", async (dialect, command, expected) => {
  115. const path =
  116. dialect === "posix" || dialect === "legacy-shell"
  117. ? "/opt/Android SDK/adb"
  118. : "C:\\Android SDK\\adb.exe";
  119. const execution = port({ status: "resolved", path });
  120. for (const run_in_background of [false, true]) {
  121. await expect(
  122. bashHandler(
  123. { command, run_in_background },
  124. context(execution, process.cwd(), selection(dialect)),
  125. ),
  126. ).rejects.toBe(execution.reached);
  127. expect(execution.runBashWithBackgroundLifecycle.mock.lastCall?.[0]).toMatchObject({
  128. command: { command: expected },
  129. });
  130. }
  131. expect(execution.resolveAdbExecutable).toHaveBeenCalledWith(
  132. expect.objectContaining({ workspaceRoot: process.cwd(), cwd: process.cwd() }),
  133. );
  134. });
  135. // 回归:legacy-shell 曾额外用 CMD 解析器分析同一命令,把 POSIX 引号、heredoc 里的 adb 文本当命令名改写。
  136. it.each(
  137. (["legacy-shell", "posix"] as const).flatMap((dialect) =>
  138. [
  139. "printf '%s\\n' 'a & adb shell' > note.txt",
  140. "cat <<'EOF' > note.txt\nadb devices\nEOF",
  141. 'echo "x & adb devices"',
  142. 'git commit -m "fix & adb devices"',
  143. ].map((command) => [dialect, command] as const),
  144. ),
  145. )("keeps quoted or heredoc adb text in %s: %s", async (dialect, command) => {
  146. const execution = port({ status: "resolved", path: "/opt/sdk/adb" });
  147. await expect(
  148. bashHandler({ command }, context(execution, process.cwd(), selection(dialect))),
  149. ).rejects.toBe(execution.reached);
  150. expect(execution.runBashWithBackgroundLifecycle.mock.lastCall?.[0]).toMatchObject({
  151. command: { command },
  152. });
  153. expect(execution.resolveAdbExecutable).not.toHaveBeenCalled();
  154. });
  155. it.each(["build", "edit", "yolo", "guarded"] as const)(
  156. "approval in %s cannot allow workspace adb",
  157. async (mode) => {
  158. const registry = createToolRegistry();
  159. registry.register(bashToolEntry);
  160. const execution = port({ status: "workspace" });
  161. const executor = createToolExecutor({
  162. registry,
  163. permissionService: new PermissionService(),
  164. permissionBroker: { requestPermission: async () => ({ decision: "allow" }) },
  165. executionPort: execution,
  166. mode,
  167. workingDirectory: process.cwd(),
  168. bashShellSelection: selection("cmd"),
  169. sessionId: createSessionId(`adb-${mode}`),
  170. emitEvent: async () => {},
  171. });
  172. for (const run_in_background of [false, true]) {
  173. const result = await executor.execute({
  174. id: createToolCallId(`adb-${mode}-${run_in_background}`),
  175. name: "Bash",
  176. input: { command: "@adb.exe devices", run_in_background },
  177. });
  178. expect(result).toMatchObject({
  179. success: false,
  180. error: { type: CoreErrorType.PermissionDenied },
  181. });
  182. expect(result.error?.message).not.toContain("Use the Android MCP");
  183. }
  184. expect(execution.runBashWithBackgroundLifecycle).not.toHaveBeenCalled();
  185. },
  186. );
  187. it("does not start an earlier segment when a later adb is workspace-controlled", async () => {
  188. const execution = port({ status: "resolved", path: "/sdk/adb" });
  189. execution.resolveAdbExecutable
  190. .mockResolvedValueOnce({ status: "resolved", path: "/sdk/adb" })
  191. .mockResolvedValueOnce({ status: "workspace" });
  192. await expect(
  193. bashHandler(
  194. { command: "adb devices; ./adb devices" },
  195. context(execution, process.cwd(), selection("posix")),
  196. ),
  197. ).rejects.toMatchObject({ context: { reason: "workspace-adb-blocked" } });
  198. expect(execution.runBashWithBackgroundLifecycle).not.toHaveBeenCalled();
  199. });
  200. it("reports missing SDK/PATH without requiring MCP or executing a fallback", async () => {
  201. const execution = port({ status: "missing" });
  202. await expect(
  203. bashHandler(
  204. { command: "adb devices" },
  205. context(execution, process.cwd(), selection("posix")),
  206. ),
  207. ).rejects.toMatchObject({
  208. type: CoreErrorType.ConfigurationError,
  209. context: { reason: "adb-not-found" },
  210. });
  211. expect(execution.runBashWithBackgroundLifecycle).not.toHaveBeenCalled();
  212. });
  213. it.each([
  214. ["posix", "echo adb ./adb.exe"],
  215. ["posix", "command -v adb"],
  216. ["posix", "command -V adb"],
  217. ["posix", "# adb devices\nprintf ok"],
  218. ["posix", "./gradlew assembleDebug"],
  219. ["posix", "pnpm build"],
  220. ["posix", "python scripts/build.py"],
  221. ["cmd", "@node scripts/build.js"],
  222. ["cmd", "@pnpm build"],
  223. ["cmd", "@call gradlew.bat assembleDebug"],
  224. ["cmd", "@echo @adb.exe"],
  225. ["cmd", '"@adb.exe" devices'],
  226. ["cmd", '@"@adb.exe" devices'],
  227. ["cmd", "^@adb.exe devices"],
  228. ["cmd", ".\\@adb.exe devices"],
  229. ["posix", "@adb.exe devices"],
  230. ["git-bash", "@adb.exe devices"],
  231. ] as const)("preserves %s command unchanged: %s", async (dialect, command) => {
  232. const reached = new Error("execution reached");
  233. const run = vi.fn<ExecutionPort["run"]>(async () => {
  234. throw reached;
  235. });
  236. await expect(
  237. bashHandler({ command }, context({ run }, process.cwd(), selection(dialect))),
  238. ).rejects.toBe(reached);
  239. expect(run.mock.calls[0]?.[0].command).toMatchObject({ mode: "shell", command });
  240. });
  241. });
  242. const windows = process.platform === "win32";
  243. const gitBash = windows ? await resolveWindowsGitBashShell(process.env) : undefined;
  244. const shells: ExecutionShellSelection[] = windows
  245. ? [
  246. { ...selection("cmd"), path: process.env.ComSpec },
  247. ...(gitBash ? [{ ...selection("git-bash"), path: gitBash }] : []),
  248. ]
  249. : [{ ...selection("posix"), path: "/bin/bash" }];
  250. it.each(shells)(
  251. "real $dialect: rejects workspace adb, allows SDK adb, builds and scripts",
  252. async (shell) => {
  253. const root = await mkdtemp(join(tmpdir(), "zcode-adb-boundary-"));
  254. const workspace = join(root, "project with spaces");
  255. const sdk = join(root, "Android SDK");
  256. await mkdir(workspace);
  257. await mkdir(join(sdk, "platform-tools"), { recursive: true });
  258. const fake = join(workspace, windows ? "adb.exe" : "adb");
  259. const trusted = join(sdk, "platform-tools", windows ? "adb.exe" : "adb");
  260. const marker = join(root, "fake-executed");
  261. const preload = join(root, "marker.cjs");
  262. await writeFile(
  263. preload,
  264. `const p=require('node:path');if(p.basename(process.execPath).toLowerCase()==='adb.exe'){if(p.resolve(process.execPath).toLowerCase()===p.resolve(process.env.ADB_TEST_FAKE).toLowerCase())require('node:fs').writeFileSync(process.env.ADB_TEST_MARKER,'executed');else console.log('trusted-adb-ok');process.exit(0)}`,
  265. );
  266. if (windows) {
  267. await copyFile(process.execPath, fake);
  268. await copyFile(process.execPath, trusted);
  269. } else {
  270. await writeFile(fake, '#!/bin/sh\nprintf executed > "$ADB_TEST_MARKER"\n');
  271. await writeFile(trusted, "#!/bin/sh\nprintf trusted-adb-ok\n");
  272. await chmod(fake, 0o755);
  273. await chmod(trusted, 0o755);
  274. }
  275. const adapter = new NodeExecutionAdapter({
  276. outputRootDir: join(root, "output"),
  277. processEnv: {
  278. ...process.env,
  279. ANDROID_HOME: sdk,
  280. ANDROID_SDK_ROOT: sdk,
  281. ANDROID_PLUGIN_SDK_PATH: sdk,
  282. PATH: [workspace, ".", process.env.PATH ?? ""].join(delimiter),
  283. ADB_TEST_FAKE: fake,
  284. ADB_TEST_MARKER: marker,
  285. NODE_OPTIONS: `--require "${preload}"`,
  286. },
  287. });
  288. const ctx = context(adapter, workspace, shell);
  289. const quote = (file: string) =>
  290. shell.dialect === "cmd"
  291. ? `"${file}"`
  292. : `'${file.replaceAll("\\", "/").replaceAll("'", "'\\''")}'`;
  293. try {
  294. expect(
  295. await adapter.run({ command: { mode: "argv", file: fake }, cwd: workspace }),
  296. ).toMatchObject({ exitCode: 0 });
  297. expect(await readFile(marker, "utf8")).toBe("executed");
  298. await rm(marker);
  299. for (const command of [
  300. quote(fake) + " devices",
  301. (shell.dialect === "cmd" ? ".\\adb.exe" : windows ? "./adb.exe" : "./adb") + " devices",
  302. ...(shell.dialect === "cmd" ? ["@.\\adb.exe devices & echo ok"] : []),
  303. ]) {
  304. for (const run_in_background of [false, true]) {
  305. await expect(bashHandler({ command, run_in_background }, ctx)).rejects.toMatchObject({
  306. context: { reason: "workspace-adb-blocked" },
  307. });
  308. await expect(readFile(marker)).rejects.toMatchObject({ code: "ENOENT" });
  309. }
  310. }
  311. for (const command of [
  312. quote(trusted) + " devices",
  313. "adb devices",
  314. ...(shell.dialect === "cmd" ? ["@adb.exe devices & echo ok"] : []),
  315. ]) {
  316. for (const run_in_background of [false, true]) {
  317. const result = (await bashHandler({ command, run_in_background }, ctx)) as BashOutput;
  318. if (run_in_background) {
  319. const completed = await adapter.waitForBackgroundTask(result.backgroundTaskId!);
  320. expect(completed?.result).toMatchObject({ exitCode: 0 });
  321. expect(completed?.result?.stdout.text).toContain("trusted-adb-ok");
  322. } else {
  323. expect(result).toMatchObject({ exitCode: 0 });
  324. expect(result.stdout).toContain("trusted-adb-ok");
  325. }
  326. await expect(readFile(marker)).rejects.toMatchObject({ code: "ENOENT" });
  327. }
  328. }
  329. if (!windows) {
  330. const external = join(root, "bin");
  331. await mkdir(external);
  332. await symlink(fake, join(external, "adb"));
  333. await symlink(trusted, join(workspace, "sdk-adb"));
  334. for (const file of [join(external, "adb"), join(workspace, "sdk-adb")]) {
  335. expect(
  336. await adapter.resolveAdbExecutable({ file, cwd: workspace, workspaceRoot: workspace }),
  337. ).toEqual({ status: "workspace" });
  338. }
  339. await rm(join(external, "adb"));
  340. await symlink(trusted, join(external, "adb"));
  341. expect(
  342. await adapter.resolveAdbExecutable({
  343. file: join(external, "adb"),
  344. cwd: workspace,
  345. workspaceRoot: workspace,
  346. }),
  347. ).toEqual({ status: "resolved", path: await realpath(trusted) });
  348. }
  349. await writeFile(join(workspace, "script.cjs"), 'console.log("project-script-ok");');
  350. const node = quote(process.execPath);
  351. for (const prefix of shell.dialect === "cmd" ? ["", "@"] : [""]) {
  352. const result = (await bashHandler(
  353. { command: `${prefix}${node} script.cjs` },
  354. ctx,
  355. )) as BashOutput;
  356. expect(result).toMatchObject({ exitCode: 0 });
  357. expect(result.stdout).toContain("project-script-ok");
  358. }
  359. const tsc = quote(createRequire(import.meta.url).resolve("typescript/lib/tsc.js"));
  360. await writeFile(
  361. join(workspace, "main.ts"),
  362. 'const message: string = "build-ok"; console.log(message);',
  363. );
  364. await writeFile(
  365. join(workspace, "tsconfig.json"),
  366. JSON.stringify({ compilerOptions: { outDir: "dist", types: [] }, files: ["main.ts"] }),
  367. );
  368. const cmd = shell.dialect === "cmd";
  369. const wrapper = cmd ? "build.cmd" : "build.sh";
  370. await writeFile(
  371. join(workspace, wrapper),
  372. `${cmd ? "@echo off\r\n" : "#!/bin/sh\n"}${node} ${tsc} -p tsconfig.json\n`,
  373. );
  374. if (!cmd) await chmod(join(workspace, wrapper), 0o755);
  375. for (const command of shell.dialect === "cmd"
  376. ? [".\\build.cmd", "@call build.cmd"]
  377. : ["./" + wrapper]) {
  378. await rm(join(workspace, "dist"), { recursive: true, force: true });
  379. expect(await bashHandler({ command }, ctx)).toMatchObject({ exitCode: 0 });
  380. expect(await readFile(join(workspace, "dist", "main.js"), "utf8")).toContain("build-ok");
  381. }
  382. await expect(readFile(marker)).rejects.toMatchObject({ code: "ENOENT" });
  383. } finally {
  384. await adapter.close();
  385. await rm(root, { recursive: true, force: true });
  386. }
  387. },
  388. 30_000,
  389. );
  390. it("resolves bare adb from absolute PATH without searching cwd or relative entries", async () => {
  391. const root = await mkdtemp(join(tmpdir(), "zcode-adb-path-"));
  392. const workspace = join(root, "project");
  393. const external = join(root, "project-tools");
  394. const name = windows ? "adb.exe" : "adb";
  395. const env = {
  396. HOME: root,
  397. USERPROFILE: root,
  398. LOCALAPPDATA: root,
  399. PATH: ["", ".", "relative", workspace, external].join(delimiter),
  400. };
  401. const adapter = new NodeExecutionAdapter({ processEnv: env });
  402. const input = { file: name, cwd: workspace, workspaceRoot: workspace };
  403. try {
  404. await mkdir(join(workspace, "sub"), { recursive: true });
  405. await mkdir(external);
  406. await writeFile(join(workspace, name), "fake");
  407. await writeFile(join(external, name), "trusted");
  408. await chmod(join(external, name), 0o755);
  409. const expected = { status: "resolved", path: await realpath(join(external, name)) };
  410. expect(await adapter.resolveAdbExecutable(input)).toEqual(expected);
  411. // 裸命令固定到外部 PATH;显式项目路径不能被同名外部工具替换。
  412. expect(await adapter.resolveAdbExecutable({ ...input, file: "./" + name })).toEqual({
  413. status: "workspace",
  414. });
  415. expect(
  416. await adapter.resolveAdbExecutable({
  417. ...input,
  418. cwd: join(workspace, "sub"),
  419. file: "../" + name,
  420. }),
  421. ).toEqual({ status: "workspace" });
  422. expect(
  423. await adapter.resolveAdbExecutable({ ...input, file: join(external, "missing", name) }),
  424. ).toEqual({ status: "missing" });
  425. await rm(join(external, name));
  426. expect(await adapter.resolveAdbExecutable(input)).toEqual({ status: "workspace" });
  427. const noPath = new NodeExecutionAdapter({ processEnv: { ...env, PATH: "" } });
  428. try {
  429. expect(await noPath.resolveAdbExecutable(input)).toEqual({ status: "missing" });
  430. } finally {
  431. await noPath.close();
  432. }
  433. } finally {
  434. await adapter.close();
  435. await rm(root, { recursive: true, force: true });
  436. }
  437. });