officialMcpAuthRemoteRouting.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /* OMCP-011 —— desktop-attached remote 的官方 MCP 身份头反向请求路由(spec §7.2 / §7.4)。
  2. *
  3. * 验证目标:
  4. * 1. 远端 workspace(workspaceIdentity 非空)发起的请求能被 host 自动解析并响应;
  5. * 2. 响应只回到**发起请求的那个** Agent client,不按 workspacePath 串到同路径的其它 workspace;
  6. * 3. 该请求不产生 renderer event(无 UI 语义),也不写入任何 session/runtime 状态;
  7. * 4. 无 resolver 时(如 standalone CLI)返回 official_auth_unavailable,绝不降级为匿名请求。
  8. *
  9. * 说明:凭证本身是 host 全局状态,不按 workspace 隔离(§7.1),因此这里断言的是**路由**与
  10. * **响应通道**,不是 per-workspace 的不同凭证。
  11. */
  12. import { describe, expect, it, vi } from "vitest";
  13. import { zcodeProtocolMethods } from "@zcode/shared";
  14. const LOCAL_WORKSPACE = {
  15. workspaceKey: "/workspace/app",
  16. workspacePath: "/workspace/app",
  17. };
  18. const REMOTE_WORKSPACE = {
  19. workspaceIdentity: "remote:wsl:ubuntu:/workspace/app",
  20. workspaceKey: "remote:wsl:ubuntu:/workspace/app",
  21. // 与 LOCAL 同路径:若实现按 workspacePath 路由就会串台,这正是本用例要挡住的
  22. workspacePath: "/workspace/app",
  23. };
  24. interface FakeClient {
  25. onRequestListener?: (request: unknown) => void;
  26. respond: ReturnType<typeof vi.fn>;
  27. respondError: ReturnType<typeof vi.fn>;
  28. }
  29. /** 按 workspaceKey 分池的假 client,模拟 local host 与 desktop-attached remote host 两条链路。 */
  30. async function createServiceWithClients(options: {
  31. officialMcpAuthHeadersResolver?: {
  32. resolveHeaders(
  33. request?: unknown,
  34. ): Promise<
  35. | { ok: true; headers: Record<string, string> }
  36. | { ok: false; reason: "official_auth_unavailable" | "official_auth_plan_required" }
  37. >;
  38. };
  39. /** 缺省为"全部可信",以便既有路由用例聚焦响应通道。 */
  40. officialMcpTrustedOrigins?: {
  41. isTrusted(input: { pluginId: string; mcpKey: string; origin: string }): Promise<{
  42. detail?: string;
  43. trusted: boolean;
  44. }>;
  45. };
  46. /** 真正省略 validator(模拟装配遗漏);`undefined` 会落回"全部可信"缺省,无法表达该场景。 */
  47. omitTrustedOrigins?: boolean;
  48. }): Promise<{
  49. clients: Map<string, FakeClient>;
  50. dispose: () => Promise<void>;
  51. initializeWorkspace: (workspace: {
  52. workspaceIdentity?: string;
  53. workspacePath: string;
  54. }) => Promise<void>;
  55. }> {
  56. const clients = new Map<string, FakeClient>();
  57. vi.resetModules();
  58. vi.doMock("../src/zcode-agent/zcodeAgentProcessManager.js", () => ({
  59. ZCodeAgentProcessManager: class {
  60. onRuntimeRestarted() {
  61. return { dispose() {} };
  62. }
  63. async getClient(params: { workspaceIdentity?: string; workspacePath: string }) {
  64. const key = params.workspaceIdentity ?? params.workspacePath;
  65. const existing = clients.get(key);
  66. if (existing) return toProtocolClient(existing);
  67. const record: FakeClient = {
  68. respond: vi.fn(async () => {}),
  69. respondError: vi.fn(async () => {}),
  70. };
  71. clients.set(key, record);
  72. return toProtocolClient(record);
  73. }
  74. getExistingClient(params: { workspaceIdentity?: string; workspacePath: string }) {
  75. const record = clients.get(params.workspaceIdentity ?? params.workspacePath);
  76. return record ? toProtocolClient(record) : undefined;
  77. }
  78. getRuntimeIdentity() {
  79. return undefined;
  80. }
  81. markReady() {}
  82. onRuntimeLifecycle() {
  83. return { dispose() {} };
  84. }
  85. disposeWorkspace() {}
  86. disposeAll() {}
  87. async disposeAllAndWait() {}
  88. },
  89. }));
  90. function toProtocolClient(record: FakeClient) {
  91. return {
  92. onClose: () => ({ dispose() {} }),
  93. onNotification: () => ({ dispose() {} }),
  94. onRequest: (listener: (request: unknown) => void) => {
  95. record.onRequestListener = listener;
  96. return { dispose() {} };
  97. },
  98. request: async (method: string) => {
  99. if (method === zcodeProtocolMethods.initialize) {
  100. return {
  101. available: true,
  102. protocolName: "ZCode Protocol",
  103. protocolVersion: 1,
  104. workspaceKey: "/workspace/app",
  105. };
  106. }
  107. throw new Error(`Unexpected request method: ${method}`);
  108. },
  109. respond: record.respond,
  110. respondError: record.respondError,
  111. transportKind: "stdio",
  112. };
  113. }
  114. const { createZCodeAgentService } = await import("../src/zcode-agent/zcodeAgentService.js");
  115. const service = createZCodeAgentService({
  116. // initialize 会先确认当前模型选择 View 中存在可执行模型,否则以
  117. // provider_not_ready 提前返回、不建 client。
  118. modelSelectionReadinessSource: {
  119. async getView() {
  120. return {
  121. providers: [
  122. {
  123. providerId: "account:zai-start-plan",
  124. config: {
  125. kind: "account" as const,
  126. api: {
  127. type: "anthropic-messages" as const,
  128. baseUrl: "https://zcode.z.ai/api/v1/zcode-plan",
  129. },
  130. models: ["GLM-5.2"],
  131. },
  132. models: [{ modelId: "GLM-5.2", config: {} }],
  133. },
  134. ],
  135. revision: 1,
  136. };
  137. },
  138. },
  139. ...(options.officialMcpAuthHeadersResolver
  140. ? { officialMcpAuthHeadersResolver: options.officialMcpAuthHeadersResolver }
  141. : {}),
  142. ...(options.omitTrustedOrigins
  143. ? {}
  144. : {
  145. officialMcpTrustedOrigins: options.officialMcpTrustedOrigins ?? {
  146. isTrusted: async () => ({ trusted: true }),
  147. },
  148. }),
  149. });
  150. return {
  151. clients,
  152. dispose: () => service.disposeAllAndWait(),
  153. initializeWorkspace: async (workspace) => {
  154. const result = await service.initialize(workspace);
  155. if (!result.available) {
  156. throw new Error(`agent initialize failed: ${result.reason ?? "unknown"}`);
  157. }
  158. },
  159. };
  160. }
  161. function officialMcpAuthRequest(
  162. id: string,
  163. workspace: Record<string, string>,
  164. ): Record<string, unknown> {
  165. return {
  166. id,
  167. method: zcodeProtocolMethods.interactionRequestOfficialMcpAuthHeaders,
  168. params: {
  169. mcpKey: "image-search",
  170. pluginId: "zcode-tools@zcode-plugins-official",
  171. requestId: `official-mcp-auth:${id}`,
  172. targetOrigin: "https://mcp.zcode.example",
  173. workspace,
  174. },
  175. };
  176. }
  177. describe("official mcp auth headers over desktop-attached remote", () => {
  178. it("OMCP-011: answers a remote agent on its own client, not the same-path local one", async () => {
  179. const headers = {
  180. Authorization: "Bearer remote-jwt",
  181. "Bigmodel-Target-Type": "PERSONAL",
  182. "X-Bigmodel-Authorization": "Bearer remote-maas-jwt",
  183. };
  184. const harness = await createServiceWithClients({
  185. officialMcpAuthHeadersResolver: {
  186. resolveHeaders: async () => ({ headers, ok: true }),
  187. },
  188. });
  189. try {
  190. await harness.initializeWorkspace(LOCAL_WORKSPACE);
  191. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  192. // 同 workspacePath、不同 workspaceIdentity 必须是两个独立 client
  193. expect(harness.clients.size).toBe(2);
  194. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  195. const local = harness.clients.get(LOCAL_WORKSPACE.workspacePath);
  196. expect(remote).toBeDefined();
  197. expect(local).toBeDefined();
  198. remote?.onRequestListener?.(officialMcpAuthRequest("remote-1", REMOTE_WORKSPACE));
  199. await vi.waitFor(() => {
  200. expect(remote?.respond).toHaveBeenCalledTimes(1);
  201. });
  202. expect(remote?.respond).toHaveBeenCalledWith("remote-1", { headers, ok: true });
  203. // 关键:同路径的 local client 不能收到任何东西
  204. expect(local?.respond).not.toHaveBeenCalled();
  205. } finally {
  206. await harness.dispose();
  207. }
  208. });
  209. it("keeps local and remote responses on separate channels under interleaved requests", async () => {
  210. const harness = await createServiceWithClients({
  211. officialMcpAuthHeadersResolver: {
  212. resolveHeaders: async () => ({
  213. headers: { Authorization: "Bearer shared-jwt" },
  214. ok: true,
  215. }),
  216. },
  217. });
  218. try {
  219. await harness.initializeWorkspace(LOCAL_WORKSPACE);
  220. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  221. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  222. const local = harness.clients.get(LOCAL_WORKSPACE.workspacePath);
  223. local?.onRequestListener?.(officialMcpAuthRequest("local-1", LOCAL_WORKSPACE));
  224. remote?.onRequestListener?.(officialMcpAuthRequest("remote-1", REMOTE_WORKSPACE));
  225. local?.onRequestListener?.(officialMcpAuthRequest("local-2", LOCAL_WORKSPACE));
  226. await vi.waitFor(() => {
  227. expect(local?.respond).toHaveBeenCalledTimes(2);
  228. expect(remote?.respond).toHaveBeenCalledTimes(1);
  229. });
  230. // 每个响应都必须回到自己的 request id,不能交叉
  231. expect(local?.respond.mock.calls.map((call) => call[0])).toEqual(["local-1", "local-2"]);
  232. expect(remote?.respond.mock.calls.map((call) => call[0])).toEqual(["remote-1"]);
  233. } finally {
  234. await harness.dispose();
  235. }
  236. });
  237. it("propagates a plan-required refusal to the remote agent unchanged", async () => {
  238. const harness = await createServiceWithClients({
  239. officialMcpAuthHeadersResolver: {
  240. resolveHeaders: async () => ({ ok: false, reason: "official_auth_plan_required" }),
  241. },
  242. });
  243. try {
  244. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  245. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  246. remote?.onRequestListener?.(officialMcpAuthRequest("remote-1", REMOTE_WORKSPACE));
  247. await vi.waitFor(() => {
  248. expect(remote?.respond).toHaveBeenCalledTimes(1);
  249. });
  250. expect(remote?.respond).toHaveBeenCalledWith("remote-1", {
  251. ok: false,
  252. reason: "official_auth_plan_required",
  253. });
  254. } finally {
  255. await harness.dispose();
  256. }
  257. });
  258. it("OMCP-009: reports official_auth_unavailable when no resolver is wired", async () => {
  259. const harness = await createServiceWithClients({});
  260. try {
  261. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  262. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  263. remote?.onRequestListener?.(officialMcpAuthRequest("remote-1", REMOTE_WORKSPACE));
  264. await vi.waitFor(() => {
  265. expect(remote?.respond).toHaveBeenCalledTimes(1);
  266. });
  267. // 绝不降级为匿名:没有 resolver 就明确不可用
  268. expect(remote?.respond).toHaveBeenCalledWith("remote-1", {
  269. ok: false,
  270. reason: "official_auth_unavailable",
  271. });
  272. } finally {
  273. await harness.dispose();
  274. }
  275. });
  276. it("CR-01: rejects an untrusted origin without invoking the resolver at all", async () => {
  277. // host 是身份权威边界:Origin 不匹配时必须在**读取凭据之前**拒绝,
  278. // 否则 agent adapter 的 fetch wrapper 就成了唯一防线(远端 runtime 可绕过)。
  279. const resolveHeaders = vi.fn(async () => ({
  280. headers: { Authorization: "Bearer must-not-leak" },
  281. ok: true as const,
  282. }));
  283. const harness = await createServiceWithClients({
  284. officialMcpAuthHeadersResolver: { resolveHeaders },
  285. officialMcpTrustedOrigins: { isTrusted: async () => ({ trusted: false }) },
  286. });
  287. try {
  288. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  289. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  290. remote?.onRequestListener?.(officialMcpAuthRequest("remote-1", REMOTE_WORKSPACE));
  291. await vi.waitFor(() => {
  292. expect(remote?.respond).toHaveBeenCalledTimes(1);
  293. });
  294. expect(resolveHeaders).not.toHaveBeenCalled();
  295. expect(remote?.respond).toHaveBeenCalledWith("remote-1", {
  296. ok: false,
  297. reason: "official_mcp_origin_untrusted",
  298. });
  299. // 响应里不得出现任何 headers 字段
  300. const payload = remote?.respond.mock.calls[0]?.[1] as Record<string, unknown>;
  301. expect(payload["headers"]).toBeUndefined();
  302. expect(JSON.stringify(payload)).not.toContain("must-not-leak");
  303. } finally {
  304. await harness.dispose();
  305. }
  306. });
  307. it("CR-01: fails closed when no trusted-origin validator is injected", async () => {
  308. const resolveHeaders = vi.fn(async () => ({
  309. headers: { Authorization: "Bearer must-not-leak" },
  310. ok: true as const,
  311. }));
  312. const harness = await createServiceWithClients({
  313. officialMcpAuthHeadersResolver: { resolveHeaders },
  314. omitTrustedOrigins: true,
  315. });
  316. try {
  317. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  318. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  319. remote?.onRequestListener?.(officialMcpAuthRequest("remote-1", REMOTE_WORKSPACE));
  320. await vi.waitFor(() => {
  321. expect(remote?.respond).toHaveBeenCalledTimes(1);
  322. });
  323. expect(resolveHeaders).not.toHaveBeenCalled();
  324. } finally {
  325. await harness.dispose();
  326. }
  327. });
  328. it("CR-01: validates all three dimensions, not just one", async () => {
  329. // 逐维度只错一项,其余正确——防止实现只比较其中某一项。
  330. const seen: Array<{ mcpKey: string; origin: string; pluginId: string }> = [];
  331. const harness = await createServiceWithClients({
  332. officialMcpAuthHeadersResolver: {
  333. resolveHeaders: async () => ({ headers: { Authorization: "Bearer ok" }, ok: true }),
  334. },
  335. officialMcpTrustedOrigins: {
  336. isTrusted: async (input) => {
  337. seen.push(input);
  338. return {
  339. trusted:
  340. input.pluginId === "zcode-tools@zcode-plugins-official" &&
  341. input.mcpKey === "image-search" &&
  342. input.origin === "https://mcp.zcode.example",
  343. };
  344. },
  345. },
  346. });
  347. try {
  348. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  349. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  350. const variants: Array<{ id: string; overrides: Record<string, string> }> = [
  351. { id: "bad-plugin", overrides: { pluginId: "evil@third-party" } },
  352. { id: "bad-key", overrides: { mcpKey: "unregistered" } },
  353. { id: "bad-origin", overrides: { targetOrigin: "https://attacker.example" } },
  354. ];
  355. for (const variant of variants) {
  356. const base = officialMcpAuthRequest(variant.id, REMOTE_WORKSPACE);
  357. const params = base["params"] as Record<string, unknown>;
  358. remote?.onRequestListener?.({
  359. ...base,
  360. params: { ...params, ...variant.overrides },
  361. });
  362. }
  363. await vi.waitFor(() => {
  364. expect(remote?.respond).toHaveBeenCalledTimes(3);
  365. });
  366. for (const call of remote?.respond.mock.calls ?? []) {
  367. expect(call[1]).toEqual({ ok: false, reason: "official_mcp_origin_untrusted" });
  368. }
  369. // validator 三个字段都收全了。origin 是唯一的判定依据,pluginId / mcpKey 只用于日志
  370. // 与凭证解析归属,但仍必须完整传到 host——否则日志答不出"是哪个插件在要凭证"。
  371. expect(seen).toHaveLength(3);
  372. expect(seen.every((input) => input.pluginId && input.mcpKey && input.origin)).toBe(true);
  373. } finally {
  374. await harness.dispose();
  375. }
  376. });
  377. it("CR-01: forwards the request context to the resolver once trusted", async () => {
  378. const resolveHeaders = vi.fn(async () => ({
  379. headers: { Authorization: "Bearer ok" },
  380. ok: true as const,
  381. }));
  382. const harness = await createServiceWithClients({
  383. officialMcpAuthHeadersResolver: { resolveHeaders },
  384. });
  385. try {
  386. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  387. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  388. remote?.onRequestListener?.(officialMcpAuthRequest("remote-1", REMOTE_WORKSPACE));
  389. await vi.waitFor(() => {
  390. expect(resolveHeaders).toHaveBeenCalledTimes(1);
  391. });
  392. expect(resolveHeaders).toHaveBeenCalledWith(
  393. expect.objectContaining({
  394. mcpKey: "image-search",
  395. pluginId: "zcode-tools@zcode-plugins-official",
  396. targetOrigin: "https://mcp.zcode.example",
  397. workspace: expect.objectContaining({
  398. workspaceIdentity: REMOTE_WORKSPACE.workspaceIdentity,
  399. }),
  400. }),
  401. );
  402. } finally {
  403. await harness.dispose();
  404. }
  405. });
  406. it("rejects malformed params without invoking the resolver", async () => {
  407. const resolveHeaders = vi.fn(async () => ({
  408. headers: { Authorization: "Bearer jwt" },
  409. ok: true as const,
  410. }));
  411. const harness = await createServiceWithClients({
  412. officialMcpAuthHeadersResolver: { resolveHeaders },
  413. });
  414. try {
  415. await harness.initializeWorkspace(REMOTE_WORKSPACE);
  416. const remote = harness.clients.get(REMOTE_WORKSPACE.workspaceIdentity);
  417. remote?.onRequestListener?.({
  418. id: "remote-bad",
  419. method: zcodeProtocolMethods.interactionRequestOfficialMcpAuthHeaders,
  420. // 走私凭证字段 + 缺 targetOrigin:strict schema 必须拒绝
  421. params: {
  422. jwt: "leaked",
  423. mcpKey: "image-search",
  424. pluginId: "zcode-tools@zcode-plugins-official",
  425. requestId: "official-mcp-auth:bad",
  426. workspace: REMOTE_WORKSPACE,
  427. },
  428. });
  429. await vi.waitFor(() => {
  430. expect(remote?.respondError).toHaveBeenCalledTimes(1);
  431. });
  432. // schema 失败走 respondError 而非 respond,且凭证解析不得被触发
  433. expect(resolveHeaders).not.toHaveBeenCalled();
  434. expect(remote?.respond).not.toHaveBeenCalled();
  435. expect(remote?.respondError).toHaveBeenCalledWith(
  436. "remote-bad",
  437. expect.objectContaining({ code: -32602 }),
  438. );
  439. } finally {
  440. await harness.dispose();
  441. }
  442. });
  443. });