mcp-official-auth.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. /* 官方 MCP 逐请求动态身份头注入与失败分类。
  2. 用真实 loopback HTTP server 验证"实际发出的请求头",而不是 mock fetch 的调用参数。 */
  3. import { createServer, type Server } from "node:http";
  4. import type { AddressInfo } from "node:net";
  5. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  6. import type {
  7. Logger,
  8. OfficialMcpAuthHeadersPort,
  9. OfficialMcpTrustedOriginRegistry,
  10. } from "@zcode/contracts";
  11. import {
  12. createOfficialMcpAuthFetch,
  13. mergeOfficialAuthHeaders,
  14. OfficialMcpAuthError,
  15. type OfficialMcpServerResponseInfo,
  16. } from "../src/mcp/official-auth.js";
  17. const PLUGIN_ID = "zcode-tools@zcode-plugins-official";
  18. const MCP_KEY = "image-search";
  19. const JWT_HEADERS = {
  20. Authorization: "Bearer jwt-current",
  21. "Bigmodel-Target-Type": "PERSONAL",
  22. "X-Bigmodel-Authorization": "Bearer maas-jwt-current",
  23. };
  24. interface Received {
  25. headers: Record<string, string | string[] | undefined>;
  26. method: string;
  27. url: string;
  28. }
  29. let server: Server;
  30. let origin: string;
  31. let received: Received[];
  32. let respond: (index: number) => { body?: string; headers?: Record<string, string>; status: number };
  33. beforeEach(async () => {
  34. received = [];
  35. respond = () => ({ body: JSON.stringify({ ok: true }), status: 200 });
  36. server = createServer((request, response) => {
  37. received.push({
  38. headers: request.headers,
  39. method: request.method ?? "",
  40. url: request.url ?? "",
  41. });
  42. const reply = respond(received.length - 1);
  43. response.writeHead(reply.status, {
  44. "content-type": "application/json",
  45. ...reply.headers,
  46. });
  47. response.end(reply.body ?? "");
  48. });
  49. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  50. origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  51. });
  52. afterEach(async () => {
  53. await new Promise<void>((resolve) => server.close(() => resolve()));
  54. });
  55. function trustedRegistry(trusted = true): OfficialMcpTrustedOriginRegistry {
  56. return { isTrusted: async () => ({ trusted }) };
  57. }
  58. function headersPort(
  59. results: Array<Awaited<ReturnType<OfficialMcpAuthHeadersPort["resolveHeaders"]>>>,
  60. ): OfficialMcpAuthHeadersPort & { calls: number } {
  61. let calls = 0;
  62. return {
  63. get calls() {
  64. return calls;
  65. },
  66. resolveHeaders: async () => {
  67. const result = results[Math.min(calls, results.length - 1)]!;
  68. calls += 1;
  69. return result;
  70. },
  71. };
  72. }
  73. function rpcRequest(method: string, headers?: HeadersInit): RequestInit {
  74. return {
  75. body: JSON.stringify({ id: 1, jsonrpc: "2.0", method }),
  76. ...(headers ? { headers } : {}),
  77. method: "POST",
  78. };
  79. }
  80. function createFetch(overrides: {
  81. logger?: Logger;
  82. onServerResponse?: (response: OfficialMcpServerResponseInfo) => void;
  83. port?: OfficialMcpAuthHeadersPort;
  84. registry?: OfficialMcpTrustedOriginRegistry;
  85. url?: string;
  86. }): typeof globalThis.fetch {
  87. return createOfficialMcpAuthFetch({
  88. authHeadersPort: overrides.port ?? headersPort([{ headers: JWT_HEADERS, ok: true }]),
  89. baseFetch: globalThis.fetch,
  90. official: { mcpKey: MCP_KEY, pluginId: PLUGIN_ID, source: "plugin" },
  91. serverName: `plugin:zcode-tools:${MCP_KEY}`,
  92. trustedOrigins: overrides.registry ?? trustedRegistry(),
  93. url: overrides.url ?? `${origin}/mcp`,
  94. ...(overrides.logger ? { logger: overrides.logger } : {}),
  95. ...(overrides.onServerResponse ? { onServerResponse: overrides.onServerResponse } : {}),
  96. });
  97. }
  98. interface RecordedLog {
  99. context: Record<string, unknown>;
  100. level: "debug" | "error" | "info" | "warn";
  101. message: string;
  102. }
  103. /** 只收集日志,不做级别过滤——过滤由真实 logger 负责,这里要能断言"记在了哪个级别"。 */
  104. function recordingLogger(): { entries: RecordedLog[]; logger: Logger } {
  105. const entries: RecordedLog[] = [];
  106. const push =
  107. (level: RecordedLog["level"]) =>
  108. (message: string, context: Record<string, unknown> = {}) => {
  109. entries.push({ context, level, message });
  110. };
  111. return {
  112. entries,
  113. logger: {
  114. debug: push("debug"),
  115. error: push("error"),
  116. info: push("info"),
  117. warn: push("warn"),
  118. } as unknown as Logger,
  119. };
  120. }
  121. describe("official mcp auth fetch", () => {
  122. it.each([
  123. {
  124. body: JSON.stringify({ code: 3001, msg: "parameter error" }),
  125. failureKind: "server_not_found",
  126. status: 400,
  127. },
  128. {
  129. body: JSON.stringify({ code: 1000, msg: "something went wrong" }),
  130. failureKind: "server_unavailable",
  131. status: 200,
  132. },
  133. {
  134. body: JSON.stringify({
  135. error: { code: 1006, message: "no permission" },
  136. id: 1,
  137. jsonrpc: "2.0",
  138. }),
  139. failureKind: "not_authenticated",
  140. status: 200,
  141. },
  142. {
  143. body: JSON.stringify({
  144. error: { code: 3101, message: "coding plan is required" },
  145. id: 1,
  146. jsonrpc: "2.0",
  147. }),
  148. failureKind: "coding_plan_required",
  149. status: 200,
  150. },
  151. {
  152. body: JSON.stringify({ error: null, id: 1, jsonrpc: "2.0" }),
  153. failureKind: "protocol_error",
  154. status: 200,
  155. },
  156. {
  157. body: JSON.stringify({ error: [], id: 1, jsonrpc: "2.0" }),
  158. failureKind: "protocol_error",
  159. status: 200,
  160. },
  161. {
  162. body: JSON.stringify({ error: "message", id: 1, jsonrpc: "2.0" }),
  163. failureKind: "protocol_error",
  164. status: 200,
  165. },
  166. {
  167. body: JSON.stringify({
  168. error: { code: "1006", message: "no permission" },
  169. id: 1,
  170. jsonrpc: "2.0",
  171. }),
  172. failureKind: "protocol_error",
  173. status: 200,
  174. },
  175. {
  176. body: JSON.stringify({
  177. error: { code: 3101, message: "coding plan is required" },
  178. id: 1,
  179. jsonrpc: "2.0",
  180. }),
  181. failureKind: "coding_plan_required",
  182. status: 400,
  183. },
  184. { body: "", failureKind: "rate_limited", status: 429 },
  185. { body: "", failureKind: "server_internal_error", status: 500 },
  186. {
  187. body: JSON.stringify({
  188. error: { code: -32601, message: "method not found" },
  189. id: 1,
  190. jsonrpc: "2.0",
  191. }),
  192. failureKind: "protocol_error",
  193. status: 200,
  194. },
  195. ])(
  196. "classifies trusted ZCode response diagnostics as $failureKind",
  197. async ({ body, failureKind, status }) => {
  198. respond = () => ({
  199. body,
  200. headers: { "x-request-id": `req-${failureKind}` },
  201. status,
  202. });
  203. const onServerResponse = vi.fn();
  204. const authFetch = createFetch({ onServerResponse });
  205. await authFetch(`${origin}/mcp`, rpcRequest("initialize")).catch(() => undefined);
  206. expect(onServerResponse).toHaveBeenCalledWith(
  207. expect.objectContaining({
  208. failureKind,
  209. rpcMethod: "initialize",
  210. serverRequestId: `req-${failureKind}`,
  211. }),
  212. );
  213. },
  214. );
  215. it("OMCP-CALL-001: injects identity headers on every trusted HTTP request", async () => {
  216. const port = headersPort([{ headers: JWT_HEADERS, ok: true }]);
  217. const authFetch = createFetch({ port });
  218. for (const method of [
  219. "server/discover",
  220. "initialize",
  221. "notifications/initialized",
  222. "tools/list",
  223. "ping",
  224. ]) {
  225. await authFetch(`${origin}/mcp`, rpcRequest(method));
  226. }
  227. await authFetch(`${origin}/mcp`, rpcRequest("tools/call"));
  228. expect(port.calls).toBe(6);
  229. expect(received).toHaveLength(6);
  230. for (const entry of received) {
  231. expect(entry.headers["authorization"]).toBe("Bearer jwt-current");
  232. expect(entry.headers["x-bigmodel-authorization"]).toBe("Bearer maas-jwt-current");
  233. expect(entry.headers["bigmodel-target-type"]).toBe("PERSONAL");
  234. // 旧通道已废弃,客户端必须一个字节都不发(同时发会让服务端额外校验 API key 归属)
  235. expect(entry.headers["x-coding-plan-api-key"]).toBeUndefined();
  236. }
  237. });
  238. it("injects identity headers into GET probes and unparseable trusted requests", async () => {
  239. const port = headersPort([{ headers: JWT_HEADERS, ok: true }]);
  240. const authFetch = createFetch({ port });
  241. await authFetch(`${origin}/mcp`, { method: "GET" });
  242. await authFetch(`${origin}/mcp`, { body: "not-json", method: "POST" });
  243. expect(port.calls).toBe(2);
  244. expect(received).toHaveLength(2);
  245. expect(received.every((entry) => entry.headers["authorization"] === "Bearer jwt-current")).toBe(
  246. true,
  247. );
  248. });
  249. it("OMCP-022: overwrites a pre-existing Authorization instead of appending", async () => {
  250. const authFetch = createFetch({});
  251. await authFetch(`${origin}/mcp`, {
  252. ...rpcRequest("tools/call"),
  253. headers: { Authorization: "Bearer stale-oauth-token" },
  254. });
  255. // 单值且为当前 JWT:append 会得到逗号拼接,"缺失才补"会保留 stale token
  256. expect(received[0]?.headers["authorization"]).toBe("Bearer jwt-current");
  257. });
  258. it("preserves protocol and content headers set by the SDK", async () => {
  259. const authFetch = createFetch({});
  260. await authFetch(`${origin}/mcp`, {
  261. headers: {
  262. accept: "application/json, text/event-stream",
  263. "content-type": "application/json",
  264. "mcp-protocol-version": "2026-07-28",
  265. "mcp-session-id": "session-abc",
  266. },
  267. method: "POST",
  268. });
  269. expect(received[0]?.headers["mcp-session-id"]).toBe("session-abc");
  270. expect(received[0]?.headers["mcp-protocol-version"]).toBe("2026-07-28");
  271. expect(received[0]?.headers["accept"]).toBe("application/json, text/event-stream");
  272. expect(received[0]?.headers["content-type"]).toBe("application/json");
  273. });
  274. it("OMCP-003: fails closed with zero network requests when the origin is untrusted", async () => {
  275. const port = headersPort([{ headers: JWT_HEADERS, ok: true }]);
  276. const authFetch = createFetch({ port, registry: trustedRegistry(false) });
  277. await expect(authFetch(`${origin}/mcp`, rpcRequest("initialize"))).rejects.toMatchObject({
  278. kind: "official_mcp_origin_untrusted",
  279. });
  280. expect(received).toHaveLength(0);
  281. // 凭证也不该被解析
  282. expect(port.calls).toBe(0);
  283. });
  284. it("rejects a request whose URL origin drifts from the configured endpoint", async () => {
  285. const authFetch = createFetch({ url: `${origin}/mcp` });
  286. await expect(authFetch("http://127.0.0.1:1/mcp", { method: "POST" })).rejects.toBeInstanceOf(
  287. OfficialMcpAuthError,
  288. );
  289. expect(received).toHaveLength(0);
  290. });
  291. it("OMCP-CALL-002: sends tools/call anonymously when auth is unavailable", async () => {
  292. const port = headersPort([{ ok: false, reason: "official_auth_unavailable" }]);
  293. const authFetch = createFetch({ port });
  294. const response = await authFetch(`${origin}/mcp`, rpcRequest("tools/call"));
  295. expect(response.status).toBe(200);
  296. expect(port.calls).toBe(1);
  297. expect(received).toHaveLength(1);
  298. expect(received[0]?.headers["authorization"]).toBeUndefined();
  299. expect(received[0]?.headers["x-bigmodel-authorization"]).toBeUndefined();
  300. });
  301. it("OMCP-CALL-003: sends only the identity header when a plan is required", async () => {
  302. const port = headersPort([{ headers: { Authorization: "Bearer logged-in-jwt" }, ok: true }]);
  303. const { entries, logger } = recordingLogger();
  304. const authFetch = createFetch({ logger, port });
  305. const response = await authFetch(`${origin}/mcp`, rpcRequest("tools/call"));
  306. expect(response.status).toBe(200);
  307. expect(port.calls).toBe(1);
  308. expect(received).toHaveLength(1);
  309. expect(received[0]?.headers["authorization"]).toBe("Bearer logged-in-jwt");
  310. expect(received[0]?.headers["x-bigmodel-authorization"]).toBeUndefined();
  311. expect(received[0]?.headers["x-coding-plan-api-key"]).toBeUndefined();
  312. expect(
  313. entries.find((entry) => entry.message === "Official MCP request sending")?.context,
  314. ).toMatchObject({ identityHeaderNames: ["authorization"] });
  315. });
  316. it("OMCP-016: retries once on 401 and succeeds with the re-resolved credential", async () => {
  317. respond = (index) => (index === 0 ? { status: 401 } : { body: "{}", status: 200 });
  318. const port = headersPort([
  319. { headers: JWT_HEADERS, ok: true },
  320. { headers: { ...JWT_HEADERS, Authorization: "Bearer jwt-refreshed" }, ok: true },
  321. ]);
  322. const authFetch = createFetch({ port });
  323. const response = await authFetch(`${origin}/mcp`, rpcRequest("tools/call"));
  324. expect(response.status).toBe(200);
  325. expect(received).toHaveLength(2);
  326. expect(received[1]?.headers["authorization"]).toBe("Bearer jwt-refreshed");
  327. });
  328. it("OMCP-017: retries at most once on persistent 401, then classifies as rejected", async () => {
  329. respond = () => ({ status: 401 });
  330. const authFetch = createFetch({});
  331. await expect(authFetch(`${origin}/mcp`, rpcRequest("tools/call"))).rejects.toMatchObject({
  332. kind: "official_auth_rejected",
  333. });
  334. // 恰好 2 次:1 次原始 + 1 次重试,不自旋
  335. expect(received).toHaveLength(2);
  336. });
  337. it("does not retry a 401 when tools/call was sent without credentials", async () => {
  338. respond = () => ({ status: 401 });
  339. const authFetch = createFetch({
  340. port: headersPort([{ ok: false, reason: "official_auth_unavailable" }]),
  341. });
  342. await expect(authFetch(`${origin}/mcp`, rpcRequest("tools/call"))).rejects.toMatchObject({
  343. kind: "official_auth_rejected",
  344. });
  345. expect(received).toHaveLength(1);
  346. });
  347. it("releases both persistent 401 response bodies after preserving the request id", async () => {
  348. const cancelled: number[] = [];
  349. let attempt = 0;
  350. const authFetch = createOfficialMcpAuthFetch({
  351. authHeadersPort: headersPort([{ headers: JWT_HEADERS, ok: true }]),
  352. baseFetch: vi.fn(async () => {
  353. const current = attempt;
  354. attempt += 1;
  355. return new Response(
  356. new ReadableStream({
  357. cancel: () => {
  358. cancelled.push(current);
  359. },
  360. }),
  361. { headers: { "x-request-id": `req-401-${current}` }, status: 401 },
  362. );
  363. }),
  364. official: { mcpKey: MCP_KEY, pluginId: PLUGIN_ID, source: "plugin" },
  365. serverName: `plugin:zcode-tools:${MCP_KEY}`,
  366. trustedOrigins: trustedRegistry(),
  367. url: `${origin}/mcp`,
  368. });
  369. await expect(authFetch(`${origin}/mcp`, rpcRequest("tools/call"))).rejects.toMatchObject({
  370. kind: "official_auth_rejected",
  371. message: expect.stringContaining("req-401-1"),
  372. });
  373. expect(cancelled).toEqual([0, 1]);
  374. });
  375. it("OMCP-015: never retries a 403", async () => {
  376. respond = () => ({ status: 403 });
  377. const authFetch = createFetch({});
  378. await expect(authFetch(`${origin}/mcp`, rpcRequest("tools/call"))).rejects.toMatchObject({
  379. kind: "official_auth_forbidden",
  380. });
  381. expect(received).toHaveLength(1);
  382. });
  383. it("OMCP-008: blocks redirects without following them", async () => {
  384. for (const status of [301, 302, 307, 308]) {
  385. received = [];
  386. respond = () => ({ headers: { location: "https://attacker.example/mcp" }, status });
  387. const authFetch = createFetch({});
  388. await expect(authFetch(`${origin}/mcp`, rpcRequest("tools/call"))).rejects.toMatchObject({
  389. kind: "official_auth_redirect_blocked",
  390. });
  391. // 只发出到可信 Origin 的那一次;不会带着 Bearer 去 attacker.example
  392. expect(received).toHaveLength(1);
  393. }
  394. });
  395. it("logs the server request id at warn on any non-2xx response", async () => {
  396. // 生产 logger 的最低级别是 Info,成功路径那条 debug 记录在生产里根本不落盘。
  397. // 出错时能对上服务端日志的唯一线索就是这条 warn。
  398. respond = () => ({
  399. body: JSON.stringify({ code: 3001, msg: "parameter error" }),
  400. headers: { "x-request-id": "req-3001-abc" },
  401. status: 400,
  402. });
  403. const { entries, logger } = recordingLogger();
  404. const authFetch = createFetch({ logger });
  405. const response = await authFetch(`${origin}/mcp`, { method: "POST" });
  406. expect(response.status).toBe(400);
  407. const warned = entries.filter((entry) => entry.level === "warn");
  408. expect(warned).toHaveLength(1);
  409. expect(warned[0]?.context).toMatchObject({
  410. httpStatus: 400,
  411. mcpKey: MCP_KEY,
  412. serverRequestId: "req-3001-abc",
  413. });
  414. });
  415. it("omits serverRequestId instead of inventing one when the server sends no header", async () => {
  416. respond = () => ({ body: "{}", status: 500 });
  417. const { entries, logger } = recordingLogger();
  418. const authFetch = createFetch({ logger });
  419. await authFetch(`${origin}/mcp`, { method: "POST" });
  420. const warned = entries.filter((entry) => entry.level === "warn");
  421. expect(warned).toHaveLength(1);
  422. expect(warned[0]?.context).toMatchObject({ httpStatus: 500 });
  423. expect(warned[0]?.context).not.toHaveProperty("serverRequestId");
  424. });
  425. it("carries the server request id into the classified 401 / 403 / redirect errors", async () => {
  426. // 分类错误会成为 MCP record 的失败原因;request id 只进日志的话,用户报障时
  427. // 还得再去翻日志文件才能给出这个 id。
  428. const cases: Array<{
  429. kind: string;
  430. message: string;
  431. requestId: string;
  432. status: number;
  433. }> = [
  434. {
  435. kind: "official_auth_rejected",
  436. message: "official MCP rejected the current credential - req-401",
  437. requestId: "req-401",
  438. status: 401,
  439. },
  440. {
  441. kind: "official_auth_forbidden",
  442. message: "official MCP denied access for the current plan - req-403",
  443. requestId: "req-403",
  444. status: 403,
  445. },
  446. {
  447. kind: "official_auth_redirect_blocked",
  448. message: "official MCP responded with a blocked redirect (307) - req-307",
  449. requestId: "req-307",
  450. status: 307,
  451. },
  452. ];
  453. for (const testCase of cases) {
  454. received = [];
  455. respond = () => ({
  456. headers: {
  457. location: "https://attacker.example/mcp",
  458. "x-request-id": testCase.requestId,
  459. },
  460. status: testCase.status,
  461. });
  462. const authFetch = createFetch({});
  463. await expect(authFetch(`${origin}/mcp`, rpcRequest("tools/call"))).rejects.toMatchObject({
  464. kind: testCase.kind,
  465. message: testCase.message,
  466. });
  467. }
  468. });
  469. it("OMCP-012/027: resolves credentials per request, so a rotation is picked up immediately", async () => {
  470. const port = headersPort([
  471. { headers: JWT_HEADERS, ok: true },
  472. {
  473. headers: { ...JWT_HEADERS, "X-Bigmodel-Authorization": "Bearer maas-jwt-rotated" },
  474. ok: true,
  475. },
  476. ]);
  477. const authFetch = createFetch({ port });
  478. await authFetch(`${origin}/mcp`, rpcRequest("tools/call"));
  479. await authFetch(`${origin}/mcp`, rpcRequest("tools/call"));
  480. expect(received[0]?.headers["x-bigmodel-authorization"]).toBe("Bearer maas-jwt-current");
  481. expect(received[1]?.headers["x-bigmodel-authorization"]).toBe("Bearer maas-jwt-rotated");
  482. });
  483. it("passes the abort signal through to the auth port", async () => {
  484. const resolveHeaders = vi.fn(async () => ({ headers: JWT_HEADERS, ok: true as const }));
  485. const controller = new AbortController();
  486. const authFetch = createFetch({ port: { resolveHeaders } });
  487. await authFetch(`${origin}/mcp`, { ...rpcRequest("tools/call"), signal: controller.signal });
  488. expect(resolveHeaders).toHaveBeenCalledWith(
  489. expect.objectContaining({ mcpKey: MCP_KEY, pluginId: PLUGIN_ID, signal: controller.signal }),
  490. );
  491. });
  492. });
  493. describe("mergeOfficialAuthHeaders", () => {
  494. it("drops reserved identity headers coming from any upstream source", () => {
  495. const merged = mergeOfficialAuthHeaders(
  496. {
  497. Authorization: "Bearer stale",
  498. "Bigmodel-Organization": "spoofed-org",
  499. // 现在这是真身份头,静态值必须被 resolved 值**覆盖**(而不是丢弃)
  500. "x-bigmodel-authorization": "Bearer spoofed",
  501. // 旧通道客户端不再发送,但服务端仍然认它,因此静态注入必须被**丢弃**
  502. "x-coding-plan-api-key": "spoofed-plan-key",
  503. "x-trace-hint": "keep-me",
  504. },
  505. JWT_HEADERS,
  506. );
  507. expect(merged.get("authorization")).toBe("Bearer jwt-current");
  508. expect(merged.get("bigmodel-organization")).toBeNull();
  509. expect(merged.get("x-bigmodel-authorization")).toBe("Bearer maas-jwt-current");
  510. expect(merged.get("x-coding-plan-api-key")).toBeNull();
  511. expect(merged.get("x-trace-hint")).toBe("keep-me");
  512. });
  513. it("keeps protocol headers untouched", () => {
  514. const merged = mergeOfficialAuthHeaders(
  515. { "mcp-protocol-version": "2026-07-28", "mcp-session-id": "s1" },
  516. JWT_HEADERS,
  517. );
  518. expect(merged.get("mcp-session-id")).toBe("s1");
  519. expect(merged.get("mcp-protocol-version")).toBe("2026-07-28");
  520. });
  521. });
  522. /* 关联 id:服务端已明确否决"采用客户端传入的 request id"(logx.RequestID 始终自行生成、
  523. 不读入站 header)。因此客户端不发送这两个头,只做两件事:剥离插件注入的值、从响应头
  524. 读回服务端生成的 id 用于对账。 */
  525. describe("official mcp correlation ids", () => {
  526. it("does not send x-request-id or x-trace-id", async () => {
  527. // 发了不会被任何人读取,属死代码;这条用例锁住"不发"这一决策。
  528. const authFetch = createFetch({});
  529. await authFetch(`${origin}/mcp`, { method: "POST" });
  530. expect(received[0]!.headers["x-request-id"]).toBeUndefined();
  531. expect(received[0]!.headers["x-trace-id"]).toBeUndefined();
  532. });
  533. it("strips correlation headers injected by static plugin config", async () => {
  534. // 插件设的值会原样出现在服务端与中间层日志里,属可观测通道污染,必须剥掉。
  535. const authFetch = createFetch({});
  536. await authFetch(`${origin}/mcp`, {
  537. headers: { "x-request-id": "attacker-supplied", "x-trace-id": "attacker-trace" },
  538. method: "POST",
  539. });
  540. expect(received[0]!.headers["x-request-id"]).toBeUndefined();
  541. expect(received[0]!.headers["x-trace-id"]).toBeUndefined();
  542. });
  543. it("strips them on the 401 retry as well", async () => {
  544. // 重试走的是同一个 send(),但仍要确认第二次请求没有把它们漏出去。
  545. respond = (index) => (index === 0 ? { status: 401 } : { body: "{}", status: 200 });
  546. const authFetch = createFetch({});
  547. await authFetch(`${origin}/mcp`, {
  548. ...rpcRequest("tools/call"),
  549. headers: { "x-trace-id": "leaked" },
  550. });
  551. expect(received).toHaveLength(2);
  552. for (const entry of received) {
  553. expect(entry.headers["x-request-id"]).toBeUndefined();
  554. expect(entry.headers["x-trace-id"]).toBeUndefined();
  555. }
  556. });
  557. it("does not forward trace_id from the tools/call _meta", async () => {
  558. // _meta 里的 trace 只进客户端日志(mcpTraceId),不落到 HTTP 头上。
  559. const authFetch = createFetch({});
  560. await authFetch(`${origin}/mcp`, {
  561. body: JSON.stringify({
  562. id: 7,
  563. jsonrpc: "2.0",
  564. method: "tools/call",
  565. params: {
  566. arguments: { query: "should not leak anywhere" },
  567. _meta: { session_id: "sess-1", trace_id: "trace-xyz-789" },
  568. name: "search_image",
  569. },
  570. }),
  571. method: "POST",
  572. });
  573. expect(received[0]!.headers["x-trace-id"]).toBeUndefined();
  574. });
  575. it("keeps the identity headers intact while stripping correlation ones", async () => {
  576. // 回归护栏:delete 的实现不得误伤身份头。
  577. const authFetch = createFetch({});
  578. await authFetch(`${origin}/mcp`, {
  579. ...rpcRequest("tools/call"),
  580. headers: { "x-request-id": "drop-me" },
  581. });
  582. expect(received[0]!.headers["authorization"]).toBe("Bearer jwt-current");
  583. expect(received[0]!.headers["x-bigmodel-authorization"]).toBe("Bearer maas-jwt-current");
  584. expect(received[0]!.headers["bigmodel-target-type"]).toBe("PERSONAL");
  585. });
  586. });