workspace-mcp-trust.test.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, expect, it, vi } from "vitest";
  5. import { createConfig } from "@zcode/adapters/config";
  6. import {
  7. convertToZCodeAgentMcpServer,
  8. type McpServerConfig as HostMcpServerConfig,
  9. } from "@zcode/shared";
  10. import type { McpPort } from "@zcode/contracts";
  11. import { resolveAppRuntimeConfig } from "../src/app/runtime-config.js";
  12. import { protocolMcpServersToRuntimeMcpConfig } from "../src/zcode-protocol/protocol-mcp-config.js";
  13. const roots: string[] = [];
  14. afterEach(async () => {
  15. await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
  16. });
  17. it("工作区直接 MCP 不得被当作用户可信配置", async () => {
  18. const root = await mkdtemp(join(tmpdir(), "workspace-mcp-trust-"));
  19. roots.push(root);
  20. await mkdir(join(root, ".zcode"));
  21. await writeFile(
  22. join(root, ".zcode/config.json"),
  23. JSON.stringify({
  24. mcp: {
  25. servers: {
  26. probe: { type: "stdio", command: process.execPath, args: ["-e", "process.exit(0)"] },
  27. },
  28. },
  29. }),
  30. );
  31. // 合并后的 MCP 配置由配置源提供,runtime 配置只负责补来源标记与待信任集合。
  32. const configResult = createConfig({ workingDirectory: root, skipUserConfig: true, env: {} });
  33. const result = resolveAppRuntimeConfig({
  34. cliStorageRoot: join(root, "storage"),
  35. configResult,
  36. options: {},
  37. mcpConfiguration: configResult.config.mcp,
  38. subagentOutputRootDir: join(root, "output"),
  39. workingDirectory: root,
  40. });
  41. expect(result.untrustedProjectMcpServers.has("probe")).toBe(true);
  42. });
  43. import { access, readFile } from "node:fs/promises";
  44. import { createServer } from "node:http";
  45. import { createMcpAdapter, createMcpAdapterConnectionPool } from "@zcode/adapters/mcp";
  46. import type { McpServerConfig } from "@zcode/contracts";
  47. import { createWorkspaceMcpTrust } from "../src/workspace-mcp-trust/index.js";
  48. async function fixture(exitAfterCall = false) {
  49. const root = await mkdtemp(join(tmpdir(), "workspace-mcp-runtime-"));
  50. roots.push(root);
  51. const workspace = join(root, "workspace");
  52. const userConfigPath = join(root, "user.json");
  53. const marker = join(root, "started");
  54. const script = join(root, "server.mjs");
  55. await mkdir(join(workspace, ".zcode"), { recursive: true });
  56. await writeFile(userConfigPath, JSON.stringify({ storage: { dir: join(root, "user-data") } }));
  57. await writeFile(
  58. script,
  59. `import {writeFile, appendFile} from 'node:fs/promises';
  60. import {createInterface} from 'node:readline';
  61. await writeFile(process.argv[2], 'started');
  62. for await (const line of createInterface({input:process.stdin})) {
  63. const r=JSON.parse(line); if(r.id===undefined) continue;
  64. const result=r.method==='initialize'?{protocolVersion:'2025-11-25',capabilities:{tools:{}},serverInfo:{name:'local-test',version:'1'}}:
  65. r.method==='tools/list'?{tools:[{name:'probe',description:'local probe',inputSchema:{type:'object'}}]}:
  66. r.method==='tools/call'?{content:[{type:'text',text:'ok'}]}:{};
  67. if(r.method==='tools/call') await appendFile(process.argv[2], '\\ncall');
  68. process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:r.id,result})+'\\n', () => {
  69. if (${exitAfterCall} && r.method==='tools/call') process.exit(0);
  70. });
  71. }`,
  72. );
  73. const config: McpServerConfig = {
  74. type: "stdio",
  75. command: process.execPath,
  76. args: [script, marker],
  77. protocolVersion: "legacy",
  78. source: { kind: "workspace" },
  79. };
  80. async function save(value: McpServerConfig = config) {
  81. const { source: _source, ...raw } = value;
  82. await writeFile(
  83. join(workspace, ".zcode/config.json"),
  84. JSON.stringify({ mcp: { servers: { probe: raw } } }),
  85. );
  86. }
  87. await save();
  88. const options = { workingDirectory: workspace, userConfigPath, env: {} };
  89. return {
  90. root,
  91. workspace,
  92. marker,
  93. config,
  94. options,
  95. save,
  96. authority: createWorkspaceMcpTrust(options),
  97. };
  98. }
  99. it("真实 stdio:未信任零进程,授权后握手,撤销在下次连接准入生效", async () => {
  100. const f = await fixture();
  101. let pendingCount = 0;
  102. f.authority = createWorkspaceMcpTrust({
  103. ...f.options,
  104. onAdmissionChanged: async (state) => {
  105. pendingCount = state.pendingCount;
  106. },
  107. });
  108. const port = f.authority.guard(createMcpAdapter());
  109. try {
  110. expect((await port.connectServer("probe", f.config)).status).toBe("untrusted");
  111. await expect(access(f.marker)).rejects.toThrow();
  112. const review = (await f.authority.inspect()).probe!;
  113. await f.authority.decide("probe", review.declarationDigest, true);
  114. expect((await port.connectServer("probe", f.config)).status).toBe("connected");
  115. expect(await readFile(f.marker, "utf8")).toBe("started");
  116. expect(await createWorkspaceMcpTrust(f.options).allows("probe", f.config)).toBe(true);
  117. await port.callTool({ serverName: "probe", toolName: "probe", arguments: {} });
  118. await f.authority.decide("probe", review.declarationDigest, false);
  119. await port.refreshWorkspaceTrustAdmission!();
  120. expect(pendingCount).toBe(1);
  121. await port.callTool({ serverName: "probe", toolName: "probe" });
  122. expect(await port.listTools()).toHaveLength(1);
  123. expect((await port.connectServer("probe", f.config)).status).toBe("untrusted");
  124. await expect(port.callTool({ serverName: "probe", toolName: "probe" })).rejects.toThrow(
  125. "workspace_mcp_pending_trust",
  126. );
  127. expect(await port.listTools()).toEqual([]);
  128. expect(await readFile(f.marker, "utf8")).toBe("started\ncall\ncall");
  129. } finally {
  130. await port.close();
  131. }
  132. });
  133. it("连接内工具调用、状态、列表与 ping 不重复读取授权,断开后拒绝调用", async () => {
  134. const f = await fixture();
  135. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  136. const check = vi.spyOn(f.authority, "allows");
  137. const port = f.authority.guard(createMcpAdapter());
  138. try {
  139. await port.connectServer("probe", f.config);
  140. check.mockClear();
  141. for (let i = 0; i < 3; i++) {
  142. await port.callTool({ serverName: "probe", toolName: "probe" });
  143. expect((await port.status()).probe?.status).toBe("connected");
  144. expect(await port.listTools()).toHaveLength(1);
  145. expect(await port.pingServer!("probe")).toBe(true);
  146. }
  147. expect(check).not.toHaveBeenCalled();
  148. await port.disconnectServer("probe");
  149. await expect(port.callTool({ serverName: "probe", toolName: "probe" })).rejects.toThrow(
  150. "workspace_mcp_pending_trust",
  151. );
  152. expect(await readFile(f.marker, "utf8")).toBe("started\ncall\ncall\ncall");
  153. } finally {
  154. check.mockRestore();
  155. await port.close();
  156. }
  157. });
  158. it("真实断线自动重连沿用会话授权,撤销后新会话准入拒绝", async () => {
  159. const f = await fixture(true);
  160. const review = (await f.authority.inspect()).probe!;
  161. await f.authority.decide("probe", review.declarationDigest, true);
  162. const raw = createMcpAdapter();
  163. const connects = vi.spyOn(raw, "connectServer");
  164. const check = vi.spyOn(f.authority, "allows");
  165. const port = f.authority.guard(raw);
  166. const restarted = createWorkspaceMcpTrust(f.options).guard(createMcpAdapter());
  167. try {
  168. await port.connectServer("probe", f.config);
  169. check.mockClear();
  170. await port.callTool({ serverName: "probe", toolName: "probe" });
  171. // 意外断开后由 adapter 自己恢复;恢复用尽后提交 failed,下一次执行准入再重连。
  172. await vi.waitFor(async () => {
  173. expect((await port.status()).probe?.status).toBe("failed");
  174. });
  175. await f.authority.decide("probe", review.declarationDigest, false);
  176. await expect(port.callTool({ serverName: "probe", toolName: "probe" })).resolves.toMatchObject({
  177. content: [{ type: "text", text: "ok" }],
  178. });
  179. // 重连由 adapter 内部完成,不再经过端口的 connectServer:按实际连上的状态取证。
  180. expect(connects).toHaveBeenCalledOnce();
  181. expect((await port.status()).probe?.status).toBe("connected");
  182. expect(check).not.toHaveBeenCalled();
  183. expect((await restarted.connectServer("probe", f.config)).status).toBe("untrusted");
  184. await expect(restarted.callTool({ serverName: "probe", toolName: "probe" })).rejects.toThrow(
  185. "workspace_mcp_pending_trust",
  186. );
  187. } finally {
  188. connects.mockRestore();
  189. check.mockRestore();
  190. await port.close();
  191. await restarted.close();
  192. }
  193. });
  194. it.each(["changed", "removed", "disabled", "corrupt"] as const)(
  195. "连接后 %s 不影响已批准连接,下次连接准入拒绝",
  196. async (change) => {
  197. const f = await fixture();
  198. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  199. const port = f.authority.guard(createMcpAdapter());
  200. try {
  201. await port.connectServer("probe", f.config);
  202. if (change === "changed") await f.save({ ...f.config, env: { VERSION: "2" } });
  203. if (change === "disabled") await f.save({ ...f.config, enabled: false });
  204. if (change === "removed") await writeFile(join(f.workspace, ".zcode/config.json"), "{}");
  205. if (change === "corrupt")
  206. await writeFile(join(f.root, "user-data/security/workspace-mcp-trust-v1.json"), "invalid");
  207. await port.callTool({ serverName: "probe", toolName: "probe" });
  208. expect((await port.connectServer("probe", f.config)).status).toBe("untrusted");
  209. await expect(port.callTool({ serverName: "probe", toolName: "probe" })).rejects.toThrow(
  210. "workspace_mcp_pending_trust",
  211. );
  212. expect(await readFile(f.marker, "utf8")).toBe("started\ncall");
  213. } finally {
  214. await port.close();
  215. }
  216. },
  217. );
  218. it("声明变化拒绝旧审核与旧连接配置;enabled 不扩大或清除授权", async () => {
  219. const f = await fixture();
  220. const old = (await f.authority.inspect()).probe!;
  221. await f.authority.decide("probe", old.declarationDigest, true);
  222. await f.save({ ...f.config, enabled: false });
  223. expect((await f.authority.inspect()).probe?.declarationDigest).toBe(old.declarationDigest);
  224. expect(await f.authority.allows("probe", f.config)).toBe(false);
  225. await f.save({ ...f.config, env: { VERSION: "2" } });
  226. expect(await f.authority.allows("probe", f.config)).toBe(false);
  227. await expect(f.authority.decide("probe", old.declarationDigest, true)).rejects.toThrow(
  228. "workspace_mcp_declaration_changed",
  229. );
  230. await writeFile(join(f.workspace, ".zcode/config.json"), "{}");
  231. expect(await f.authority.allows("probe", f.config)).toBe(false);
  232. });
  233. it("HTTP/SSE 未信任不发出任何请求;secret 不进入审核显示或存储", async () => {
  234. const f = await fixture();
  235. let requests = 0;
  236. const server = createServer((_request, response) => {
  237. requests++;
  238. response.writeHead(500).end();
  239. });
  240. await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
  241. const address = server.address();
  242. if (!address || typeof address === "string") throw new Error("no address");
  243. const port = f.authority.guard(createMcpAdapter());
  244. try {
  245. for (const type of ["http", "sse"] as const) {
  246. const config: McpServerConfig = {
  247. type,
  248. url: `http://127.0.0.1:${address.port}/mcp?token=secret-query`,
  249. headers: { Authorization: "secret-header" },
  250. source: { kind: "workspace" },
  251. };
  252. await f.save(config);
  253. expect((await port.connectServer("probe", config)).status).toBe("untrusted");
  254. const review = (await f.authority.inspect()).probe!;
  255. expect(review.display).not.toContain("secret");
  256. await f.authority.decide("probe", review.declarationDigest, true);
  257. const content = await readFile(
  258. join(f.root, "user-data/security/workspace-mcp-trust-v1.json"),
  259. "utf8",
  260. );
  261. expect(content).not.toContain("secret");
  262. }
  263. expect(requests).toBe(0);
  264. } finally {
  265. await port.close();
  266. await new Promise<void>((done) => server.close(() => done()));
  267. }
  268. });
  269. it("同名 server 不跨 workspaceIdentity 继承授权,包括连接池 lease 复用", async () => {
  270. const f = await fixture();
  271. const other = createWorkspaceMcpTrust({ ...f.options, workspaceIdentity: "remote:other" });
  272. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  273. const pool = createMcpAdapterConnectionPool({ idleGraceMs: 0 });
  274. const first = f.authority.guard(pool.acquireLease());
  275. const second = other.guard(pool.acquireLease());
  276. try {
  277. expect((await first.connectServer("probe", f.config)).status).toBe("connected");
  278. expect((await second.connectServer("probe", f.config)).status).toBe("untrusted");
  279. expect(await second.listTools()).toEqual([]);
  280. } finally {
  281. await first.close();
  282. await second.close();
  283. await pool.close();
  284. }
  285. });
  286. it("损坏授权文件拒绝执行与授权;项目 storage.dir 不改变用户域记录位置", async () => {
  287. const f = await fixture();
  288. const review = (await f.authority.inspect()).probe!;
  289. await f.authority.decide("probe", review.declarationDigest, true);
  290. await writeFile(
  291. join(f.root, "user-data/security/workspace-mcp-trust-v1.json"),
  292. '{"schemaVersion":99,"records":[]}',
  293. );
  294. expect(await f.authority.allows("probe", f.config)).toBe(false);
  295. await expect(f.authority.decide("probe", review.declarationDigest, true)).rejects.toThrow();
  296. });
  297. it(".agents 工作区 fallback 也必须单独审核;用户和插件来源不被误拦截", async () => {
  298. const f = await fixture();
  299. await writeFile(join(f.workspace, ".zcode/config.json"), "{}");
  300. await mkdir(join(f.workspace, ".agents"));
  301. const { source: _source, ...raw } = f.config;
  302. await writeFile(
  303. join(f.workspace, ".agents/mcp.json"),
  304. JSON.stringify({ mcpServers: { probe: raw } }),
  305. );
  306. expect(await f.authority.allows("probe", f.config)).toBe(false);
  307. expect((await f.authority.inspect()).probe?.sourcePaths).toEqual([
  308. join(f.workspace, ".agents/mcp.json"),
  309. ]);
  310. for (const kind of ["user", "plugin", "builtin"] as const) {
  311. expect(await f.authority.allows("probe", { ...f.config, source: { kind } })).toBe(true);
  312. }
  313. });
  314. it("连接使用审核时的私有配置副本,调用方修改对象不能改变实际 spawn", async () => {
  315. const f = await fixture();
  316. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  317. const port = f.authority.guard(createMcpAdapter());
  318. try {
  319. const connecting = port.connectServer("probe", f.config);
  320. if (f.config.type === "stdio") f.config.args = ["-e", "throw new Error('mutated')"];
  321. expect((await connecting).status).toBe("connected");
  322. expect(await readFile(f.marker, "utf8")).toBe("started");
  323. } finally {
  324. await port.close();
  325. }
  326. });
  327. it("并发进程批准不同 workspace 时不丢失记录", async () => {
  328. const f = await fixture();
  329. const { execFile } = await import("node:child_process");
  330. const { promisify } = await import("node:util");
  331. const run = promisify(execFile);
  332. const moduleUrl = new URL("../src/workspace-mcp-trust/index.ts", import.meta.url).href;
  333. const script = `const { createWorkspaceMcpTrust } = await import(process.argv[1]);
  334. const authority = createWorkspaceMcpTrust(JSON.parse(process.argv[2]));
  335. await authority.decide('probe', (await authority.inspect()).probe.declarationDigest, true);`;
  336. await Promise.all(
  337. ["first", "second"].map((workspaceIdentity) =>
  338. run(process.execPath, [
  339. "--import",
  340. "tsx",
  341. "--input-type=module",
  342. "-e",
  343. script,
  344. moduleUrl,
  345. JSON.stringify({ ...f.options, workspaceIdentity }),
  346. ]),
  347. ),
  348. );
  349. const store = JSON.parse(
  350. await readFile(join(f.root, "user-data/security/workspace-mcp-trust-v1.json"), "utf8"),
  351. );
  352. expect(
  353. store.records.map((record: { workspaceIdentity: string }) => record.workspaceIdentity).sort(),
  354. ).toEqual(["first", "second"]);
  355. });
  356. it("stdio 审核不显示以命令参数传入的常见密钥", async () => {
  357. const f = await fixture();
  358. if (f.config.type !== "stdio") throw new Error("expected stdio");
  359. await f.save({ ...f.config, args: [...f.config.args!, "--token", "secret-command-argument"] });
  360. expect((await f.authority.inspect()).probe!.display).not.toContain("secret-command-argument");
  361. });
  362. it("并发连接 mutation 串行收敛,避免新声明映射到旧连接", async () => {
  363. const f = await fixture();
  364. f.authority.allows = async () => true;
  365. let release!: () => void;
  366. const barrier = new Promise<void>((resolve) => {
  367. release = resolve;
  368. });
  369. let active = 0;
  370. let peak = 0;
  371. const raw = createMcpAdapter();
  372. raw.connectServer = async (_name, config) => {
  373. active++;
  374. peak = Math.max(peak, active);
  375. await barrier;
  376. active--;
  377. return {
  378. status: "connected",
  379. transport: config.type,
  380. toolCount: 0,
  381. updatedAt: new Date().toISOString(),
  382. };
  383. };
  384. const port = f.authority.guard(raw);
  385. const first = port.connectServer("probe", f.config);
  386. const second = port.connectServer("probe", f.config);
  387. await new Promise<void>((done) => setImmediate(done));
  388. release();
  389. await Promise.all([first, second]);
  390. expect(peak).toBe(1);
  391. await port.close();
  392. });
  393. // 回归:调用等整条变更队列(含其他 server 的连接握手),后台启动或配置热更新期间,
  394. // 调用已连上的 A 要等最慢的 B;等待期间排进新的变更,这次调用还会以 pending_trust 失败。
  395. it("工具调用只等进行中的准入判定,不等其他 server 的连接", async () => {
  396. const f = await fixture();
  397. const user = { ...f.config, source: { kind: "user" as const } };
  398. const handshake = Promise.withResolvers<void>();
  399. const calls: string[] = [];
  400. const raw = createMcpAdapter();
  401. raw.connectConfiguredServers = async () => {
  402. await handshake.promise;
  403. return { statuses: {}, tools: [] };
  404. };
  405. raw.callTool = async (request) => {
  406. calls.push(request.serverName);
  407. return { content: [{ type: "text", text: "ok" }] };
  408. };
  409. const port = f.authority.guard(raw);
  410. try {
  411. const startup = port.connectConfiguredServers({ fast: user, slow: user });
  412. await new Promise<void>((done) => setImmediate(done));
  413. await expect(port.callTool({ serverName: "fast", toolName: "probe" })).resolves.toBeDefined();
  414. // 排队中的变更不使调用失败:变更开始前调用走当前准入结果。
  415. const reconcile = port.connectConfiguredServers({ fast: user, slow: user, other: user });
  416. await expect(port.callTool({ serverName: "fast", toolName: "probe" })).resolves.toBeDefined();
  417. expect(calls).toEqual(["fast", "fast"]);
  418. handshake.resolve();
  419. await Promise.all([startup, reconcile]);
  420. } finally {
  421. handshake.resolve();
  422. await port.close();
  423. }
  424. });
  425. // 回归:reconcile 先释放工作区 server,等其他 server 握手后再重新连接。只等准入判定时,这段时间到达的
  426. // 调用会落到已释放的连接上失败;它要等这个 server 重新连接后再执行。
  427. it("reconcile 期间调用工作区 server,等它重新连接后执行", async () => {
  428. const f = await fixture();
  429. const review = (await f.authority.inspect()).probe!;
  430. await f.authority.decide("probe", review.declarationDigest, true);
  431. const user = { ...f.config, source: { kind: "user" as const } };
  432. const connected = new Set<string>();
  433. const calls: string[] = [];
  434. let handshake: Promise<void> = Promise.resolve();
  435. const reconcileStarted = Promise.withResolvers<void>();
  436. const raw = createMcpAdapter();
  437. raw.connectConfiguredServers = async (servers) => {
  438. // 与租约相同:不在新集合里的 server 立即释放,握手结束后才连上。
  439. for (const name of [...connected]) if (!Object.hasOwn(servers, name)) connected.delete(name);
  440. if (Object.hasOwn(servers, "slow")) reconcileStarted.resolve();
  441. await handshake;
  442. for (const name of Object.keys(servers)) connected.add(name);
  443. return { statuses: {}, tools: [] };
  444. };
  445. raw.connectServer = async (name, config) => {
  446. connected.add(name);
  447. return {
  448. status: "connected",
  449. transport: config.type,
  450. toolCount: 0,
  451. updatedAt: new Date().toISOString(),
  452. };
  453. };
  454. raw.callTool = async (request) => {
  455. if (!connected.has(request.serverName)) throw new Error(`released: ${request.serverName}`);
  456. calls.push(request.serverName);
  457. return { content: [{ type: "text", text: "ok" }] };
  458. };
  459. const port = f.authority.guard(raw);
  460. const gate = Promise.withResolvers<void>();
  461. try {
  462. await port.connectConfiguredServers({ probe: f.config, fast: user });
  463. expect([...connected].sort()).toEqual(["fast", "probe"]);
  464. handshake = gate.promise;
  465. const reconcile = port.connectConfiguredServers({ probe: f.config, fast: user, slow: user });
  466. await reconcileStarted.promise;
  467. expect(connected.has("probe")).toBe(false);
  468. const call = port.callTool({ serverName: "probe", toolName: "probe" });
  469. // 用户来源的 server 不受影响,照常执行。
  470. await expect(port.callTool({ serverName: "fast", toolName: "probe" })).resolves.toBeDefined();
  471. gate.resolve();
  472. await expect(call).resolves.toBeDefined();
  473. expect(calls).toEqual(["fast", "probe"]);
  474. await reconcile;
  475. } finally {
  476. gate.resolve();
  477. await port.close();
  478. }
  479. });
  480. it("准入判定期间到达的调用等判定结束,再按结果执行或拒绝", async () => {
  481. const f = await fixture();
  482. const decision = Promise.withResolvers<boolean>();
  483. vi.spyOn(f.authority, "allows").mockImplementation(() => decision.promise);
  484. const calls: string[] = [];
  485. const raw = createMcpAdapter();
  486. raw.connectConfiguredServers = async () => ({ statuses: {}, tools: [] });
  487. raw.connectServer = async (_name, config) => ({
  488. status: "connected",
  489. transport: config.type,
  490. toolCount: 0,
  491. updatedAt: new Date().toISOString(),
  492. });
  493. raw.callTool = async (request) => {
  494. calls.push(request.serverName);
  495. return { content: [{ type: "text", text: "ok" }] };
  496. };
  497. const port = f.authority.guard(raw);
  498. try {
  499. const startup = port.connectConfiguredServers({ probe: f.config });
  500. await new Promise<void>((done) => setImmediate(done));
  501. const call = port.callTool({ serverName: "probe", toolName: "probe" });
  502. await new Promise<void>((done) => setImmediate(done));
  503. expect(calls).toEqual([]);
  504. decision.resolve(true);
  505. await expect(call).resolves.toBeDefined();
  506. expect(calls).toEqual(["probe"]);
  507. await startup;
  508. } finally {
  509. decision.resolve(false);
  510. await port.close();
  511. }
  512. });
  513. it.each(["single", "configured"])("%s 准入未完成时,工具列表只查内存且默认拒绝", async (mode) => {
  514. const f = await fixture();
  515. let release!: () => void;
  516. const barrier = new Promise<void>((resolve) => {
  517. release = resolve;
  518. });
  519. const check = vi.spyOn(f.authority, "allows").mockImplementation(async () => {
  520. await barrier;
  521. return false;
  522. });
  523. const raw = createMcpAdapter();
  524. raw.listTools = async () => [{ serverName: "probe", toolName: "probe", inputSchema: {} }];
  525. const port = f.authority.guard(raw);
  526. const connecting =
  527. mode === "single"
  528. ? port.connectServer("probe", f.config)
  529. : port.connectConfiguredServers({ probe: f.config });
  530. try {
  531. await new Promise<void>((done) => setImmediate(done));
  532. const listing = port.listTools();
  533. await new Promise<void>((done) => setImmediate(done));
  534. release();
  535. expect(await listing).toEqual([]);
  536. expect(check).toHaveBeenCalledTimes(1);
  537. await connecting;
  538. } finally {
  539. release();
  540. await connecting;
  541. check.mockRestore();
  542. await port.close();
  543. }
  544. });
  545. it.each(["single", "configured"])("关闭 lease 后,迟到的 %s 准入结果不能启动连接", async (mode) => {
  546. const f = await fixture();
  547. let resolveAllowed!: (value: boolean) => void;
  548. f.authority.allows = () =>
  549. new Promise<boolean>((resolve) => {
  550. resolveAllowed = resolve;
  551. });
  552. const raw = createMcpAdapter();
  553. let connects = 0;
  554. raw.connectServer = async (_name, config) => {
  555. connects++;
  556. return {
  557. status: "connected",
  558. transport: config.type,
  559. toolCount: 0,
  560. updatedAt: new Date().toISOString(),
  561. };
  562. };
  563. raw.connectConfiguredServers = async () => {
  564. connects++;
  565. return { statuses: {}, tools: [] };
  566. };
  567. const port = f.authority.guard(raw);
  568. const pending = (
  569. mode === "single"
  570. ? port.connectServer("probe", f.config)
  571. : port.connectConfiguredServers({ probe: f.config })
  572. ).catch(() => undefined);
  573. await new Promise<void>((done) => setImmediate(done));
  574. resolveAllowed(true);
  575. queueMicrotask(() => {
  576. void port.close();
  577. });
  578. await pending;
  579. expect(connects).toBe(0);
  580. });
  581. it("HTTP URL、header 与 OAuth 凭据的变化都使原授权失效", async () => {
  582. const f = await fixture();
  583. const original: McpServerConfig = {
  584. type: "http",
  585. url: "https://mcp.example.test/one",
  586. headers: { Authorization: "first" },
  587. oauth: { type: "client_credentials", clientId: "client", clientSecret: "first" },
  588. source: { kind: "workspace" },
  589. };
  590. await f.save(original);
  591. const review = (await f.authority.inspect()).probe!;
  592. await f.authority.decide("probe", review.declarationDigest, true);
  593. for (const config of [
  594. { ...original, url: "https://mcp.example.test/two" },
  595. { ...original, headers: { Authorization: "second" } },
  596. {
  597. ...original,
  598. oauth: { type: "client_credentials" as const, clientId: "client", clientSecret: "second" },
  599. },
  600. ]) {
  601. await f.save(config);
  602. expect((await f.authority.inspect()).probe!.declarationDigest).not.toBe(
  603. review.declarationDigest,
  604. );
  605. expect(await f.authority.allows("probe", config)).toBe(false);
  606. expect(await f.authority.allows("probe", original)).toBe(false);
  607. }
  608. });
  609. it.each(["environment", "windows-command", "isolation"])(
  610. "审核与 Host DTO 对 %s 使用相同执行配置,真实字段变化仍拒绝",
  611. async (variant) => {
  612. const f = await fixture();
  613. const raw: HostMcpServerConfig = {
  614. type: "stdio",
  615. command: variant === "windows-command" ? "cmd" : "node",
  616. args: variant === "windows-command" ? ["/c", "npx", "example-mcp"] : ["server.mjs"],
  617. ...(variant === "environment" ? { environment: { EXAMPLE_TOKEN: "fake-value" } } : {}),
  618. ...(variant === "isolation" ? { isolation: "session" } : {}),
  619. };
  620. await writeFile(
  621. join(f.workspace, ".zcode/config.json"),
  622. JSON.stringify({ mcp: { servers: { probe: raw } } }),
  623. );
  624. const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
  625. try {
  626. if (variant === "windows-command")
  627. Object.defineProperty(process, "platform", { value: "win32" });
  628. const review = (await f.authority.inspect()).probe;
  629. expect(review).toBeDefined();
  630. await f.authority.decide("probe", review!.declarationDigest, true);
  631. const dto = convertToZCodeAgentMcpServer("probe", raw, "workspace")!;
  632. const runtime = protocolMcpServersToRuntimeMcpConfig([dto])!.servers.probe!;
  633. if (variant === "environment")
  634. expect(runtime).toMatchObject({ env: { EXAMPLE_TOKEN: "fake-value" } });
  635. if (variant === "windows-command")
  636. expect(runtime).toMatchObject({ command: "npx", args: ["example-mcp"] });
  637. expect(await f.authority.allows("probe", runtime)).toBe(true);
  638. expect(
  639. await f.authority.allows("probe", { ...runtime, command: "different" } as McpServerConfig),
  640. ).toBe(false);
  641. } finally {
  642. Object.defineProperty(process, "platform", platform);
  643. }
  644. },
  645. );
  646. it("空项目 MCP map 使用 fallback;坏邻项不阻止有效声明审核", async () => {
  647. const f = await fixture();
  648. await writeFile(
  649. join(f.workspace, ".zcode/config.json"),
  650. JSON.stringify({ mcp: { servers: {} } }),
  651. );
  652. await mkdir(join(f.workspace, ".agents"));
  653. const { source: _source, ...config } = f.config;
  654. await writeFile(
  655. join(f.workspace, ".agents/mcp.json"),
  656. JSON.stringify({
  657. mcpServers: {
  658. probe: config,
  659. invalid: { command: "fake", description: "metadata not accepted by the execution schema" },
  660. },
  661. }),
  662. );
  663. const reviews = await f.authority.inspect();
  664. expect(Object.keys(reviews)).toEqual(["probe"]);
  665. await f.authority.decide("probe", reviews.probe!.declarationDigest, true);
  666. expect(await f.authority.allows("probe", f.config)).toBe(true);
  667. expect(await f.authority.allows("invalid", { type: "stdio", command: "fake" })).toBe(false);
  668. await f.save();
  669. expect(await f.authority.allows("probe", f.config)).toBe(false);
  670. });
  671. it("项目配置损坏时保留 headless 用户来源,工作区声明仍拒绝", async () => {
  672. const f = await fixture();
  673. await writeFile(
  674. f.options.userConfigPath,
  675. JSON.stringify({
  676. storage: { dir: join(f.root, "user-data") },
  677. mcp: { servers: { user_probe: { type: "stdio", command: "fake" } } },
  678. }),
  679. );
  680. await writeFile(join(f.workspace, ".zcode/config.json"), "{broken");
  681. const configResult = createConfig(f.options);
  682. const runtime = resolveAppRuntimeConfig({
  683. cliStorageRoot: join(f.root, "user-data"),
  684. configResult,
  685. options: {},
  686. mcpConfiguration: configResult.config.mcp,
  687. subagentOutputRootDir: join(f.root, "output"),
  688. workingDirectory: f.workspace,
  689. });
  690. const configured = runtime.runtimeConfig.mcp?.servers ?? {};
  691. expect(configured.user_probe?.source).toEqual({ kind: "user" });
  692. expect(await f.authority.allows("user_probe", configured.user_probe!)).toBe(true);
  693. expect(await f.authority.inspect()).toEqual({});
  694. expect(await f.authority.allows("probe", f.config)).toBe(false);
  695. });
  696. it("未信任邻项和撤销均不能阻止 MCP App 订阅释放", async () => {
  697. const f = await fixture();
  698. const subscribers = new Set<string>();
  699. const raw = {
  700. async connectServer() {
  701. return {
  702. status: "connected",
  703. transport: "stdio",
  704. toolCount: 0,
  705. updatedAt: new Date().toISOString(),
  706. };
  707. },
  708. async disconnectServer() {},
  709. async subscribeResource(request: { subscriberKey: string }) {
  710. subscribers.add(request.subscriberKey);
  711. },
  712. async unsubscribeResourcesBySubscriber(prefix: string) {
  713. let released = 0;
  714. for (const key of subscribers)
  715. if (key.startsWith(prefix)) {
  716. subscribers.delete(key);
  717. released++;
  718. }
  719. return released;
  720. },
  721. } as unknown as McpPort;
  722. const port = f.authority.guard(raw);
  723. await port.connectServer("user", { type: "stdio", command: "fake", source: { kind: "user" } });
  724. await port.subscribeResource!({
  725. serverName: "user",
  726. uri: "example://resource",
  727. subscriberKey: "session|app|first",
  728. });
  729. await port.connectServer("probe", f.config);
  730. expect(await port.unsubscribeResourcesBySubscriber!("session|app|")).toBe(1);
  731. const digest = (await f.authority.inspect()).probe!.declarationDigest;
  732. await f.authority.decide("probe", digest, true);
  733. await port.connectServer("probe", f.config);
  734. await port.subscribeResource!({
  735. serverName: "probe",
  736. uri: "example://resource",
  737. subscriberKey: "session|app|second",
  738. });
  739. await f.authority.decide("probe", digest, false);
  740. expect(await port.unsubscribeResourcesBySubscriber!("session|app|")).toBe(1);
  741. expect(subscribers.size).toBe(0);
  742. });
  743. it("会话准入提示只包含启用且未信任的声明,授权与撤销刷新但不连接", async () => {
  744. const f = await fixture();
  745. const states: Array<{ pendingCount: number; bundleDigest: string; workspaceIdentity?: string }> =
  746. [];
  747. const authority = createWorkspaceMcpTrust({
  748. ...f.options,
  749. onAdmissionChanged: async (state) => {
  750. states.push(state);
  751. },
  752. });
  753. const port = authority.guard(createMcpAdapter());
  754. try {
  755. await port.refreshWorkspaceTrustAdmission!();
  756. await port.refreshWorkspaceTrustAdmission!();
  757. expect(states).toHaveLength(1);
  758. expect(states[0]).toMatchObject({ pendingCount: 1, workspaceIdentity: f.workspace });
  759. const firstDigest = states[0]!.bundleDigest;
  760. await port.refreshWorkspaceTrustAdmission!(true);
  761. expect(states).toHaveLength(2);
  762. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  763. await port.refreshWorkspaceTrustAdmission!();
  764. expect(states.at(-1)?.pendingCount).toBe(0);
  765. await expect(access(f.marker)).rejects.toThrow();
  766. await f.save({ ...f.config, env: { EXAMPLE: "changed" } });
  767. await port.refreshWorkspaceTrustAdmission!();
  768. expect(states.at(-1)?.pendingCount).toBe(1);
  769. expect(states.at(-1)?.bundleDigest).not.toBe(firstDigest);
  770. await f.save({ ...f.config, enabled: false });
  771. await port.refreshWorkspaceTrustAdmission!();
  772. expect(states.at(-1)?.pendingCount).toBe(0);
  773. expect(JSON.stringify(states)).not.toContain("changed");
  774. await port.close();
  775. const count = states.length;
  776. await port.refreshWorkspaceTrustAdmission!();
  777. expect(states).toHaveLength(count);
  778. } finally {
  779. await port.close();
  780. }
  781. });
  782. it("准入事件发布串行,授权后的刷新不会被旧 pending 结果覆盖", async () => {
  783. const f = await fixture();
  784. const publishing = Promise.withResolvers<void>();
  785. const release = Promise.withResolvers<void>();
  786. const states: number[] = [];
  787. const port = createWorkspaceMcpTrust({
  788. ...f.options,
  789. onAdmissionChanged: async (state) => {
  790. if (states.length === 0) {
  791. publishing.resolve();
  792. await release.promise;
  793. }
  794. states.push(state.pendingCount);
  795. },
  796. }).guard(createMcpAdapter());
  797. try {
  798. const first = port.refreshWorkspaceTrustAdmission!();
  799. await publishing.promise;
  800. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  801. const second = port.refreshWorkspaceTrustAdmission!();
  802. release.resolve();
  803. await Promise.all([first, second]);
  804. expect(states).toEqual([1, 0]);
  805. } finally {
  806. release.resolve();
  807. await port.close();
  808. }
  809. });
  810. import type { ConfigResult } from "@zcode/adapters/config";
  811. import type { AgentRuntimeConfig } from "@zcode/core";
  812. import type { Logger, PluginLoadOutcome } from "@zcode/contracts";
  813. import { createAppMcpConfigurationSource } from "../src/app/dynamic-mcp-config.js";
  814. /** 会话的实际路径:动态配置源读盘 → 工作区 guard → 真实 stdio adapter。 */
  815. async function connectSessionSnapshot(f: Awaited<ReturnType<typeof fixture>>) {
  816. const configResult: ConfigResult = createConfig(f.options);
  817. const source = await createAppMcpConfigurationSource({
  818. options: { env: {}, skipUserConfig: true, pluginStorageRoot: join(f.root, "plugins") },
  819. configResult,
  820. runtimeFeatures: {} as AgentRuntimeConfig["runtimeFeatures"],
  821. pluginOutcome: { plugins: [] } as unknown as PluginLoadOutcome,
  822. builtInMcpServers: {},
  823. cliStorageRoot: join(f.root, "user-data"),
  824. workingDirectory: f.workspace,
  825. logger: { warn: vi.fn(), debug: vi.fn() } as unknown as Logger,
  826. });
  827. const port = f.authority.guard(createMcpAdapter());
  828. try {
  829. const { servers } = source.getSnapshot();
  830. const { statuses } = await port.connectConfiguredServers(servers, {
  831. workingDirectory: f.workspace,
  832. });
  833. return { servers, statuses };
  834. } finally {
  835. source.close();
  836. await port.close();
  837. }
  838. }
  839. it("会话配置源里的项目 plugins.dirs 与 .agents 回退都不能绕过工作区信任", async () => {
  840. // 修复前:动态加载器原样合并项目 plugins.dirs,也不给磁盘 server 标来源;
  841. // guard 找不到项目声明时放行,未信任工作区里的命令被执行。
  842. const f = await fixture();
  843. const { source: _source, ...raw } = f.config;
  844. const plugin = join(f.root, "evil-plugin");
  845. await mkdir(join(plugin, ".zcode-plugin"), { recursive: true });
  846. await writeFile(
  847. join(plugin, ".zcode-plugin", "plugin.json"),
  848. JSON.stringify({ name: "evil", mcpServers: { pwn: raw } }),
  849. );
  850. await writeFile(
  851. join(f.workspace, ".zcode/config.json"),
  852. JSON.stringify({ plugins: { dirs: [plugin] } }),
  853. );
  854. // zcode.json 已声明 server,guard 不把 .agents/mcp.json 计为声明;
  855. // 加载器仍因 .zcode/config.json 没有 server 读取这个回退。
  856. await writeFile(
  857. join(f.workspace, "zcode.json"),
  858. JSON.stringify({
  859. mcp: { servers: { benign: { type: "stdio", command: "fake", enabled: false } } },
  860. }),
  861. );
  862. await mkdir(join(f.workspace, ".agents"));
  863. await writeFile(
  864. join(f.workspace, ".agents/mcp.json"),
  865. JSON.stringify({ mcpServers: { probe: raw } }),
  866. );
  867. const { servers, statuses } = await connectSessionSnapshot(f);
  868. expect(servers["plugin:evil:pwn"]).toBeUndefined();
  869. expect(servers.probe?.source).toEqual({ kind: "workspace" });
  870. expect(statuses.probe?.status).toBe("untrusted");
  871. await expect(access(f.marker)).rejects.toThrow();
  872. });