official-mcp-auth-port.test.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. /* CR-01 —— 官方 MCP 身份头端口构造协议参数的定向测试(spec §7.1 / §7.2)。
  2. *
  3. * 覆盖缺口说明:officialMcpAuthRemoteRouting.test.ts 验证的是 service 层**收到** workspace
  4. * 之后的响应路由,不覆盖本端口把 OfficialMcpAuthHeadersPort 入参转成协议参数这一段。
  5. * 同路径、不同 identity 的远端 workspace 在这里如果丢掉 identity,审计上下文就无法区分。
  6. */
  7. import { describe, expect, it, vi } from "vitest";
  8. import { zcodeProtocolMethods } from "@zcode/shared";
  9. import {
  10. createOfficialMcpAuthHeadersPort,
  11. type OfficialMcpAuthRequestContext,
  12. } from "../src/zcode-protocol/official-mcp-auth-port.js";
  13. const OK = { headers: { Authorization: "Bearer jwt" }, ok: true as const };
  14. /** 与 zcode-protocol-entrypoint.ts 相同的构造口径:workspaceKey = 会话 key || identity?.trim() || path。 */
  15. function entrypointResolveWorkspace(fallbackCwd: string) {
  16. return ({
  17. workspaceIdentity,
  18. workspacePath,
  19. workspaceKey,
  20. }: {
  21. workspaceIdentity?: string;
  22. workspacePath?: string;
  23. workspaceKey?: string;
  24. }) => {
  25. const path = workspacePath ?? fallbackCwd;
  26. if (!path) return undefined;
  27. const identity = workspaceIdentity?.trim();
  28. return {
  29. ...(identity ? { workspaceIdentity: identity } : {}),
  30. workspaceKey: workspaceKey || identity || path,
  31. workspacePath: path,
  32. };
  33. };
  34. }
  35. function createHarness(
  36. options: { resolveWorkspace?: ReturnType<typeof entrypointResolveWorkspace> } = {},
  37. ) {
  38. const requestClient = vi.fn(async () => OK);
  39. const context = { requestClient } as unknown as OfficialMcpAuthRequestContext;
  40. const port = createOfficialMcpAuthHeadersPort({
  41. resolveContext: () => context,
  42. resolveWorkspace: options.resolveWorkspace ?? entrypointResolveWorkspace("/fallback"),
  43. });
  44. const sentWorkspace = (call: number) =>
  45. (requestClient.mock.calls[call]?.[1] as { workspace: Record<string, string> }).workspace;
  46. return { port, requestClient, sentWorkspace };
  47. }
  48. const BASE_REQUEST = {
  49. mcpKey: "image-search",
  50. pluginId: "zcode-tools@zcode-plugins-official",
  51. targetOrigin: "https://mcp.zcode.example",
  52. };
  53. describe("official mcp auth headers port", () => {
  54. it("CR-01: keeps same-path workspaces distinguishable by workspaceIdentity", async () => {
  55. const { port, sentWorkspace } = createHarness();
  56. await port.resolveHeaders({
  57. ...BASE_REQUEST,
  58. workspaceIdentity: "remote:wsl:ubuntu:/workspace/app",
  59. workspacePath: "/workspace/app",
  60. });
  61. await port.resolveHeaders({ ...BASE_REQUEST, workspacePath: "/workspace/app" });
  62. // 同 workspacePath,但 identity 不同 -> 协议参数必须可区分
  63. expect(sentWorkspace(0)).toEqual({
  64. workspaceIdentity: "remote:wsl:ubuntu:/workspace/app",
  65. workspaceKey: "remote:wsl:ubuntu:/workspace/app",
  66. workspacePath: "/workspace/app",
  67. });
  68. expect(sentWorkspace(1)).toEqual({
  69. workspaceKey: "/workspace/app",
  70. workspacePath: "/workspace/app",
  71. });
  72. });
  73. it("routes a managed worktree session by its workspace key, not its working directory", async () => {
  74. const { port, sentWorkspace } = createHarness();
  75. await port.resolveHeaders({
  76. ...BASE_REQUEST,
  77. workspacePath: "/data/.zcode/worktrees/3f2a/repo",
  78. workspaceKey: "/projects/repo",
  79. });
  80. // Host 按 workspaceKey 路由;按工作目录重算会被拒为"未通过工作区路由"(§9.3)。
  81. expect(sentWorkspace(0)).toEqual({
  82. workspaceKey: "/projects/repo",
  83. workspacePath: "/data/.zcode/worktrees/3f2a/repo",
  84. });
  85. });
  86. it("sends the declared plugin identity and target origin unchanged", async () => {
  87. const { port, requestClient } = createHarness();
  88. await port.resolveHeaders({ ...BASE_REQUEST, workspacePath: "/repo" });
  89. expect(requestClient).toHaveBeenCalledWith(
  90. zcodeProtocolMethods.interactionRequestOfficialMcpAuthHeaders,
  91. expect.objectContaining({
  92. mcpKey: "image-search",
  93. pluginId: "zcode-tools@zcode-plugins-official",
  94. targetOrigin: "https://mcp.zcode.example",
  95. }),
  96. expect.anything(),
  97. expect.anything(),
  98. );
  99. });
  100. it("uses a distinct requestId per call", async () => {
  101. const { port, requestClient } = createHarness();
  102. await port.resolveHeaders({ ...BASE_REQUEST, workspacePath: "/repo" });
  103. await port.resolveHeaders({ ...BASE_REQUEST, workspacePath: "/repo" });
  104. const ids = requestClient.mock.calls.map(
  105. (call) => (call[1] as { requestId: string }).requestId,
  106. );
  107. expect(new Set(ids).size).toBe(2);
  108. });
  109. it("fails closed when the server context is not ready yet", async () => {
  110. const requestClient = vi.fn(async () => OK);
  111. const port = createOfficialMcpAuthHeadersPort({
  112. resolveContext: () => undefined,
  113. resolveWorkspace: entrypointResolveWorkspace("/fallback"),
  114. });
  115. await expect(port.resolveHeaders({ ...BASE_REQUEST, workspacePath: "/repo" })).resolves.toEqual(
  116. { ok: false, reason: "official_auth_unavailable" },
  117. );
  118. expect(requestClient).not.toHaveBeenCalled();
  119. });
  120. it("fails closed when no workspace can be resolved", async () => {
  121. const { port, requestClient } = createHarness({
  122. resolveWorkspace: entrypointResolveWorkspace(""),
  123. });
  124. await expect(port.resolveHeaders({ ...BASE_REQUEST })).resolves.toEqual({
  125. ok: false,
  126. reason: "official_auth_unavailable",
  127. });
  128. expect(requestClient).not.toHaveBeenCalled();
  129. });
  130. it("maps a transport failure to official_auth_unavailable without leaking details", async () => {
  131. const context = {
  132. requestClient: vi.fn(async () => {
  133. throw new Error("stdio closed: /secret/path context");
  134. }),
  135. } as unknown as OfficialMcpAuthRequestContext;
  136. const port = createOfficialMcpAuthHeadersPort({
  137. resolveContext: () => context,
  138. resolveWorkspace: entrypointResolveWorkspace("/fallback"),
  139. });
  140. const result = await port.resolveHeaders({ ...BASE_REQUEST, workspacePath: "/repo" });
  141. // 绝不降级为匿名,且不把可能含上下文的错误详情带出
  142. expect(result).toEqual({ ok: false, reason: "official_auth_unavailable" });
  143. });
  144. });