workspace-mcp-trust.test.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  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. const result = resolveAppRuntimeConfig({
  32. cliStorageRoot: join(root, "storage"),
  33. configResult: createConfig({ workingDirectory: root, skipUserConfig: true, env: {} }),
  34. options: {},
  35. subagentOutputRootDir: join(root, "output"),
  36. workingDirectory: root,
  37. });
  38. expect(result.untrustedProjectMcpServers.has("probe")).toBe(true);
  39. });
  40. import { access, readFile } from "node:fs/promises";
  41. import { createServer } from "node:http";
  42. import { createMcpAdapter, createMcpAdapterConnectionPool } from "@zcode/adapters/mcp";
  43. import type { McpServerConfig } from "@zcode/contracts";
  44. import { createWorkspaceMcpTrust } from "../src/workspace-mcp-trust/index.js";
  45. async function fixture(exitAfterCall = false) {
  46. const root = await mkdtemp(join(tmpdir(), "workspace-mcp-runtime-"));
  47. roots.push(root);
  48. const workspace = join(root, "workspace");
  49. const userConfigPath = join(root, "user.json");
  50. const marker = join(root, "started");
  51. const script = join(root, "server.mjs");
  52. await mkdir(join(workspace, ".zcode"), { recursive: true });
  53. await writeFile(userConfigPath, JSON.stringify({ storage: { dir: join(root, "user-data") } }));
  54. await writeFile(
  55. script,
  56. `import {writeFile, appendFile} from 'node:fs/promises';
  57. import {createInterface} from 'node:readline';
  58. await writeFile(process.argv[2], 'started');
  59. for await (const line of createInterface({input:process.stdin})) {
  60. const r=JSON.parse(line); if(r.id===undefined) continue;
  61. const result=r.method==='initialize'?{protocolVersion:'2025-11-25',capabilities:{tools:{}},serverInfo:{name:'local-test',version:'1'}}:
  62. r.method==='tools/list'?{tools:[{name:'probe',description:'local probe',inputSchema:{type:'object'}}]}:
  63. r.method==='tools/call'?{content:[{type:'text',text:'ok'}]}:{};
  64. if(r.method==='tools/call') await appendFile(process.argv[2], '\\ncall');
  65. process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:r.id,result})+'\\n', () => {
  66. if (${exitAfterCall} && r.method==='tools/call') process.exit(0);
  67. });
  68. }`,
  69. );
  70. const config: McpServerConfig = {
  71. type: "stdio",
  72. command: process.execPath,
  73. args: [script, marker],
  74. protocolVersion: "legacy",
  75. source: { kind: "workspace" },
  76. };
  77. async function save(value: McpServerConfig = config) {
  78. const { source: _source, ...raw } = value;
  79. await writeFile(
  80. join(workspace, ".zcode/config.json"),
  81. JSON.stringify({ mcp: { servers: { probe: raw } } }),
  82. );
  83. }
  84. await save();
  85. const options = { workingDirectory: workspace, userConfigPath, env: {} };
  86. return {
  87. root,
  88. workspace,
  89. marker,
  90. config,
  91. options,
  92. save,
  93. authority: createWorkspaceMcpTrust(options),
  94. };
  95. }
  96. it("真实 stdio:未信任零进程,授权后握手,撤销在下次连接准入生效", async () => {
  97. const f = await fixture();
  98. let pendingCount = 0;
  99. f.authority = createWorkspaceMcpTrust({
  100. ...f.options,
  101. onAdmissionChanged: async (state) => {
  102. pendingCount = state.pendingCount;
  103. },
  104. });
  105. const port = f.authority.guard(createMcpAdapter());
  106. try {
  107. expect((await port.connectServer("probe", f.config)).status).toBe("untrusted");
  108. await expect(access(f.marker)).rejects.toThrow();
  109. const review = (await f.authority.inspect()).probe!;
  110. await f.authority.decide("probe", review.declarationDigest, true);
  111. expect((await port.connectServer("probe", f.config)).status).toBe("connected");
  112. expect(await readFile(f.marker, "utf8")).toBe("started");
  113. expect(await createWorkspaceMcpTrust(f.options).allows("probe", f.config)).toBe(true);
  114. await port.callTool({ serverName: "probe", toolName: "probe", arguments: {} });
  115. await f.authority.decide("probe", review.declarationDigest, false);
  116. await port.refreshWorkspaceTrustAdmission!();
  117. expect(pendingCount).toBe(1);
  118. await port.callTool({ serverName: "probe", toolName: "probe" });
  119. expect(await port.listTools()).toHaveLength(1);
  120. expect((await port.connectServer("probe", f.config)).status).toBe("untrusted");
  121. await expect(port.callTool({ serverName: "probe", toolName: "probe" })).rejects.toThrow(
  122. "workspace_mcp_pending_trust",
  123. );
  124. expect(await port.listTools()).toEqual([]);
  125. expect(await readFile(f.marker, "utf8")).toBe("started\ncall\ncall");
  126. } finally {
  127. await port.close();
  128. }
  129. });
  130. it("连接内工具调用、状态、列表与 ping 不重复读取授权,断开后拒绝调用", async () => {
  131. const f = await fixture();
  132. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  133. const check = vi.spyOn(f.authority, "allows");
  134. const port = f.authority.guard(createMcpAdapter());
  135. try {
  136. await port.connectServer("probe", f.config);
  137. check.mockClear();
  138. for (let i = 0; i < 3; i++) {
  139. await port.callTool({ serverName: "probe", toolName: "probe" });
  140. expect((await port.status()).probe?.status).toBe("connected");
  141. expect(await port.listTools()).toHaveLength(1);
  142. expect(await port.pingServer!("probe")).toBe(true);
  143. }
  144. expect(check).not.toHaveBeenCalled();
  145. await port.disconnectServer("probe");
  146. await expect(port.callTool({ serverName: "probe", toolName: "probe" })).rejects.toThrow(
  147. "workspace_mcp_pending_trust",
  148. );
  149. expect(await readFile(f.marker, "utf8")).toBe("started\ncall\ncall\ncall");
  150. } finally {
  151. check.mockRestore();
  152. await port.close();
  153. }
  154. });
  155. it("真实断线自动重连沿用会话授权,撤销后新会话准入拒绝", async () => {
  156. const f = await fixture(true);
  157. const review = (await f.authority.inspect()).probe!;
  158. await f.authority.decide("probe", review.declarationDigest, true);
  159. const raw = createMcpAdapter();
  160. const connects = vi.spyOn(raw, "connectServer");
  161. const check = vi.spyOn(f.authority, "allows");
  162. const port = f.authority.guard(raw);
  163. const restarted = createWorkspaceMcpTrust(f.options).guard(createMcpAdapter());
  164. try {
  165. await port.connectServer("probe", f.config);
  166. check.mockClear();
  167. await port.callTool({ serverName: "probe", toolName: "probe" });
  168. await vi.waitFor(async () => {
  169. expect((await port.status()).probe?.status).toBe("disconnected");
  170. });
  171. await f.authority.decide("probe", review.declarationDigest, false);
  172. await expect(port.callTool({ serverName: "probe", toolName: "probe" })).resolves.toMatchObject({
  173. content: [{ type: "text", text: "ok" }],
  174. });
  175. expect(connects).toHaveBeenCalledTimes(2);
  176. expect(check).not.toHaveBeenCalled();
  177. expect((await restarted.connectServer("probe", f.config)).status).toBe("untrusted");
  178. await expect(restarted.callTool({ serverName: "probe", toolName: "probe" })).rejects.toThrow(
  179. "workspace_mcp_pending_trust",
  180. );
  181. } finally {
  182. connects.mockRestore();
  183. check.mockRestore();
  184. await port.close();
  185. await restarted.close();
  186. }
  187. });
  188. it.each(["changed", "removed", "disabled", "corrupt"] as const)(
  189. "连接后 %s 不影响已批准连接,下次连接准入拒绝",
  190. async (change) => {
  191. const f = await fixture();
  192. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  193. const port = f.authority.guard(createMcpAdapter());
  194. try {
  195. await port.connectServer("probe", f.config);
  196. if (change === "changed") await f.save({ ...f.config, env: { VERSION: "2" } });
  197. if (change === "disabled") await f.save({ ...f.config, enabled: false });
  198. if (change === "removed") await writeFile(join(f.workspace, ".zcode/config.json"), "{}");
  199. if (change === "corrupt")
  200. await writeFile(join(f.root, "user-data/security/workspace-mcp-trust-v1.json"), "invalid");
  201. await port.callTool({ serverName: "probe", toolName: "probe" });
  202. expect((await port.connectServer("probe", f.config)).status).toBe("untrusted");
  203. await expect(port.callTool({ serverName: "probe", toolName: "probe" })).rejects.toThrow(
  204. "workspace_mcp_pending_trust",
  205. );
  206. expect(await readFile(f.marker, "utf8")).toBe("started\ncall");
  207. } finally {
  208. await port.close();
  209. }
  210. },
  211. );
  212. it("声明变化拒绝旧审核与旧连接配置;enabled 不扩大或清除授权", async () => {
  213. const f = await fixture();
  214. const old = (await f.authority.inspect()).probe!;
  215. await f.authority.decide("probe", old.declarationDigest, true);
  216. await f.save({ ...f.config, enabled: false });
  217. expect((await f.authority.inspect()).probe?.declarationDigest).toBe(old.declarationDigest);
  218. expect(await f.authority.allows("probe", f.config)).toBe(false);
  219. await f.save({ ...f.config, env: { VERSION: "2" } });
  220. expect(await f.authority.allows("probe", f.config)).toBe(false);
  221. await expect(f.authority.decide("probe", old.declarationDigest, true)).rejects.toThrow(
  222. "workspace_mcp_declaration_changed",
  223. );
  224. await writeFile(join(f.workspace, ".zcode/config.json"), "{}");
  225. expect(await f.authority.allows("probe", f.config)).toBe(false);
  226. });
  227. it("HTTP/SSE 未信任不发出任何请求;secret 不进入审核显示或存储", async () => {
  228. const f = await fixture();
  229. let requests = 0;
  230. const server = createServer((_request, response) => {
  231. requests++;
  232. response.writeHead(500).end();
  233. });
  234. await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
  235. const address = server.address();
  236. if (!address || typeof address === "string") throw new Error("no address");
  237. const port = f.authority.guard(createMcpAdapter());
  238. try {
  239. for (const type of ["http", "sse"] as const) {
  240. const config: McpServerConfig = {
  241. type,
  242. url: `http://127.0.0.1:${address.port}/mcp?token=secret-query`,
  243. headers: { Authorization: "secret-header" },
  244. source: { kind: "workspace" },
  245. };
  246. await f.save(config);
  247. expect((await port.connectServer("probe", config)).status).toBe("untrusted");
  248. const review = (await f.authority.inspect()).probe!;
  249. expect(review.display).not.toContain("secret");
  250. await f.authority.decide("probe", review.declarationDigest, true);
  251. const content = await readFile(
  252. join(f.root, "user-data/security/workspace-mcp-trust-v1.json"),
  253. "utf8",
  254. );
  255. expect(content).not.toContain("secret");
  256. }
  257. expect(requests).toBe(0);
  258. } finally {
  259. await port.close();
  260. await new Promise<void>((done) => server.close(() => done()));
  261. }
  262. });
  263. it("同名 server 不跨 workspaceIdentity 继承授权,包括连接池 lease 复用", async () => {
  264. const f = await fixture();
  265. const other = createWorkspaceMcpTrust({ ...f.options, workspaceIdentity: "remote:other" });
  266. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  267. const pool = createMcpAdapterConnectionPool({ idleGraceMs: 0 });
  268. const first = f.authority.guard(pool.acquireLease());
  269. const second = other.guard(pool.acquireLease());
  270. try {
  271. expect((await first.connectServer("probe", f.config)).status).toBe("connected");
  272. expect((await second.connectServer("probe", f.config)).status).toBe("untrusted");
  273. expect(await second.listTools()).toEqual([]);
  274. } finally {
  275. await first.close();
  276. await second.close();
  277. await pool.close();
  278. }
  279. });
  280. it("损坏授权文件拒绝执行与授权;项目 storage.dir 不改变用户域记录位置", async () => {
  281. const f = await fixture();
  282. const review = (await f.authority.inspect()).probe!;
  283. await f.authority.decide("probe", review.declarationDigest, true);
  284. await writeFile(
  285. join(f.root, "user-data/security/workspace-mcp-trust-v1.json"),
  286. '{"schemaVersion":99,"records":[]}',
  287. );
  288. expect(await f.authority.allows("probe", f.config)).toBe(false);
  289. await expect(f.authority.decide("probe", review.declarationDigest, true)).rejects.toThrow();
  290. });
  291. it(".agents 工作区 fallback 也必须单独审核;用户和插件来源不被误拦截", async () => {
  292. const f = await fixture();
  293. await writeFile(join(f.workspace, ".zcode/config.json"), "{}");
  294. await mkdir(join(f.workspace, ".agents"));
  295. const { source: _source, ...raw } = f.config;
  296. await writeFile(
  297. join(f.workspace, ".agents/mcp.json"),
  298. JSON.stringify({ mcpServers: { probe: raw } }),
  299. );
  300. expect(await f.authority.allows("probe", f.config)).toBe(false);
  301. expect((await f.authority.inspect()).probe?.sourcePaths).toEqual([
  302. join(f.workspace, ".agents/mcp.json"),
  303. ]);
  304. for (const kind of ["user", "plugin", "builtin"] as const) {
  305. expect(await f.authority.allows("probe", { ...f.config, source: { kind } })).toBe(true);
  306. }
  307. });
  308. it("连接使用审核时的私有配置副本,调用方修改对象不能改变实际 spawn", async () => {
  309. const f = await fixture();
  310. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  311. const port = f.authority.guard(createMcpAdapter());
  312. try {
  313. const connecting = port.connectServer("probe", f.config);
  314. if (f.config.type === "stdio") f.config.args = ["-e", "throw new Error('mutated')"];
  315. expect((await connecting).status).toBe("connected");
  316. expect(await readFile(f.marker, "utf8")).toBe("started");
  317. } finally {
  318. await port.close();
  319. }
  320. });
  321. it("并发进程批准不同 workspace 时不丢失记录", async () => {
  322. const f = await fixture();
  323. const { execFile } = await import("node:child_process");
  324. const { promisify } = await import("node:util");
  325. const run = promisify(execFile);
  326. const moduleUrl = new URL("../src/workspace-mcp-trust/index.ts", import.meta.url).href;
  327. const script = `const { createWorkspaceMcpTrust } = await import(process.argv[1]);
  328. const authority = createWorkspaceMcpTrust(JSON.parse(process.argv[2]));
  329. await authority.decide('probe', (await authority.inspect()).probe.declarationDigest, true);`;
  330. await Promise.all(
  331. ["first", "second"].map((workspaceIdentity) =>
  332. run(process.execPath, [
  333. "--import",
  334. "tsx",
  335. "--input-type=module",
  336. "-e",
  337. script,
  338. moduleUrl,
  339. JSON.stringify({ ...f.options, workspaceIdentity }),
  340. ]),
  341. ),
  342. );
  343. const store = JSON.parse(
  344. await readFile(join(f.root, "user-data/security/workspace-mcp-trust-v1.json"), "utf8"),
  345. );
  346. expect(
  347. store.records.map((record: { workspaceIdentity: string }) => record.workspaceIdentity).sort(),
  348. ).toEqual(["first", "second"]);
  349. });
  350. it("stdio 审核不显示以命令参数传入的常见密钥", async () => {
  351. const f = await fixture();
  352. if (f.config.type !== "stdio") throw new Error("expected stdio");
  353. await f.save({ ...f.config, args: [...f.config.args!, "--token", "secret-command-argument"] });
  354. expect((await f.authority.inspect()).probe!.display).not.toContain("secret-command-argument");
  355. });
  356. it("并发连接 mutation 串行收敛,避免新声明映射到旧连接", async () => {
  357. const f = await fixture();
  358. f.authority.allows = async () => true;
  359. let release!: () => void;
  360. const barrier = new Promise<void>((resolve) => {
  361. release = resolve;
  362. });
  363. let active = 0;
  364. let peak = 0;
  365. const raw = createMcpAdapter();
  366. raw.connectServer = async (_name, config) => {
  367. active++;
  368. peak = Math.max(peak, active);
  369. await barrier;
  370. active--;
  371. return {
  372. status: "connected",
  373. transport: config.type,
  374. toolCount: 0,
  375. updatedAt: new Date().toISOString(),
  376. };
  377. };
  378. const port = f.authority.guard(raw);
  379. const first = port.connectServer("probe", f.config);
  380. const second = port.connectServer("probe", f.config);
  381. await new Promise<void>((done) => setImmediate(done));
  382. release();
  383. await Promise.all([first, second]);
  384. expect(peak).toBe(1);
  385. await port.close();
  386. });
  387. it.each(["single", "configured"])("%s 准入未完成时,工具列表只查内存且默认拒绝", async (mode) => {
  388. const f = await fixture();
  389. let release!: () => void;
  390. const barrier = new Promise<void>((resolve) => {
  391. release = resolve;
  392. });
  393. const check = vi.spyOn(f.authority, "allows").mockImplementation(async () => {
  394. await barrier;
  395. return false;
  396. });
  397. const raw = createMcpAdapter();
  398. raw.listTools = async () => [{ serverName: "probe", toolName: "probe", inputSchema: {} }];
  399. const port = f.authority.guard(raw);
  400. const connecting =
  401. mode === "single"
  402. ? port.connectServer("probe", f.config)
  403. : port.connectConfiguredServers({ probe: f.config });
  404. try {
  405. await new Promise<void>((done) => setImmediate(done));
  406. const listing = port.listTools();
  407. await new Promise<void>((done) => setImmediate(done));
  408. release();
  409. expect(await listing).toEqual([]);
  410. expect(check).toHaveBeenCalledTimes(1);
  411. await connecting;
  412. } finally {
  413. release();
  414. await connecting;
  415. check.mockRestore();
  416. await port.close();
  417. }
  418. });
  419. it.each(["single", "configured"])("关闭 lease 后,迟到的 %s 准入结果不能启动连接", async (mode) => {
  420. const f = await fixture();
  421. let resolveAllowed!: (value: boolean) => void;
  422. f.authority.allows = () =>
  423. new Promise<boolean>((resolve) => {
  424. resolveAllowed = resolve;
  425. });
  426. const raw = createMcpAdapter();
  427. let connects = 0;
  428. raw.connectServer = async (_name, config) => {
  429. connects++;
  430. return {
  431. status: "connected",
  432. transport: config.type,
  433. toolCount: 0,
  434. updatedAt: new Date().toISOString(),
  435. };
  436. };
  437. raw.connectConfiguredServers = async () => {
  438. connects++;
  439. return { statuses: {}, tools: [] };
  440. };
  441. const port = f.authority.guard(raw);
  442. const pending = (
  443. mode === "single"
  444. ? port.connectServer("probe", f.config)
  445. : port.connectConfiguredServers({ probe: f.config })
  446. ).catch(() => undefined);
  447. await new Promise<void>((done) => setImmediate(done));
  448. resolveAllowed(true);
  449. queueMicrotask(() => {
  450. void port.close();
  451. });
  452. await pending;
  453. expect(connects).toBe(0);
  454. });
  455. it("HTTP URL、header 与 OAuth 凭据的变化都使原授权失效", async () => {
  456. const f = await fixture();
  457. const original: McpServerConfig = {
  458. type: "http",
  459. url: "https://mcp.example.test/one",
  460. headers: { Authorization: "first" },
  461. oauth: { type: "client_credentials", clientId: "client", clientSecret: "first" },
  462. source: { kind: "workspace" },
  463. };
  464. await f.save(original);
  465. const review = (await f.authority.inspect()).probe!;
  466. await f.authority.decide("probe", review.declarationDigest, true);
  467. for (const config of [
  468. { ...original, url: "https://mcp.example.test/two" },
  469. { ...original, headers: { Authorization: "second" } },
  470. {
  471. ...original,
  472. oauth: { type: "client_credentials" as const, clientId: "client", clientSecret: "second" },
  473. },
  474. ]) {
  475. await f.save(config);
  476. expect((await f.authority.inspect()).probe!.declarationDigest).not.toBe(
  477. review.declarationDigest,
  478. );
  479. expect(await f.authority.allows("probe", config)).toBe(false);
  480. expect(await f.authority.allows("probe", original)).toBe(false);
  481. }
  482. });
  483. it.each(["environment", "windows-command", "isolation"])(
  484. "审核与 Host DTO 对 %s 使用相同执行配置,真实字段变化仍拒绝",
  485. async (variant) => {
  486. const f = await fixture();
  487. const raw: HostMcpServerConfig = {
  488. type: "stdio",
  489. command: variant === "windows-command" ? "cmd" : "node",
  490. args: variant === "windows-command" ? ["/c", "npx", "example-mcp"] : ["server.mjs"],
  491. ...(variant === "environment" ? { environment: { EXAMPLE_TOKEN: "fake-value" } } : {}),
  492. ...(variant === "isolation" ? { isolation: "session" } : {}),
  493. };
  494. await writeFile(
  495. join(f.workspace, ".zcode/config.json"),
  496. JSON.stringify({ mcp: { servers: { probe: raw } } }),
  497. );
  498. const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
  499. try {
  500. if (variant === "windows-command")
  501. Object.defineProperty(process, "platform", { value: "win32" });
  502. const review = (await f.authority.inspect()).probe;
  503. expect(review).toBeDefined();
  504. await f.authority.decide("probe", review!.declarationDigest, true);
  505. const dto = convertToZCodeAgentMcpServer("probe", raw, "workspace")!;
  506. const runtime = protocolMcpServersToRuntimeMcpConfig([dto])!.servers.probe!;
  507. if (variant === "environment")
  508. expect(runtime).toMatchObject({ env: { EXAMPLE_TOKEN: "fake-value" } });
  509. if (variant === "windows-command")
  510. expect(runtime).toMatchObject({ command: "npx", args: ["example-mcp"] });
  511. expect(await f.authority.allows("probe", runtime)).toBe(true);
  512. expect(
  513. await f.authority.allows("probe", { ...runtime, command: "different" } as McpServerConfig),
  514. ).toBe(false);
  515. } finally {
  516. Object.defineProperty(process, "platform", platform);
  517. }
  518. },
  519. );
  520. it("空项目 MCP map 使用 fallback;坏邻项不阻止有效声明审核", async () => {
  521. const f = await fixture();
  522. await writeFile(
  523. join(f.workspace, ".zcode/config.json"),
  524. JSON.stringify({ mcp: { servers: {} } }),
  525. );
  526. await mkdir(join(f.workspace, ".agents"));
  527. const { source: _source, ...config } = f.config;
  528. await writeFile(
  529. join(f.workspace, ".agents/mcp.json"),
  530. JSON.stringify({
  531. mcpServers: {
  532. probe: config,
  533. invalid: { command: "fake", description: "metadata not accepted by the execution schema" },
  534. },
  535. }),
  536. );
  537. const reviews = await f.authority.inspect();
  538. expect(Object.keys(reviews)).toEqual(["probe"]);
  539. await f.authority.decide("probe", reviews.probe!.declarationDigest, true);
  540. expect(await f.authority.allows("probe", f.config)).toBe(true);
  541. expect(await f.authority.allows("invalid", { type: "stdio", command: "fake" })).toBe(false);
  542. await f.save();
  543. expect(await f.authority.allows("probe", f.config)).toBe(false);
  544. });
  545. it("项目配置损坏时保留 headless 用户来源,工作区声明仍拒绝", async () => {
  546. const f = await fixture();
  547. await writeFile(
  548. f.options.userConfigPath,
  549. JSON.stringify({
  550. storage: { dir: join(f.root, "user-data") },
  551. mcp: { servers: { user_probe: { type: "stdio", command: "fake" } } },
  552. }),
  553. );
  554. await writeFile(join(f.workspace, ".zcode/config.json"), "{broken");
  555. const runtime = resolveAppRuntimeConfig({
  556. cliStorageRoot: join(f.root, "user-data"),
  557. configResult: createConfig(f.options),
  558. options: {},
  559. subagentOutputRootDir: join(f.root, "output"),
  560. workingDirectory: f.workspace,
  561. });
  562. expect(runtime.configuredMcpServers.user_probe?.source).toEqual({ kind: "user" });
  563. expect(await f.authority.allows("user_probe", runtime.configuredMcpServers.user_probe!)).toBe(
  564. true,
  565. );
  566. expect(await f.authority.inspect()).toEqual({});
  567. expect(await f.authority.allows("probe", f.config)).toBe(false);
  568. });
  569. it("未信任邻项和撤销均不能阻止 MCP App 订阅释放", async () => {
  570. const f = await fixture();
  571. const subscribers = new Set<string>();
  572. const raw = {
  573. async connectServer() {
  574. return {
  575. status: "connected",
  576. transport: "stdio",
  577. toolCount: 0,
  578. updatedAt: new Date().toISOString(),
  579. };
  580. },
  581. async disconnectServer() {},
  582. async subscribeResource(request: { subscriberKey: string }) {
  583. subscribers.add(request.subscriberKey);
  584. },
  585. async unsubscribeResourcesBySubscriber(prefix: string) {
  586. let released = 0;
  587. for (const key of subscribers)
  588. if (key.startsWith(prefix)) {
  589. subscribers.delete(key);
  590. released++;
  591. }
  592. return released;
  593. },
  594. } as unknown as McpPort;
  595. const port = f.authority.guard(raw);
  596. await port.connectServer("user", { type: "stdio", command: "fake", source: { kind: "user" } });
  597. await port.subscribeResource!({
  598. serverName: "user",
  599. uri: "example://resource",
  600. subscriberKey: "session|app|first",
  601. });
  602. await port.connectServer("probe", f.config);
  603. expect(await port.unsubscribeResourcesBySubscriber!("session|app|")).toBe(1);
  604. const digest = (await f.authority.inspect()).probe!.declarationDigest;
  605. await f.authority.decide("probe", digest, true);
  606. await port.connectServer("probe", f.config);
  607. await port.subscribeResource!({
  608. serverName: "probe",
  609. uri: "example://resource",
  610. subscriberKey: "session|app|second",
  611. });
  612. await f.authority.decide("probe", digest, false);
  613. expect(await port.unsubscribeResourcesBySubscriber!("session|app|")).toBe(1);
  614. expect(subscribers.size).toBe(0);
  615. });
  616. it("会话准入提示只包含启用且未信任的声明,授权与撤销刷新但不连接", async () => {
  617. const f = await fixture();
  618. const states: Array<{ pendingCount: number; bundleDigest: string; workspaceIdentity?: string }> =
  619. [];
  620. const authority = createWorkspaceMcpTrust({
  621. ...f.options,
  622. onAdmissionChanged: async (state) => {
  623. states.push(state);
  624. },
  625. });
  626. const port = authority.guard(createMcpAdapter());
  627. try {
  628. await port.refreshWorkspaceTrustAdmission!();
  629. await port.refreshWorkspaceTrustAdmission!();
  630. expect(states).toHaveLength(1);
  631. expect(states[0]).toMatchObject({ pendingCount: 1, workspaceIdentity: f.workspace });
  632. const firstDigest = states[0]!.bundleDigest;
  633. await port.refreshWorkspaceTrustAdmission!(true);
  634. expect(states).toHaveLength(2);
  635. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  636. await port.refreshWorkspaceTrustAdmission!();
  637. expect(states.at(-1)?.pendingCount).toBe(0);
  638. await expect(access(f.marker)).rejects.toThrow();
  639. await f.save({ ...f.config, env: { EXAMPLE: "changed" } });
  640. await port.refreshWorkspaceTrustAdmission!();
  641. expect(states.at(-1)?.pendingCount).toBe(1);
  642. expect(states.at(-1)?.bundleDigest).not.toBe(firstDigest);
  643. await f.save({ ...f.config, enabled: false });
  644. await port.refreshWorkspaceTrustAdmission!();
  645. expect(states.at(-1)?.pendingCount).toBe(0);
  646. expect(JSON.stringify(states)).not.toContain("changed");
  647. await port.close();
  648. const count = states.length;
  649. await port.refreshWorkspaceTrustAdmission!();
  650. expect(states).toHaveLength(count);
  651. } finally {
  652. await port.close();
  653. }
  654. });
  655. it("准入事件发布串行,授权后的刷新不会被旧 pending 结果覆盖", async () => {
  656. const f = await fixture();
  657. const publishing = Promise.withResolvers<void>();
  658. const release = Promise.withResolvers<void>();
  659. const states: number[] = [];
  660. const port = createWorkspaceMcpTrust({
  661. ...f.options,
  662. onAdmissionChanged: async (state) => {
  663. if (states.length === 0) {
  664. publishing.resolve();
  665. await release.promise;
  666. }
  667. states.push(state.pendingCount);
  668. },
  669. }).guard(createMcpAdapter());
  670. try {
  671. const first = port.refreshWorkspaceTrustAdmission!();
  672. await publishing.promise;
  673. await f.authority.decide("probe", (await f.authority.inspect()).probe!.declarationDigest, true);
  674. const second = port.refreshWorkspaceTrustAdmission!();
  675. release.resolve();
  676. await Promise.all([first, second]);
  677. expect(states).toEqual([1, 0]);
  678. } finally {
  679. release.resolve();
  680. await port.close();
  681. }
  682. });