mcp-official-auth-routing-runtime.ts 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import assert from "node:assert/strict";
  2. import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
  3. import { join, resolve } from "node:path";
  4. import { setTimeout as pause } from "node:timers/promises";
  5. import { createOfficialMcpTrustedOriginRegistry } from "@zcode/shared";
  6. import { createZCodeAgentService, getDataBaseDir, setDataBaseDir } from "@zcode/services/node";
  7. import {
  8. getTasksIndexDatabasePath,
  9. prepareTasksIndexStorage,
  10. } from "@zcode/services/storage-startup";
  11. import { getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  12. import {
  13. OFFICIAL_AUTH_ROUTING_PLUGIN,
  14. OFFICIAL_AUTH_ROUTING_SERVER,
  15. } from "#e2e/helpers/mcp-official-auth-routing-fixture";
  16. /** 可重复运行时场景:真实 service + CLI + MCP;只替代凭证端口并注入恶意反向协议帧。 */
  17. export async function runOfficialMcpRoutingRuntime(artifactDir: string): Promise<void> {
  18. const paths = getE2EAppDataPaths();
  19. const home = await mkdtemp(join(paths.homeDir, "mcp-auth-runtime-"));
  20. const previous = getDataBaseDir();
  21. const origin = process.env.ZCODE_E2E_OFFICIAL_AUTH_ROUTING_URL;
  22. assert(origin, "Missing controlled MCP origin");
  23. const evidenceFile = join(home, "rejected-requests.ndjson");
  24. const cliRoot = join(home, ".zcode", "cli");
  25. const workspaceA = join(home, "project-a");
  26. const workspaceB = join(home, "project-b");
  27. await Promise.all(
  28. [cliRoot, workspaceA, workspaceB].map((path) => mkdir(path, { recursive: true })),
  29. );
  30. await writeFile(evidenceFile, "");
  31. await writeFile(
  32. join(cliRoot, "config.json"),
  33. JSON.stringify({
  34. plugins: {
  35. enabled: true,
  36. dirs: [join(paths.storageRoot, "cli", "e2e-fixtures", OFFICIAL_AUTH_ROUTING_PLUGIN)],
  37. },
  38. }),
  39. );
  40. setDataBaseDir(home);
  41. let loggedIn = true;
  42. const issued: Array<{ key: string; workspace: string }> = [];
  43. const exited: number[] = [];
  44. try {
  45. await prepareTasksIndexStorage(getTasksIndexDatabasePath(), () => {});
  46. const service = createZCodeAgentService({
  47. mcpStatusIdleTimeoutMs: 1_000,
  48. commandResolver: ({ workspacePath }) => ({
  49. command: process.execPath,
  50. args: [
  51. resolve("test/e2e/fixtures/mcp/official-auth-routing-proxy.mjs"),
  52. resolve("../../apps/zcode-cli/packages/cli/dist/zcode.cjs"),
  53. evidenceFile,
  54. workspacePath.endsWith("plugin-workspace") ? "probe" : "passthrough",
  55. ],
  56. env: {
  57. HOME: home,
  58. USERPROFILE: home,
  59. ZCODE_DATA_BASE_DIR: home,
  60. ZCODE_OFFICIAL_MCP_DEV_TRUSTED_ORIGINS: origin,
  61. },
  62. }),
  63. officialMcpTrustedOrigins: createOfficialMcpTrustedOriginRegistry({
  64. devTrustedOriginsRaw: origin,
  65. resolveZCodeApiOrigin: () => "https://example.com",
  66. }),
  67. officialMcpAuthHeadersResolver: {
  68. async resolveHeaders(request) {
  69. issued.push({ key: request.mcpKey, workspace: request.workspace.workspaceKey });
  70. return loggedIn
  71. ? { ok: true, headers: { Authorization: "Bearer mock-token" } }
  72. : { ok: false, reason: "official_auth_unavailable" };
  73. },
  74. },
  75. processLifecycleReporter: {
  76. onSpawn() {},
  77. onExit(event) {
  78. if (event.lane === "mcp-status") exited.push(event.pid);
  79. },
  80. },
  81. });
  82. try {
  83. const connected = async (workspacePath: string) => {
  84. const result = await service.listMcpServerStatuses({ workspacePath });
  85. assert.equal(result.statuses[OFFICIAL_AUTH_ROUTING_SERVER]?.status, "connected");
  86. };
  87. // 尚无聊天进程时,管理进程已能反向取身份。
  88. await connected(workspaceA);
  89. await assert.rejects(service.getWorkspaceRuntimeIdentity({ workspacePath: workspaceA }));
  90. // 同一项目已有真实聊天 CLI 后,控制面仍独立工作。
  91. await service.listSessions({ workspacePath: workspaceA });
  92. const chatBefore = await service.getWorkspaceRuntimeIdentity({ workspacePath: workspaceA });
  93. await Promise.all([connected(workspaceB), connected(workspaceA)]);
  94. assert.deepEqual(
  95. await service.getWorkspaceRuntimeIdentity({ workspacePath: workspaceA }),
  96. chatBefore,
  97. );
  98. assert(issued.some((entry) => entry.workspace === workspaceA));
  99. assert(issued.some((entry) => entry.workspace === workspaceB));
  100. const waitForIdleExit = async () => {
  101. const previousExits = exited.length;
  102. const deadline = Date.now() + 10_000;
  103. while (exited.length === previousExits && Date.now() < deadline) await pause(25);
  104. assert(exited.length > previousExits, "MCP status lane did not exit after idle timeout");
  105. };
  106. await waitForIdleExit();
  107. await connected(workspaceA);
  108. assert.deepEqual(
  109. await service.getWorkspaceRuntimeIdentity({ workspacePath: workspaceA }),
  110. chatBefore,
  111. );
  112. loggedIn = false;
  113. // 等待当前控制面按既有 idle 策略退出,下一次刷新必须在新进程中重新取身份。
  114. await waitForIdleExit();
  115. const signedOut = await service.listMcpServerStatuses({ workspacePath: workspaceA });
  116. await writeFile(
  117. join(artifactDir, "OMCP-SETTINGS-signout.json"),
  118. JSON.stringify(signedOut, null, 2),
  119. );
  120. assert.equal(
  121. signedOut.statuses[OFFICIAL_AUTH_ROUTING_SERVER]?.failureKind,
  122. "not_authenticated",
  123. );
  124. const probes = (await readFile(evidenceFile, "utf8"))
  125. .trim()
  126. .split("\n")
  127. .map((line) => JSON.parse(line));
  128. for (const kind of ["unregistered", "identity", "consumer", "malformed"]) {
  129. assert(
  130. probes.some((probe) => probe.kind === kind && probe.code === -32602),
  131. kind,
  132. );
  133. }
  134. assert(
  135. probes.some(
  136. (probe) => probe.kind === "origin" && probe.reason === "official_mcp_origin_untrusted",
  137. ),
  138. );
  139. assert(
  140. !issued.some((entry) => entry.key.startsWith("probe-")),
  141. "Rejected request read credentials",
  142. );
  143. await writeFile(
  144. join(artifactDir, "OMCP-SETTINGS-02-03-runtime.json"),
  145. JSON.stringify({ issued, probes, exited }, null, 2),
  146. );
  147. } finally {
  148. await service.disposeAllAndWait();
  149. }
  150. } finally {
  151. setDataBaseDir(previous);
  152. }
  153. }