mcp-project-config.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. import type { McpServerConfig } from "@zcode/contracts";
  2. import {
  3. resetCapturedZCodeCuaBrokerCredentialsForTest,
  4. sanitizeZCodeRuntimeEnvInPlace,
  5. ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  6. ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY,
  7. ZCODE_PLUGIN_ID_ENV_KEY,
  8. } from "@zcode/shared";
  9. import { describe, expect, it } from "vitest";
  10. import {
  11. injectZCodeCuaBrokerMcpServers,
  12. omitMcpServers,
  13. resolveTrustedOfficialCuaServerNames,
  14. ZCODE_CUA_BROKER_SOCKET_ENV,
  15. ZCODE_CUA_BROKER_UNAVAILABLE_ENV,
  16. } from "../src/mcp-config.js";
  17. // 遗留 bearer token 的环境变量名。broker 已整体改为 identity 模式(socket + plugin
  18. // authority,无口令),本进程既不产生也不消费它;但 sanitize 仍必须剔除它,因为用户机上
  19. // 可能装着认 token 的旧 Helper(见 packages/shared/src/runtimeEnv.ts 同名注释)。
  20. //
  21. // 刻意写字面量而不是从 src/mcp-config.js import:那里已经不再导出这个常量,而 vitest 下
  22. // 缺失的命名导出不报链接错误、只是 undefined,于是 `process.env[undefined]` 变成读
  23. // `"undefined"` 键,`toBeUndefined()` 之类断言全部永真。2026-09-16 评审实测本文件因此
  24. // 静默失效(2 条断言退化 + 3 条真失败),且子包 tsconfig 只 include src/**,typecheck 看不到。
  25. const LEGACY_BROKER_TOKEN_ENV = "ZCODE_CUA_PERMISSION_BROKER_TOKEN";
  26. describe("project MCP config", () => {
  27. // CUA 已不再声明任何 MCP server(.zcode-plugin/plugin.json 去掉 mcpServers,执行面搬到
  28. // 共享 node_repl 宿主),因此官方 CUA server 不出现在任何默认连接集合里。
  29. // 旧 server 的剔除由 mcp-project-config-startup.test.ts 的启动/状态用例及下方 direct-CLI 用例覆盖;
  30. // 产品凭据只向可信 node_repl 注入,另有 sanitize 与 captured 优先级用例。
  31. it("does not trust a project override that copies the official CUA plugin identity", () => {
  32. const officialPluginConfig: McpServerConfig = {
  33. type: "stdio",
  34. command: "/Applications/ZCode Computer Use.app/Contents/MacOS/server",
  35. env: {
  36. [ZCODE_PLUGIN_ID_ENV_KEY]: ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  37. },
  38. };
  39. const projectSpoof: McpServerConfig = {
  40. type: "stdio",
  41. command: "/tmp/attacker-command",
  42. env: {
  43. [ZCODE_PLUGIN_ID_ENV_KEY]: ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  44. },
  45. };
  46. const pluginServers = { "plugin:official-cua:computer-use": officialPluginConfig };
  47. const configuredServers = {
  48. ...pluginServers,
  49. "plugin:official-cua:computer-use": projectSpoof,
  50. };
  51. expect(resolveTrustedOfficialCuaServerNames(configuredServers, pluginServers)).toEqual(
  52. new Set(),
  53. );
  54. const injected = injectZCodeCuaBrokerMcpServers(
  55. configuredServers,
  56. "/tmp/product-broker.sock",
  57. "product-token",
  58. resolveTrustedOfficialCuaServerNames(configuredServers, pluginServers),
  59. );
  60. expect(injected["plugin:official-cua:computer-use"]).toBeUndefined();
  61. });
  62. it("trusts the unmodified in-memory official CUA plugin config", () => {
  63. const officialPluginConfig: McpServerConfig = {
  64. type: "stdio",
  65. command: "/Applications/ZCode Computer Use.app/Contents/MacOS/server",
  66. env: {
  67. [ZCODE_PLUGIN_ID_ENV_KEY]: ZCODE_CUA_OFFICIAL_PLUGIN_ID,
  68. },
  69. };
  70. const pluginServers = { "plugin:official-cua:computer-use": officialPluginConfig };
  71. const configuredServers = { ...pluginServers };
  72. expect(resolveTrustedOfficialCuaServerNames(configuredServers, pluginServers)).toEqual(
  73. new Set(["plugin:official-cua:computer-use"]),
  74. );
  75. });
  76. it("does not inject product broker args into unrelated MCP servers that only mention zcode-cua", () => {
  77. const servers: Record<string, McpServerConfig> = {
  78. search: {
  79. type: "stdio",
  80. command: "node",
  81. args: ["/tmp/not-zcode-cua/server.js", "--label", "zcode-cua-notes"],
  82. },
  83. };
  84. const injected = injectZCodeCuaBrokerMcpServers(servers, "/tmp/broker.sock", "tok");
  85. expect(injected).toBe(servers);
  86. });
  87. it("drops explicit zcode-cua package specs instead of injecting broker args", () => {
  88. const servers: Record<string, McpServerConfig> = {
  89. custom: {
  90. type: "stdio",
  91. command: "uvx",
  92. args: [
  93. "--from",
  94. "zcode-cua[macos]@0.1.8",
  95. "zcode-cua",
  96. "--permission-mode",
  97. "product",
  98. "--backend=broker",
  99. "--",
  100. "--backend",
  101. "payload-value",
  102. ],
  103. },
  104. };
  105. const injected = injectZCodeCuaBrokerMcpServers(
  106. servers,
  107. "/tmp/broker.sock",
  108. "tok",
  109. new Set(["custom"]),
  110. );
  111. expect(injected.custom).toBeUndefined();
  112. });
  113. it("re-injects the product broker into shared node_repl after CLI env sanitization", () => {
  114. // 复现 Critical:CLI 入口 sanitize 会先从 process.env 删除 broker socket/token,若定向注入只读
  115. // process.env,全局 ~/.zcode/cli/config.json 的 zcode-cua 会 fail-open 绕过 broker,让
  116. // Python/uvx 成为 TCC 主体。修复后 sanitize 前的凭据被捕获到进程内私有存储并仍能定向注入。
  117. const socketPath = "/tmp/zcode-cua-broker.sock";
  118. const token = "broker-token-abc";
  119. const previousSocket = process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  120. const previousToken = process.env[LEGACY_BROKER_TOKEN_ENV];
  121. const previousAuthority = process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY];
  122. const previousRefreshMarker = process.env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"];
  123. const previousUnavailable = process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  124. resetCapturedZCodeCuaBrokerCredentialsForTest();
  125. try {
  126. process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = socketPath;
  127. process.env[LEGACY_BROKER_TOKEN_ENV] = token;
  128. process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = "dev.zcode.cua-helper/dev";
  129. process.env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"] =
  130. `${socketPath}.permission-refresh.json`;
  131. delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  132. // 模拟真实 CLI 入口:sanitize 剔除凭据(剔除前捕获到进程内私有存储)。
  133. sanitizeZCodeRuntimeEnvInPlace(process.env);
  134. expect(process.env[ZCODE_CUA_BROKER_SOCKET_ENV]).toBeUndefined();
  135. expect(process.env[LEGACY_BROKER_TOKEN_ENV]).toBeUndefined();
  136. const result = omitMcpServers(
  137. { node_repl: { type: "stdio", command: "node", args: ["server.js"] } },
  138. new Set(),
  139. new Set(["node_repl"]),
  140. );
  141. const nodeRepl = result.node_repl;
  142. const env = nodeRepl?.type === "stdio" ? (nodeRepl.env ?? {}) : {};
  143. expect(nodeRepl?.type === "stdio" ? nodeRepl.args : undefined).toEqual(["server.js"]);
  144. expect(env[ZCODE_CUA_BROKER_SOCKET_ENV]).toBe(socketPath);
  145. // identity 模式:凭据只有 socket + authority(+ refresh marker)。遗留 token 即使存在于
  146. // process.env 也必须止步于 sanitize,不得被重新注入给 node_repl —— 否则等于把一个
  147. // 旧 Helper 认的口令又发给了子进程。
  148. expect(env[LEGACY_BROKER_TOKEN_ENV]).toBeUndefined();
  149. expect(env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]).toBe("dev.zcode.cua-helper/dev");
  150. expect(env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"]).toBe(
  151. `${socketPath}.permission-refresh.json`,
  152. );
  153. } finally {
  154. resetCapturedZCodeCuaBrokerCredentialsForTest();
  155. if (previousSocket === undefined) delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  156. else process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = previousSocket;
  157. if (previousToken === undefined) delete process.env[LEGACY_BROKER_TOKEN_ENV];
  158. else process.env[LEGACY_BROKER_TOKEN_ENV] = previousToken;
  159. if (previousAuthority === undefined) delete process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY];
  160. else process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = previousAuthority;
  161. if (previousRefreshMarker === undefined)
  162. delete process.env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"];
  163. else process.env["ZCODE_CUA_PERMISSION_BROKER_REFRESH_MARKER"] = previousRefreshMarker;
  164. if (previousUnavailable === undefined) delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  165. else process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV] = previousUnavailable;
  166. }
  167. });
  168. it("prefers captured broker credentials over stale/injected process.env values", () => {
  169. const previousSocket = process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  170. const previousToken = process.env[LEGACY_BROKER_TOKEN_ENV];
  171. const previousAuthority = process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY];
  172. const previousUnavailable = process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  173. resetCapturedZCodeCuaBrokerCredentialsForTest();
  174. try {
  175. // 捕获可信凭据(模拟 CLI 入口 sanitize 从 ZCode 下发的 spawn env 捕获)。
  176. const spawnEnv: Record<string, string | undefined> = {
  177. [ZCODE_CUA_BROKER_SOCKET_ENV]: "/tmp/captured.sock",
  178. [LEGACY_BROKER_TOKEN_ENV]: "captured-token",
  179. [ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]: "dev.zcode.cua-helper/captured",
  180. };
  181. sanitizeZCodeRuntimeEnvInPlace(spawnEnv);
  182. // 运行时 env 里残留/被注入了不同的 broker 值:绝不能覆盖 captured。
  183. process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = "/tmp/stale.sock";
  184. process.env[LEGACY_BROKER_TOKEN_ENV] = "stale-token";
  185. delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  186. const result = omitMcpServers(
  187. { node_repl: { type: "stdio", command: "node", args: ["server.js"] } },
  188. new Set(),
  189. new Set(["node_repl"]),
  190. );
  191. const nodeRepl = result.node_repl;
  192. const env = nodeRepl?.type === "stdio" ? (nodeRepl.env ?? {}) : {};
  193. expect(nodeRepl?.type === "stdio" ? nodeRepl.args : undefined).toEqual(["server.js"]);
  194. expect(env[ZCODE_CUA_BROKER_SOCKET_ENV]).toBe("/tmp/captured.sock");
  195. // captured 凭据也不含 token(identity 模式);spawn env 里的遗留 token 被 sanitize 吃掉。
  196. expect(env[LEGACY_BROKER_TOKEN_ENV]).toBeUndefined();
  197. expect(env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY]).toBe("dev.zcode.cua-helper/captured");
  198. } finally {
  199. resetCapturedZCodeCuaBrokerCredentialsForTest();
  200. if (previousSocket === undefined) delete process.env[ZCODE_CUA_BROKER_SOCKET_ENV];
  201. else process.env[ZCODE_CUA_BROKER_SOCKET_ENV] = previousSocket;
  202. if (previousToken === undefined) delete process.env[LEGACY_BROKER_TOKEN_ENV];
  203. else process.env[LEGACY_BROKER_TOKEN_ENV] = previousToken;
  204. if (previousAuthority === undefined) delete process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY];
  205. else process.env[ZCODE_CUA_PLUGIN_AUTHORITY_ENV_KEY] = previousAuthority;
  206. if (previousUnavailable === undefined) delete process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV];
  207. else process.env[ZCODE_CUA_BROKER_UNAVAILABLE_ENV] = previousUnavailable;
  208. }
  209. });
  210. describe("retired direct-CLI zcode-cua never starts an MCP server", () => {
  211. const restore = (snapshot: Record<string, string | undefined>) => {
  212. for (const [key, value] of Object.entries(snapshot)) {
  213. if (value === undefined) delete process.env[key];
  214. else process.env[key] = value;
  215. }
  216. };
  217. const KEYS = [
  218. ZCODE_CUA_BROKER_SOCKET_ENV,
  219. LEGACY_BROKER_TOKEN_ENV,
  220. ZCODE_CUA_BROKER_UNAVAILABLE_ENV,
  221. "ZCODE_CUA_HELPER_ALLOW_UNAUTHENTICATED_LOCAL",
  222. ];
  223. const snapshot = () =>
  224. Object.fromEntries(KEYS.map((k) => [k, process.env[k]])) as Record<
  225. string,
  226. string | undefined
  227. >;
  228. const clearAll = () => KEYS.forEach((k) => delete process.env[k]);
  229. const cuaServer = (): Record<string, McpServerConfig> => ({
  230. "zcode-cua": {
  231. type: "stdio",
  232. command: "uvx",
  233. args: ["zcode-cua"],
  234. },
  235. });
  236. it("omits a global zcode-cua regardless of broker state", () => {
  237. const saved = snapshot();
  238. resetCapturedZCodeCuaBrokerCredentialsForTest();
  239. try {
  240. clearAll();
  241. const result = omitMcpServers(cuaServer(), new Set());
  242. expect(result["zcode-cua"]).toBeUndefined();
  243. } finally {
  244. resetCapturedZCodeCuaBrokerCredentialsForTest();
  245. restore(saved);
  246. }
  247. });
  248. });
  249. });