mcp-oauth.e2e.test.ts 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023
  1. import { createHash } from "node:crypto";
  2. import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
  3. import { Buffer } from "node:buffer";
  4. import { mkdtemp, rm } from "node:fs/promises";
  5. import { tmpdir } from "node:os";
  6. import { join } from "node:path";
  7. import type {
  8. OAuthClientInformationMixed,
  9. OAuthTokens,
  10. } from "@modelcontextprotocol/sdk/shared/auth.js";
  11. import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
  12. import type { Logger } from "@zcode/contracts";
  13. import { afterEach, describe, expect, it, vi } from "vitest";
  14. import {
  15. createSharedZCodeCredentialStore,
  16. type SharedZCodeCredentialStore,
  17. } from "../src/auth/shared-credentials.js";
  18. import { createMcpAdapter } from "../src/mcp/index.js";
  19. import { publishCanonicalCredentials } from "../src/mcp/oauth-credentials.js";
  20. import { MCP_OAUTH_INTERACTIVE_REQUIRED_ERROR_CODE } from "../src/mcp/oauth-errors.js";
  21. import {
  22. createCredentialKeyPrefix,
  23. createMcpAuthorizationCodeOAuthSession,
  24. type McpOAuthSession,
  25. } from "../src/mcp/oauth.js";
  26. import { createMcpOAuthTokenProvider } from "../src/mcp/oauth-provider.js";
  27. const OAUTH_ACCESS_TOKEN = "oauth-e2e-access-token";
  28. const OAUTH_CLIENT_ID = "zcode-client";
  29. const OAUTH_CLIENT_SECRET = "zcode-secret";
  30. const DYNAMIC_CLIENT_ID = "dynamic-zcode-client";
  31. const DYNAMIC_CLIENT_SECRET = "dynamic-zcode-secret";
  32. const MCP_SCOPE = "mcp:tools";
  33. /** 后台授权完成后等待连接恢复的轮询上限。 */
  34. const RECOVERY_POLL_ATTEMPTS = 100;
  35. const RECOVERY_POLL_INTERVAL_MS = 20;
  36. const servers: Server[] = [];
  37. interface StrictAuthorizationServerState {
  38. authorizationCodes: Map<
  39. string,
  40. {
  41. clientId: string;
  42. codeChallenge: string;
  43. redirectUri: string;
  44. }
  45. >;
  46. clients: Map<
  47. string,
  48. {
  49. clientSecret: string;
  50. redirectUris: string[];
  51. }
  52. >;
  53. refreshTokens: Map<string, string>;
  54. }
  55. describe("MCP OAuth client credentials e2e", () => {
  56. afterEach(async () => {
  57. await Promise.all(servers.splice(0).map(closeServer));
  58. });
  59. it("authenticates a protected HTTP MCP server after a 401 challenge", async () => {
  60. const authTokenRequests: Array<Record<string, string>> = [];
  61. const mcpAuthorizations: string[] = [];
  62. let authBaseUrl = "";
  63. const authServer = await listen(
  64. createServer(async (req, res) => {
  65. await handleAuthServerRequest(req, res, {
  66. authBaseUrl,
  67. tokenRequests: authTokenRequests,
  68. });
  69. }),
  70. );
  71. authBaseUrl = serverBaseUrl(authServer);
  72. let mcpUrl = "";
  73. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  74. const mcpServer = await listen(
  75. createServer(async (req, res) => {
  76. await handleProtectedMcpRequest(req, res, {
  77. authBaseUrl,
  78. authorizations: mcpAuthorizations,
  79. mcpUrl,
  80. resourceMetadataPath,
  81. });
  82. }),
  83. );
  84. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  85. const adapter = createMcpAdapter();
  86. const status = await adapter.connectServer("protected", {
  87. type: "http",
  88. url: mcpUrl,
  89. oauth: {
  90. type: "client_credentials",
  91. clientId: OAUTH_CLIENT_ID,
  92. clientSecret: OAUTH_CLIENT_SECRET,
  93. scope: MCP_SCOPE,
  94. },
  95. });
  96. expect(status).toMatchObject({
  97. status: "connected",
  98. toolCount: 1,
  99. transport: "http",
  100. });
  101. await expect(adapter.listTools()).resolves.toMatchObject([
  102. {
  103. serverName: "protected",
  104. toolName: "oauth_ping",
  105. },
  106. ]);
  107. expect(authTokenRequests).toEqual([
  108. expect.objectContaining({
  109. grant_type: "client_credentials",
  110. resource: mcpUrl,
  111. scope: MCP_SCOPE,
  112. }),
  113. ]);
  114. expect(mcpAuthorizations).toContain(`Bearer ${OAUTH_ACCESS_TOKEN}`);
  115. await adapter.close();
  116. });
  117. it("completes interactive authorization_code OAuth and reconnects the MCP server", async () => {
  118. const authorizationRequests: Array<Record<string, string>> = [];
  119. const authTokenRequests: Array<Record<string, string>> = [];
  120. const mcpAuthorizations: string[] = [];
  121. const registrationRequests: Array<Record<string, unknown>> = [];
  122. const pkceChallenges = new Map<string, string>();
  123. let authBaseUrl = "";
  124. const authServer = await listen(
  125. createServer(async (req, res) => {
  126. await handleAuthorizationCodeAuthServerRequest(req, res, {
  127. authBaseUrl,
  128. authorizationRequests,
  129. pkceChallenges,
  130. registrationRequests,
  131. tokenRequests: authTokenRequests,
  132. });
  133. }),
  134. );
  135. authBaseUrl = serverBaseUrl(authServer);
  136. let mcpUrl = "";
  137. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  138. const mcpServer = await listen(
  139. createServer(async (req, res) => {
  140. await handleProtectedMcpRequest(req, res, {
  141. authBaseUrl,
  142. authorizations: mcpAuthorizations,
  143. mcpUrl,
  144. resourceMetadataPath,
  145. });
  146. }),
  147. );
  148. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  149. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-"));
  150. const credentialStore = createSharedZCodeCredentialStore({
  151. env: {
  152. ZCODE_CREDENTIAL_SECRET: "mcp-oauth-e2e-secret",
  153. },
  154. filePath: join(credentialsDir, "credentials.json"),
  155. });
  156. const adapter = createMcpAdapter({
  157. mcpOAuth: {
  158. authorizationTimeoutMs: 5_000,
  159. credentialStore,
  160. openAuthorizationUrl: async ({ authorizationUrl }) => {
  161. const authorizationResponse = await fetch(authorizationUrl, {
  162. redirect: "manual",
  163. });
  164. expect(authorizationResponse.status).toBe(302);
  165. const location = authorizationResponse.headers.get("location");
  166. if (!location) {
  167. throw new Error("Authorization server did not redirect to callback URL");
  168. }
  169. const callbackResponse = await fetch(location);
  170. expect(callbackResponse.status).toBe(200);
  171. },
  172. },
  173. });
  174. try {
  175. const status = await adapter.connectServer("figma", {
  176. type: "http",
  177. url: mcpUrl,
  178. oauth: {
  179. type: "authorization_code",
  180. clientName: "ZCode Test",
  181. scope: MCP_SCOPE,
  182. },
  183. });
  184. expect(status).toMatchObject({
  185. status: "connected",
  186. toolCount: 1,
  187. transport: "http",
  188. });
  189. await expect(adapter.listTools()).resolves.toMatchObject([
  190. {
  191. serverName: "figma",
  192. toolName: "oauth_ping",
  193. },
  194. ]);
  195. expect(registrationRequests).toHaveLength(1);
  196. expect(registrationRequests[0]).toMatchObject({
  197. client_name: "ZCode Test",
  198. grant_types: ["authorization_code", "refresh_token"],
  199. response_types: ["code"],
  200. scope: MCP_SCOPE,
  201. });
  202. expect(registrationRequests[0]?.redirect_uris).toEqual([
  203. expect.stringMatching(/^http:\/\/127\.0\.0\.1:\d+\/oauth\/callback\/mcp\/figma$/),
  204. ]);
  205. expect(authorizationRequests).toEqual([
  206. expect.objectContaining({
  207. client_id: DYNAMIC_CLIENT_ID,
  208. code_challenge_method: "S256",
  209. redirect_uri: expect.stringMatching(
  210. /^http:\/\/127\.0\.0\.1:\d+\/oauth\/callback\/mcp\/figma$/,
  211. ),
  212. resource: mcpUrl,
  213. response_type: "code",
  214. scope: MCP_SCOPE,
  215. }),
  216. ]);
  217. expect(authorizationRequests[0]?.code_challenge).toMatch(/^[A-Za-z0-9_-]{43}$/);
  218. expect(authorizationRequests[0]?.state).toMatch(/^[A-Za-z0-9_-]+$/);
  219. expect(authTokenRequests).toEqual([
  220. expect.objectContaining({
  221. code: "interactive-code-1",
  222. grant_type: "authorization_code",
  223. redirect_uri: expect.stringMatching(
  224. /^http:\/\/127\.0\.0\.1:\d+\/oauth\/callback\/mcp\/figma$/,
  225. ),
  226. resource: mcpUrl,
  227. }),
  228. ]);
  229. expect(authTokenRequests[0]?.code_verifier).toMatch(/^[A-Za-z0-9._~-]{43,128}$/);
  230. expect(pkceChallenges.size).toBe(0);
  231. expect(mcpAuthorizations).toContain(`Bearer ${OAUTH_ACCESS_TOKEN}`);
  232. } finally {
  233. await adapter.close();
  234. await rm(credentialsDir, { force: true, recursive: true });
  235. }
  236. });
  237. it("runs a single interactive authorization transaction for concurrent adapters sharing one credential file", async () => {
  238. const authorizationRequests: Array<Record<string, string>> = [];
  239. const authTokenRequests: Array<Record<string, string>> = [];
  240. const mcpAuthorizations: string[] = [];
  241. const registrationRequests: Array<Record<string, unknown>> = [];
  242. const pkceChallenges = new Map<string, string>();
  243. const strictAuthorizationState = createStrictAuthorizationServerState();
  244. let authBaseUrl = "";
  245. const authServer = await listen(
  246. createServer(async (req, res) => {
  247. await handleAuthorizationCodeAuthServerRequest(req, res, {
  248. authBaseUrl,
  249. authorizationRequests,
  250. pkceChallenges,
  251. registrationRequests,
  252. strictAuthorizationState,
  253. tokenRequests: authTokenRequests,
  254. });
  255. }),
  256. );
  257. authBaseUrl = serverBaseUrl(authServer);
  258. let mcpUrl = "";
  259. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  260. const mcpServer = await listen(
  261. createServer(async (req, res) => {
  262. await handleProtectedMcpRequest(req, res, {
  263. authBaseUrl,
  264. authorizations: mcpAuthorizations,
  265. mcpUrl,
  266. resourceMetadataPath,
  267. });
  268. }),
  269. );
  270. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  271. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-race-"));
  272. const credentialStore = createSharedZCodeCredentialStore({
  273. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-race-secret" },
  274. filePath: join(credentialsDir, "credentials.json"),
  275. });
  276. const authorizationUrls: string[] = [];
  277. const driveAuthorization = async ({ authorizationUrl }: { authorizationUrl: string }) => {
  278. authorizationUrls.push(authorizationUrl);
  279. await followAuthorizationRedirect(authorizationUrl);
  280. };
  281. const adapterA = createMcpAdapter({
  282. mcpOAuth: {
  283. authorizationTimeoutMs: 5_000,
  284. credentialStore,
  285. openAuthorizationUrl: driveAuthorization,
  286. },
  287. });
  288. const adapterB = createMcpAdapter({
  289. mcpOAuth: {
  290. authorizationTimeoutMs: 5_000,
  291. credentialStore,
  292. openAuthorizationUrl: driveAuthorization,
  293. },
  294. });
  295. const config = {
  296. type: "http" as const,
  297. url: mcpUrl,
  298. oauth: {
  299. type: "authorization_code" as const,
  300. clientName: "ZCode Concurrent Test",
  301. scope: MCP_SCOPE,
  302. },
  303. };
  304. try {
  305. const [statusA, statusB] = await Promise.all([
  306. adapterA.connectServer("exa", config),
  307. adapterB.connectServer("exa", config),
  308. ]);
  309. // 修复原因(根因 2):过去两个并发 adapter 各跑一套授权事务,产生两个 DCR client、两个
  310. // state、两个授权 URL;用户会点到已超时或非目标事务的链接,且每个 client 的 redirect_uris
  311. // 都锁死在各自的随机端口。现在授权由跨进程 lease 单飞,follower 观察 canonical 换代后
  312. // 复用同一份凭据。
  313. expect(statusA).toMatchObject({ status: "connected", toolCount: 1 });
  314. expect(statusB).toMatchObject({ status: "connected", toolCount: 1 });
  315. expect(authorizationUrls).toHaveLength(1);
  316. expect(authorizationRequests).toHaveLength(1);
  317. expect(registrationRequests).toHaveLength(1);
  318. expect(authTokenRequests).toHaveLength(1);
  319. expect(authTokenRequests[0]).toMatchObject({
  320. client_id: `${DYNAMIC_CLIENT_ID}-1`,
  321. code: "interactive-code-1",
  322. grant_type: "authorization_code",
  323. });
  324. // fresh DCR 的 redirect_uri 必须与本次授权请求实际使用的回调地址一致。
  325. expect(registrationRequests[0]?.redirect_uris).toEqual([
  326. authorizationRequests[0]?.redirect_uri,
  327. ]);
  328. expect(pkceChallenges.size).toBe(0);
  329. } finally {
  330. await Promise.all([adapterA.close(), adapterB.close()]);
  331. await rm(credentialsDir, { force: true, recursive: true });
  332. }
  333. });
  334. it("re-registers a fresh client instead of reusing a stored client bound to a dead callback port", async () => {
  335. const authorizationRequests: Array<Record<string, string>> = [];
  336. const authTokenRequests: Array<Record<string, string>> = [];
  337. const mcpAuthorizations: string[] = [];
  338. const registrationRequests: Array<Record<string, unknown>> = [];
  339. const pkceChallenges = new Map<string, string>();
  340. const strictAuthorizationState = createStrictAuthorizationServerState();
  341. const STALE_CLIENT_ID = "stale-exa-client";
  342. const STALE_REDIRECT_URI = "http://127.0.0.1:54735/oauth/callback/mcp/exa";
  343. let authBaseUrl = "";
  344. const authServer = await listen(
  345. createServer(async (req, res) => {
  346. await handleAuthorizationCodeAuthServerRequest(req, res, {
  347. authBaseUrl,
  348. authorizationRequests,
  349. // 精确匹配 redirect_uri(含端口),模拟对 loopback 不做 RFC 8252 端口豁免的授权服务器。
  350. exactRedirectUriMatch: true,
  351. pkceChallenges,
  352. registrationRequests,
  353. strictAuthorizationState,
  354. tokenRequests: authTokenRequests,
  355. });
  356. }),
  357. );
  358. authBaseUrl = serverBaseUrl(authServer);
  359. let mcpUrl = "";
  360. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  361. const mcpServer = await listen(
  362. createServer(async (req, res) => {
  363. await handleProtectedMcpRequest(req, res, {
  364. authBaseUrl,
  365. authorizations: mcpAuthorizations,
  366. mcpUrl,
  367. resourceMetadataPath,
  368. });
  369. }),
  370. );
  371. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  372. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-stale-client-"));
  373. const credentialStore = createSharedZCodeCredentialStore({
  374. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-stale-client-secret" },
  375. filePath: join(credentialsDir, "credentials.json"),
  376. });
  377. const oauthConfig = {
  378. type: "authorization_code" as const,
  379. clientName: "ZCode exa",
  380. scope: MCP_SCOPE,
  381. };
  382. const keyPrefix = createCredentialKeyPrefix("exa", mcpUrl, oauthConfig);
  383. // 现场复现:client 注册于历史端口 54735,之后每次授权都换新的随机端口。
  384. strictAuthorizationState.clients.set(STALE_CLIENT_ID, {
  385. clientSecret: "stale-exa-secret",
  386. redirectUris: [STALE_REDIRECT_URI],
  387. });
  388. await credentialStore.save(
  389. `${keyPrefix}:client_information`,
  390. JSON.stringify({
  391. client_id: STALE_CLIENT_ID,
  392. client_secret: "stale-exa-secret",
  393. token_endpoint_auth_method: "client_secret_basic",
  394. }),
  395. );
  396. const adapter = createMcpAdapter({
  397. mcpOAuth: {
  398. authorizationTimeoutMs: 5_000,
  399. credentialStore,
  400. openAuthorizationUrl: async ({ authorizationUrl }) => {
  401. await followAuthorizationRedirect(authorizationUrl);
  402. },
  403. },
  404. });
  405. try {
  406. const status = await adapter.connectServer("exa", {
  407. type: "http",
  408. url: mcpUrl,
  409. oauth: oauthConfig,
  410. });
  411. // 修复原因(根因 2):过去这条路径会发出「旧 client_id + 新 redirect_uri」的授权请求。
  412. // 授权服务器按 RFC 6749 §4.1.2.1 禁止回跳、就地渲染错误页(用户看到的 Exa
  413. // "Server Components render error"),回调永不到达,且重试永不自愈。
  414. expect(status).toMatchObject({ status: "connected", toolCount: 1 });
  415. expect(registrationRequests).toHaveLength(1);
  416. expect(authorizationRequests).toHaveLength(1);
  417. expect(authorizationRequests[0]?.client_id).toBe(`${DYNAMIC_CLIENT_ID}-1`);
  418. expect(authorizationRequests[0]?.client_id).not.toBe(STALE_CLIENT_ID);
  419. expect(authorizationRequests[0]?.redirect_uri).not.toBe(STALE_REDIRECT_URI);
  420. // fresh DCR 注册的 redirect_uri 必须正是本次授权实际使用的存活 listener 地址。
  421. expect(registrationRequests[0]?.redirect_uris).toEqual([
  422. authorizationRequests[0]?.redirect_uri,
  423. ]);
  424. expect(authTokenRequests).toHaveLength(1);
  425. expect(authTokenRequests[0]?.client_id).toBe(`${DYNAMIC_CLIENT_ID}-1`);
  426. // 发布后的 canonical pair 必须是本次授权的 client,而不是历史 client。
  427. const canonicalRaw = await credentialStore.load(`${keyPrefix}:authorization_credentials`);
  428. expect(canonicalRaw).toBeTruthy();
  429. const canonical = JSON.parse(canonicalRaw ?? "{}") as {
  430. client_information?: { client_id?: string };
  431. generation?: string;
  432. };
  433. expect(canonical.client_information?.client_id).toBe(`${DYNAMIC_CLIENT_ID}-1`);
  434. expect(canonical.generation).toMatch(/^[0-9a-f]{32}$/);
  435. } finally {
  436. await adapter.close();
  437. await rm(credentialsDir, { force: true, recursive: true });
  438. }
  439. });
  440. it("performs zero discovery, zero DCR and opens zero listeners for a passive connect with valid credentials", async () => {
  441. const authorizationRequests: Array<Record<string, string>> = [];
  442. const authTokenRequests: Array<Record<string, string>> = [];
  443. const mcpAuthorizations: string[] = [];
  444. const registrationRequests: Array<Record<string, unknown>> = [];
  445. const pkceChallenges = new Map<string, string>();
  446. let authServerRequests = 0;
  447. let authBaseUrl = "";
  448. const authServer = await listen(
  449. createServer(async (req, res) => {
  450. authServerRequests += 1;
  451. await handleAuthorizationCodeAuthServerRequest(req, res, {
  452. authBaseUrl,
  453. authorizationRequests,
  454. pkceChallenges,
  455. registrationRequests,
  456. tokenRequests: authTokenRequests,
  457. });
  458. }),
  459. );
  460. authBaseUrl = serverBaseUrl(authServer);
  461. let mcpUrl = "";
  462. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  463. const mcpServer = await listen(
  464. createServer(async (req, res) => {
  465. await handleProtectedMcpRequest(req, res, {
  466. authBaseUrl,
  467. authorizations: mcpAuthorizations,
  468. mcpUrl,
  469. resourceMetadataPath,
  470. });
  471. }),
  472. );
  473. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  474. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-passive-"));
  475. const credentialStore = createSharedZCodeCredentialStore({
  476. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-passive-secret" },
  477. filePath: join(credentialsDir, "credentials.json"),
  478. });
  479. const oauthConfig = { type: "authorization_code" as const, scope: MCP_SCOPE };
  480. const keyPrefix = createCredentialKeyPrefix("passive", mcpUrl, oauthConfig);
  481. // 现成可用的凭据:还没临期,因此连接期不需要任何 OAuth 动作。
  482. await publishCanonicalCredentials(credentialStore, keyPrefix, {
  483. clientInformation: { client_id: "passive-client" },
  484. publishedBy: "passive-seed",
  485. tokens: {
  486. access_token: OAUTH_ACCESS_TOKEN,
  487. expires_in: 3600,
  488. refresh_token: "passive-refresh-token",
  489. token_type: "Bearer",
  490. },
  491. });
  492. const adapter = createMcpAdapter({ mcpOAuth: { credentialStore } });
  493. const listenersBefore = countTcpServers();
  494. try {
  495. const status = await adapter.connectServer("passive", {
  496. type: "http",
  497. url: mcpUrl,
  498. oauth: oauthConfig,
  499. });
  500. expect(status).toMatchObject({ status: "connected", toolCount: 1 });
  501. expect(mcpAuthorizations).toContain(`Bearer ${OAUTH_ACCESS_TOKEN}`);
  502. // 修复原因:过去任何没有 Authorization header 的 HTTP/SSE MCP 在建连前就会创建完整 OAuth
  503. // session,而 session 返回前就 listen(0) 起了一个 callback server——即使凭据完全有效。
  504. // 纯 AuthProvider 让被动连接彻底不碰 discovery / DCR / listener。
  505. expect(authServerRequests).toBe(0);
  506. expect(registrationRequests).toHaveLength(0);
  507. expect(authorizationRequests).toHaveLength(0);
  508. expect(countTcpServers()).toBe(listenersBefore);
  509. } finally {
  510. await adapter.close();
  511. await rm(credentialsDir, { force: true, recursive: true });
  512. }
  513. });
  514. it("recovers a tool call whose refresh token was revoked by running Phase 2 and reconnecting", async () => {
  515. const authorizationRequests: Array<Record<string, string>> = [];
  516. const authTokenRequests: Array<Record<string, string>> = [];
  517. const mcpAuthorizations: string[] = [];
  518. const registrationRequests: Array<Record<string, unknown>> = [];
  519. const pkceChallenges = new Map<string, string>();
  520. let authBaseUrl = "";
  521. const authServer = await listen(
  522. createServer(async (req, res) => {
  523. await handleAuthorizationCodeAuthServerRequest(req, res, {
  524. authBaseUrl,
  525. authorizationRequests,
  526. pkceChallenges,
  527. registrationRequests,
  528. tokenRequests: authTokenRequests,
  529. });
  530. }),
  531. );
  532. authBaseUrl = serverBaseUrl(authServer);
  533. // 前 N 次工具调用返回 401,模拟运行期 access token 失效。
  534. let rejectToolCalls = true;
  535. let mcpUrl = "";
  536. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  537. const mcpServer = await listen(
  538. createServer(async (req, res) => {
  539. if (rejectToolCalls && req.method === "POST") {
  540. const body = await readRequestBody(req);
  541. if (body.includes('"tools/call"')) {
  542. res.writeHead(401, {
  543. "WWW-Authenticate": [
  544. `Bearer resource_metadata="${new URL(resourceMetadataPath, mcpUrl).href}", scope="${MCP_SCOPE}"`,
  545. ],
  546. });
  547. res.end();
  548. return;
  549. }
  550. await handleProtectedMcpRequest(req, res, {
  551. authBaseUrl,
  552. authorizations: mcpAuthorizations,
  553. body,
  554. mcpUrl,
  555. resourceMetadataPath,
  556. });
  557. return;
  558. }
  559. await handleProtectedMcpRequest(req, res, {
  560. authBaseUrl,
  561. authorizations: mcpAuthorizations,
  562. mcpUrl,
  563. resourceMetadataPath,
  564. });
  565. }),
  566. );
  567. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  568. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-runtime-"));
  569. const credentialStore = createSharedZCodeCredentialStore({
  570. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-runtime-secret" },
  571. filePath: join(credentialsDir, "credentials.json"),
  572. });
  573. const oauthConfig = { type: "authorization_code" as const, scope: MCP_SCOPE };
  574. const keyPrefix = createCredentialKeyPrefix("runtime", mcpUrl, oauthConfig);
  575. await publishCanonicalCredentials(credentialStore, keyPrefix, {
  576. clientInformation: { client_id: "revoked-client" },
  577. publishedBy: "runtime-seed",
  578. tokens: {
  579. access_token: OAUTH_ACCESS_TOKEN,
  580. expires_in: 3600,
  581. // 该 refresh token 在 fake AS 上不存在 → 刷新时收到 invalid_grant。
  582. refresh_token: "revoked-refresh-token",
  583. token_type: "Bearer",
  584. },
  585. });
  586. const adapter = createMcpAdapter({
  587. mcpOAuth: {
  588. credentialStore,
  589. openAuthorizationUrl: async ({ authorizationUrl }) => {
  590. rejectToolCalls = false;
  591. await followAuthorizationRedirect(authorizationUrl);
  592. },
  593. },
  594. });
  595. try {
  596. const status = await adapter.connectServer("runtime", {
  597. type: "http",
  598. url: mcpUrl,
  599. oauth: oauthConfig,
  600. });
  601. expect(status).toMatchObject({ status: "connected", toolCount: 1 });
  602. // Bugfix 回归:建连后 token 被撤销时,过去 callTool 的 401/403 原样冒泡,用户看到裸错误且
  603. // 永不自愈——OAuth 自愈只存在于 startup connect 路径。现在运行期共用 Phase 2 → Phase 1 编排。
  604. // 授权链接一发布,触发授权的这次调用就结束(由 core 改写为 needs-auth);授权在后台完成后连接恢复。
  605. await expect(
  606. adapter.callTool({ serverName: "runtime", toolName: "oauth_ping" }),
  607. ).rejects.toThrow();
  608. for (
  609. let attempt = 0;
  610. attempt < RECOVERY_POLL_ATTEMPTS &&
  611. adapter.getToolSnapshot().runtime?.status.status !== "connected";
  612. attempt += 1
  613. )
  614. await new Promise((resolve) => setTimeout(resolve, RECOVERY_POLL_INTERVAL_MS));
  615. await expect(
  616. adapter.callTool({ serverName: "runtime", toolName: "oauth_ping" }),
  617. ).resolves.toMatchObject({ isError: false });
  618. expect(registrationRequests).toHaveLength(1);
  619. expect(authorizationRequests).toHaveLength(1);
  620. } finally {
  621. await adapter.close();
  622. await rm(credentialsDir, { force: true, recursive: true });
  623. }
  624. });
  625. it("steps up authorization scope with the union of configured, granted, and challenged scopes", async () => {
  626. const authorizationRequests: Array<Record<string, string>> = [];
  627. const authTokenRequests: Array<Record<string, string>> = [];
  628. const mcpAuthorizations: string[] = [];
  629. const registrationRequests: Array<Record<string, unknown>> = [];
  630. const pkceChallenges = new Map<string, string>();
  631. const STEP_UP_SCOPE = "admin:tools";
  632. let authBaseUrl = "";
  633. const authServer = await listen(
  634. createServer(async (req, res) => {
  635. await handleAuthorizationCodeAuthServerRequest(req, res, {
  636. authBaseUrl,
  637. authorizationRequests,
  638. pkceChallenges,
  639. registrationRequests,
  640. tokenRequests: authTokenRequests,
  641. });
  642. }),
  643. );
  644. authBaseUrl = serverBaseUrl(authServer);
  645. let mcpUrl = "";
  646. let stepUpRequired = true;
  647. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  648. const mcpServer = await listen(
  649. createServer(async (req, res) => {
  650. await handleProtectedMcpRequest(req, res, {
  651. authBaseUrl,
  652. authorizations: mcpAuthorizations,
  653. mcpUrl,
  654. resourceMetadataPath,
  655. ...(stepUpRequired ? { stepUpScope: STEP_UP_SCOPE } : {}),
  656. });
  657. }),
  658. );
  659. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  660. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-stepup-"));
  661. const credentialStore = createSharedZCodeCredentialStore({
  662. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-stepup-secret" },
  663. filePath: join(credentialsDir, "credentials.json"),
  664. });
  665. const oauthConfig = { type: "authorization_code" as const, scope: MCP_SCOPE };
  666. const keyPrefix = createCredentialKeyPrefix("stepup", mcpUrl, oauthConfig);
  667. // 现存凭据:token 有效、已授予 mcp:tools,但服务端现在要求 admin:tools。
  668. await publishCanonicalCredentials(credentialStore, keyPrefix, {
  669. clientInformation: { client_id: "stepup-client" },
  670. publishedBy: "stepup-seed",
  671. tokens: {
  672. access_token: OAUTH_ACCESS_TOKEN,
  673. expires_in: 3600,
  674. scope: MCP_SCOPE,
  675. token_type: "Bearer",
  676. },
  677. });
  678. const adapter = createMcpAdapter({
  679. mcpOAuth: {
  680. credentialStore,
  681. openAuthorizationUrl: async ({ authorizationUrl }) => {
  682. stepUpRequired = false;
  683. await followAuthorizationRedirect(authorizationUrl);
  684. },
  685. },
  686. });
  687. try {
  688. const status = await adapter.connectServer("stepup", {
  689. type: "http",
  690. url: mcpUrl,
  691. oauth: oauthConfig,
  692. });
  693. expect(status).toMatchObject({ status: "connected", toolCount: 1 });
  694. // 修复原因(spec §5.2,复核 P1):只带 challenge scope 重新授权时,授权服务器可能按新请求
  695. // 收回先前授予的 scope,下一个请求换个 challenge 又 403,形成重授权乒乓。重新授权请求
  696. // 必须携带 config ∪ token.scope ∪ challenge 的并集,且 DCR 注册同一个值。
  697. expect(authorizationRequests).toHaveLength(1);
  698. expect(authorizationRequests[0]?.scope).toBe(`${MCP_SCOPE} ${STEP_UP_SCOPE}`);
  699. expect(registrationRequests).toHaveLength(1);
  700. expect(registrationRequests[0]?.scope).toBe(`${MCP_SCOPE} ${STEP_UP_SCOPE}`);
  701. // challenge 携带的 resource_metadata 要传导为授权请求的 resource 受众参数。
  702. expect(authorizationRequests[0]?.resource).toBe(mcpUrl);
  703. expect(authTokenRequests).toHaveLength(1);
  704. } finally {
  705. await adapter.close();
  706. await rm(credentialsDir, { force: true, recursive: true });
  707. }
  708. });
  709. it("binds dynamically registered client information to each OAuth transaction", async () => {
  710. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-client-transaction-"));
  711. const credentialStore = createSharedZCodeCredentialStore({
  712. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-client-transaction-secret" },
  713. filePath: join(credentialsDir, "credentials.json"),
  714. });
  715. const sessions: McpOAuthSession[] = [];
  716. try {
  717. const sessionA = await createTestOAuthSession(credentialStore, "transaction-a");
  718. const sessionB = await createTestOAuthSession(credentialStore, "transaction-b");
  719. sessions.push(sessionA, sessionB);
  720. const clientA = dynamicClientInformation("transaction-client-a");
  721. const clientB = dynamicClientInformation("transaction-client-b");
  722. await saveDynamicClientInformation(sessionA, clientA);
  723. await saveDynamicClientInformation(sessionB, clientB);
  724. await expect(sessionA.provider.clientInformation()).resolves.toEqual(clientA);
  725. await expect(sessionB.provider.clientInformation()).resolves.toEqual(clientB);
  726. } finally {
  727. await Promise.all(sessions.map((session) => session.close()));
  728. await rm(credentialsDir, { force: true, recursive: true });
  729. }
  730. });
  731. it("restores dynamically registered client information after provider reconstruction", async () => {
  732. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-client-recovery-"));
  733. const credentialStore = createSharedZCodeCredentialStore({
  734. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-client-recovery-secret" },
  735. filePath: join(credentialsDir, "credentials.json"),
  736. });
  737. const sessions: McpOAuthSession[] = [];
  738. try {
  739. const registered = await createTestOAuthSession(credentialStore, "recovery-registered");
  740. sessions.push(registered);
  741. const client = dynamicClientInformation("recovery-client");
  742. await saveDynamicClientInformation(registered, client);
  743. await registered.close();
  744. sessions.splice(sessions.indexOf(registered), 1);
  745. const reconstructed = await createTestOAuthSession(credentialStore, "recovery-reconstructed");
  746. sessions.push(reconstructed);
  747. await expect(reconstructed.provider.clientInformation()).resolves.toEqual(client);
  748. } finally {
  749. await Promise.all(sessions.map((session) => session.close()));
  750. await rm(credentialsDir, { force: true, recursive: true });
  751. }
  752. });
  753. it("retries credential snapshots after a transient load failure", async () => {
  754. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-load-retry-"));
  755. const credentialStore = createSharedZCodeCredentialStore({
  756. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-load-retry-secret" },
  757. filePath: join(credentialsDir, "credentials.json"),
  758. });
  759. const sessions: McpOAuthSession[] = [];
  760. try {
  761. const publisher = await createTestOAuthSession(credentialStore, "load-retry-publisher");
  762. sessions.push(publisher);
  763. const client = dynamicClientInformation("load-retry-client");
  764. const tokens = oauthTokens("load-retry-client");
  765. await saveDynamicClientInformation(publisher, client);
  766. await publisher.provider.saveTokens(tokens);
  767. let loadAttempts = 0;
  768. const transientFailure = new Error("injected transient credential load failure");
  769. const retryingStore: SharedZCodeCredentialStore = {
  770. ...credentialStore,
  771. async loadMany(keys: string[]): Promise<Record<string, string | null>> {
  772. loadAttempts += 1;
  773. if (loadAttempts === 1) throw transientFailure;
  774. return await credentialStore.loadMany(keys);
  775. },
  776. };
  777. const reader = await createTestOAuthSession(retryingStore, "load-retry-reader");
  778. sessions.push(reader);
  779. await expect(reader.provider.tokens()).rejects.toThrow(transientFailure.message);
  780. await expect(reader.provider.tokens()).resolves.toEqual(tokens);
  781. await expect(reader.provider.clientInformation()).resolves.toEqual(client);
  782. expect(loadAttempts).toBe(2);
  783. } finally {
  784. await Promise.all(sessions.map((session) => session.close()));
  785. await rm(credentialsDir, { force: true, recursive: true });
  786. }
  787. });
  788. it("does not fail session close when verifier cleanup fails", async () => {
  789. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-close-cleanup-"));
  790. const credentialStore = createSharedZCodeCredentialStore({
  791. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-close-cleanup-secret" },
  792. filePath: join(credentialsDir, "credentials.json"),
  793. });
  794. const cleanupError = new Error("injected verifier cleanup failure");
  795. const failingStore: SharedZCodeCredentialStore = {
  796. ...credentialStore,
  797. async delete(key: string): Promise<void> {
  798. if (key.includes(":code_verifier:")) throw cleanupError;
  799. await credentialStore.delete(key);
  800. },
  801. };
  802. const { logger, warn } = createTestLogger();
  803. const session = await createMcpAuthorizationCodeOAuthSession({
  804. adapterInstanceId: "close-cleanup",
  805. config: testAuthorizationCodeConfig(),
  806. logger,
  807. options: { credentialStore: failingStore },
  808. serverName: "credential-pair-test",
  809. serverUrl: "https://mcp.example.test/mcp",
  810. });
  811. try {
  812. await session.provider.saveCodeVerifier("close-cleanup-verifier");
  813. await expect(session.close()).resolves.toBeUndefined();
  814. expect(warn).toHaveBeenCalledWith(
  815. "MCP OAuth verifier cleanup failed",
  816. expect.objectContaining({
  817. error: cleanupError.message,
  818. event: "mcp.oauth.verifier.cleanup_failed",
  819. mcpServerName: "credential-pair-test",
  820. }),
  821. );
  822. } finally {
  823. await rm(credentialsDir, { force: true, recursive: true });
  824. }
  825. });
  826. it("publishes client information and tokens as one credential snapshot", async () => {
  827. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-client-token-pair-"));
  828. const credentialStore = createSharedZCodeCredentialStore({
  829. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-client-token-pair-secret" },
  830. filePath: join(credentialsDir, "credentials.json"),
  831. });
  832. const sessions: McpOAuthSession[] = [];
  833. try {
  834. const sessionA = await createTestOAuthSession(credentialStore, "pair-a");
  835. const sessionB = await createTestOAuthSession(credentialStore, "pair-b");
  836. sessions.push(sessionA, sessionB);
  837. const clientA = dynamicClientInformation("pair-client-a");
  838. const clientB = dynamicClientInformation("pair-client-b");
  839. const tokensA = oauthTokens("pair-client-a");
  840. const tokensB = oauthTokens("pair-client-b");
  841. await saveDynamicClientInformation(sessionA, clientA);
  842. await saveDynamicClientInformation(sessionB, clientB);
  843. await sessionB.provider.saveTokens(tokensB);
  844. await sessionA.provider.saveTokens(tokensA);
  845. const reader = await createTestOAuthSession(credentialStore, "pair-reader");
  846. sessions.push(reader);
  847. await expect(reader.provider.clientInformation()).resolves.toEqual(clientA);
  848. await expect(reader.provider.tokens()).resolves.toEqual(tokensA);
  849. } finally {
  850. await Promise.all(sessions.map((session) => session.close()));
  851. await rm(credentialsDir, { force: true, recursive: true });
  852. }
  853. });
  854. it("preserves v1 canonical credentials across legacy migration states", async () => {
  855. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-v1-migration-"));
  856. const credentialStore = createSharedZCodeCredentialStore({
  857. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-v1-migration-secret" },
  858. filePath: join(credentialsDir, "credentials.json"),
  859. });
  860. const sessions: McpOAuthSession[] = [];
  861. const config = testAuthorizationCodeConfig();
  862. const serverUrl = "https://mcp.example.test/mcp";
  863. const keyPrefix = createCredentialKeyPrefix("credential-pair-test", serverUrl, config);
  864. const canonicalKey = `${keyPrefix}:authorization_credentials`;
  865. const legacyClientKey = `${keyPrefix}:client_information`;
  866. const legacyTokensKey = `${keyPrefix}:tokens`;
  867. const canonicalClient = dynamicClientInformation("v1-canonical-client");
  868. const canonicalTokens = oauthTokens("v1-canonical-client");
  869. const canonicalRaw = JSON.stringify({
  870. client_information: canonicalClient,
  871. expires_at: Date.now() + 3_600_000,
  872. published_by: "v1-publisher",
  873. tokens: canonicalTokens,
  874. version: 1,
  875. });
  876. try {
  877. // v1 发布时会删除 legacy 镜像;无镜像是正常稳态,不能因此丢弃 canonical token。
  878. await credentialStore.save(canonicalKey, canonicalRaw);
  879. const canonicalReader = await createTestOAuthSession(credentialStore, "v1-canonical-reader");
  880. sessions.push(canonicalReader);
  881. await expect(canonicalReader.provider.clientInformation()).resolves.toEqual(canonicalClient);
  882. await expect(canonicalReader.provider.tokens()).resolves.toEqual(canonicalTokens);
  883. const phaseOneProvider = createMcpOAuthTokenProvider({
  884. config,
  885. credentialStore,
  886. keyPrefix,
  887. serverName: "credential-pair-test",
  888. serverUrl,
  889. });
  890. await expect(phaseOneProvider.token()).resolves.toBe(canonicalTokens.access_token);
  891. // 旧 provider 可能只写回 refresh 后的 tokens;缺少 legacy client 时复用 canonical 身份。
  892. const tokenOnlyRefresh = {
  893. ...canonicalTokens,
  894. access_token: "v1-token-only-refreshed-access-token",
  895. };
  896. await credentialStore.save(legacyTokensKey, JSON.stringify(tokenOnlyRefresh));
  897. const tokenOnlyReader = await createTestOAuthSession(credentialStore, "v1-token-only-reader");
  898. sessions.push(tokenOnlyReader);
  899. await expect(tokenOnlyReader.provider.clientInformation()).resolves.toEqual(canonicalClient);
  900. await expect(tokenOnlyReader.provider.tokens()).resolves.toEqual(tokenOnlyRefresh);
  901. // legacy client 与 canonical 身份一致时,可以确认 tokens 属于同一 client 的更新。
  902. const matchingRefresh = {
  903. ...canonicalTokens,
  904. access_token: "v1-matching-refreshed-access-token",
  905. };
  906. await credentialStore.saveMany({
  907. [legacyClientKey]: JSON.stringify(canonicalClient),
  908. [legacyTokensKey]: JSON.stringify(matchingRefresh),
  909. });
  910. const matchingReader = await createTestOAuthSession(credentialStore, "v1-matching-reader");
  911. sessions.push(matchingReader);
  912. await expect(matchingReader.provider.clientInformation()).resolves.toEqual(canonicalClient);
  913. await expect(matchingReader.provider.tokens()).resolves.toEqual(matchingRefresh);
  914. // legacy client 身份不一致时无法确认 token 归属,必须保留完整 canonical pair。
  915. const mismatchedClient = dynamicClientInformation("v1-mismatched-client");
  916. const mismatchedTokens = oauthTokens("v1-mismatched-client");
  917. await credentialStore.saveMany({
  918. [legacyClientKey]: JSON.stringify(mismatchedClient),
  919. [legacyTokensKey]: JSON.stringify(mismatchedTokens),
  920. });
  921. const mismatchedReader = await createTestOAuthSession(
  922. credentialStore,
  923. "v1-mismatched-reader",
  924. );
  925. sessions.push(mismatchedReader);
  926. await expect(mismatchedReader.provider.clientInformation()).resolves.toEqual(canonicalClient);
  927. await expect(mismatchedReader.provider.tokens()).resolves.toEqual(canonicalTokens);
  928. } finally {
  929. await Promise.all(sessions.map((session) => session.close()));
  930. await rm(credentialsDir, { force: true, recursive: true });
  931. }
  932. });
  933. it("keeps legacy readers and writers coherent during the canonical migration window", async () => {
  934. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-mixed-version-"));
  935. const credentialStore = createSharedZCodeCredentialStore({
  936. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-mixed-version-secret" },
  937. filePath: join(credentialsDir, "credentials.json"),
  938. });
  939. const sessions: McpOAuthSession[] = [];
  940. const config = testAuthorizationCodeConfig();
  941. const keyPrefix = createCredentialKeyPrefix(
  942. "credential-pair-test",
  943. "https://mcp.example.test/mcp",
  944. config,
  945. );
  946. const legacyClientKey = `${keyPrefix}:client_information`;
  947. const legacyTokensKey = `${keyPrefix}:tokens`;
  948. const client = dynamicClientInformation("mixed-version-client");
  949. const initialTokens = oauthTokens("mixed-version-client");
  950. const reauthorizedClient = dynamicClientInformation("mixed-version-reauthorized-client");
  951. const reauthorizedTokens = oauthTokens("mixed-version-reauthorized-client");
  952. const refreshedByLegacy = {
  953. ...reauthorizedTokens,
  954. access_token: "mixed-version-reauthorized-client-legacy-refreshed-access-token",
  955. };
  956. try {
  957. const publisher = await createTestOAuthSession(credentialStore, "mixed-version-publisher");
  958. sessions.push(publisher);
  959. await saveDynamicClientInformation(publisher, client);
  960. await publisher.provider.saveTokens(initialTokens);
  961. // 目标分支旧 provider 只认识这两个 legacy key,发布后必须仍能读取同一 pair。
  962. await expect(credentialStore.load(legacyClientKey)).resolves.toBe(JSON.stringify(client));
  963. await expect(credentialStore.load(legacyTokensKey)).resolves.toBe(
  964. JSON.stringify(initialTokens),
  965. );
  966. // 旧 provider 的 DCR 与 token exchange 不是同一次写入;只更新 client 时仍须读取旧 canonical pair。
  967. await credentialStore.save(legacyClientKey, JSON.stringify(reauthorizedClient));
  968. const pendingReader = await createTestOAuthSession(
  969. credentialStore,
  970. "mixed-version-pending-reader",
  971. );
  972. sessions.push(pendingReader);
  973. await expect(pendingReader.provider.clientInformation()).resolves.toEqual(client);
  974. await expect(pendingReader.provider.tokens()).resolves.toEqual(initialTokens);
  975. // legacy 没有 generation;client/token 都变化时无法区分已完成重授权与跨事务交错。
  976. // 新 provider 保留 client 但丢弃不可信 token,完成自己的 token exchange 后再发布 pair。
  977. await credentialStore.save(legacyTokensKey, JSON.stringify(reauthorizedTokens));
  978. const reauthorizedReader = await createTestOAuthSession(
  979. credentialStore,
  980. "mixed-version-reauthorized-reader",
  981. );
  982. sessions.push(reauthorizedReader);
  983. await expect(reauthorizedReader.provider.clientInformation()).resolves.toEqual(
  984. reauthorizedClient,
  985. );
  986. await expect(reauthorizedReader.provider.tokens()).resolves.toBeUndefined();
  987. await reauthorizedReader.provider.saveTokens(reauthorizedTokens);
  988. // 模拟旧 provider refresh:它只更新 legacy tokens,新 provider 不得继续读取 stale canonical。
  989. await credentialStore.save(legacyTokensKey, JSON.stringify(refreshedByLegacy));
  990. const refreshedReader = await createTestOAuthSession(
  991. credentialStore,
  992. "mixed-version-refreshed-reader",
  993. );
  994. sessions.push(refreshedReader);
  995. await expect(refreshedReader.provider.clientInformation()).resolves.toEqual(
  996. reauthorizedClient,
  997. );
  998. await expect(refreshedReader.provider.tokens()).resolves.toEqual(refreshedByLegacy);
  999. // 模拟旧 provider invalidate tokens:canonical 不能把已失效 token 复活。
  1000. await credentialStore.delete(legacyTokensKey);
  1001. const invalidatedReader = await createTestOAuthSession(
  1002. credentialStore,
  1003. "mixed-version-invalidated-reader",
  1004. );
  1005. sessions.push(invalidatedReader);
  1006. await expect(invalidatedReader.provider.clientInformation()).resolves.toEqual(
  1007. reauthorizedClient,
  1008. );
  1009. await expect(invalidatedReader.provider.tokens()).resolves.toBeUndefined();
  1010. } finally {
  1011. await Promise.all(sessions.map((session) => session.close()));
  1012. await rm(credentialsDir, { force: true, recursive: true });
  1013. }
  1014. });
  1015. it("does not combine a pending legacy client with another legacy refresh", async () => {
  1016. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-legacy-race-"));
  1017. const credentialStore = createSharedZCodeCredentialStore({
  1018. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-legacy-race-secret" },
  1019. filePath: join(credentialsDir, "credentials.json"),
  1020. });
  1021. const sessions: McpOAuthSession[] = [];
  1022. const config = testAuthorizationCodeConfig();
  1023. const keyPrefix = createCredentialKeyPrefix(
  1024. "credential-pair-test",
  1025. "https://mcp.example.test/mcp",
  1026. config,
  1027. );
  1028. const clientA = dynamicClientInformation("legacy-race-client-a");
  1029. const tokensA = oauthTokens("legacy-race-client-a");
  1030. const pendingClientB = dynamicClientInformation("legacy-race-client-b");
  1031. const refreshedTokensA = {
  1032. ...tokensA,
  1033. access_token: "legacy-race-client-a-refreshed-access-token",
  1034. };
  1035. try {
  1036. const publisher = await createTestOAuthSession(credentialStore, "legacy-race-publisher");
  1037. sessions.push(publisher);
  1038. await saveDynamicClientInformation(publisher, clientA);
  1039. await publisher.provider.saveTokens(tokensA);
  1040. // 旧 provider B 只完成动态注册;旧 provider A 随后只刷新 token。两次独立写入
  1041. // 没有 generation 可证明归属,新 reader 不能把 client B 与 token A2 拼成一对。
  1042. await credentialStore.save(`${keyPrefix}:client_information`, JSON.stringify(pendingClientB));
  1043. await credentialStore.save(`${keyPrefix}:tokens`, JSON.stringify(refreshedTokensA));
  1044. const reader = await createTestOAuthSession(credentialStore, "legacy-race-reader");
  1045. sessions.push(reader);
  1046. await expect(reader.provider.clientInformation()).resolves.toEqual(pendingClientB);
  1047. await expect(reader.provider.tokens()).resolves.toBeUndefined();
  1048. } finally {
  1049. await Promise.all(sessions.map((session) => session.close()));
  1050. await rm(credentialsDir, { force: true, recursive: true });
  1051. }
  1052. });
  1053. it("does not invalidate a credential snapshot replaced by another transaction", async () => {
  1054. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-compare-delete-"));
  1055. const credentialStore = createSharedZCodeCredentialStore({
  1056. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-compare-delete-secret" },
  1057. filePath: join(credentialsDir, "credentials.json"),
  1058. });
  1059. const sessions: McpOAuthSession[] = [];
  1060. try {
  1061. const publisherA = await createTestOAuthSession(credentialStore, "publisher-a");
  1062. const staleReader = await createTestOAuthSession(credentialStore, "stale-reader");
  1063. const publisherB = await createTestOAuthSession(credentialStore, "publisher-b");
  1064. sessions.push(publisherA, staleReader, publisherB);
  1065. const clientA = dynamicClientInformation("published-client-a");
  1066. const tokensA = oauthTokens("published-client-a");
  1067. const clientB = dynamicClientInformation("published-client-b");
  1068. const tokensB = oauthTokens("published-client-b");
  1069. await saveDynamicClientInformation(publisherA, clientA);
  1070. await publisherA.provider.saveTokens(tokensA);
  1071. await expect(staleReader.provider.clientInformation()).resolves.toEqual(clientA);
  1072. await expect(staleReader.provider.tokens()).resolves.toEqual(tokensA);
  1073. await saveDynamicClientInformation(publisherB, clientB);
  1074. await publisherB.provider.saveTokens(tokensB);
  1075. await staleReader.provider.invalidateCredentials?.("tokens");
  1076. // 同一个失败 provider 的 SDK 重试也必须丢弃旧 client 缓存并读取获胜事务的 pair。
  1077. await expect(staleReader.provider.clientInformation()).resolves.toEqual(clientB);
  1078. await expect(staleReader.provider.tokens()).resolves.toEqual(tokensB);
  1079. const verifier = await createTestOAuthSession(credentialStore, "compare-delete-verifier");
  1080. sessions.push(verifier);
  1081. await expect(verifier.provider.clientInformation()).resolves.toEqual(clientB);
  1082. await expect(verifier.provider.tokens()).resolves.toEqual(tokensB);
  1083. } finally {
  1084. await Promise.all(sessions.map((session) => session.close()));
  1085. await rm(credentialsDir, { force: true, recursive: true });
  1086. }
  1087. });
  1088. it("refreshes the last concurrently published canonical pair with one client identity", async () => {
  1089. const authorizationRequests: Array<Record<string, string>> = [];
  1090. const tokenRequests: Array<Record<string, string>> = [];
  1091. const registrationRequests: Array<Record<string, unknown>> = [];
  1092. const pkceChallenges = new Map<string, string>();
  1093. const strictAuthorizationState = createStrictAuthorizationServerState();
  1094. let authBaseUrl = "";
  1095. const authServer = await listen(
  1096. createServer(async (req, res) => {
  1097. await handleAuthorizationCodeAuthServerRequest(req, res, {
  1098. authBaseUrl,
  1099. authorizationRequests,
  1100. pkceChallenges,
  1101. registrationRequests,
  1102. strictAuthorizationState,
  1103. tokenRequests,
  1104. });
  1105. }),
  1106. );
  1107. authBaseUrl = serverBaseUrl(authServer);
  1108. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-refresh-pair-"));
  1109. const credentialStore = createSharedZCodeCredentialStore({
  1110. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-refresh-pair-secret" },
  1111. filePath: join(credentialsDir, "credentials.json"),
  1112. });
  1113. const sessions: McpOAuthSession[] = [];
  1114. const clientA = dynamicClientInformation("refresh-pair-client-a");
  1115. const tokensA = oauthTokens("refresh-pair-client-a");
  1116. const clientB = dynamicClientInformation("refresh-pair-client-b");
  1117. const tokensB = oauthTokens("refresh-pair-client-b");
  1118. for (const [client, tokens] of [
  1119. [clientA, tokensA],
  1120. [clientB, tokensB],
  1121. ] as const) {
  1122. strictAuthorizationState.clients.set(client.client_id, {
  1123. clientSecret: client.client_secret ?? "",
  1124. redirectUris: [],
  1125. });
  1126. strictAuthorizationState.refreshTokens.set(tokens.refresh_token ?? "", client.client_id);
  1127. }
  1128. try {
  1129. const publisherA = await createTestOAuthSession(
  1130. credentialStore,
  1131. "refresh-publisher-a",
  1132. `${authBaseUrl}/mcp`,
  1133. );
  1134. const publisherB = await createTestOAuthSession(
  1135. credentialStore,
  1136. "refresh-publisher-b",
  1137. `${authBaseUrl}/mcp`,
  1138. );
  1139. sessions.push(publisherA, publisherB);
  1140. await saveDynamicClientInformation(publisherA, clientA);
  1141. await saveDynamicClientInformation(publisherB, clientB);
  1142. await publisherB.provider.saveTokens(tokensB);
  1143. await publisherA.provider.saveTokens(tokensA);
  1144. const reader = await createTestOAuthSession(
  1145. credentialStore,
  1146. "refresh-reader",
  1147. `${authBaseUrl}/mcp`,
  1148. );
  1149. sessions.push(reader);
  1150. await expect(auth(reader.provider, { serverUrl: `${authBaseUrl}/mcp` })).resolves.toBe(
  1151. "AUTHORIZED",
  1152. );
  1153. expect(authorizationRequests).toHaveLength(0);
  1154. expect(registrationRequests).toHaveLength(0);
  1155. expect(tokenRequests).toEqual([
  1156. expect.objectContaining({
  1157. client_id: clientA.client_id,
  1158. grant_type: "refresh_token",
  1159. refresh_token: tokensA.refresh_token,
  1160. }),
  1161. ]);
  1162. await expect(reader.provider.clientInformation()).resolves.toEqual(clientA);
  1163. await expect(reader.provider.tokens()).resolves.toMatchObject({
  1164. access_token: `${clientA.client_id}-refreshed-access-token`,
  1165. refresh_token: tokensA.refresh_token,
  1166. });
  1167. } finally {
  1168. await Promise.all(sessions.map((session) => session.close()));
  1169. await rm(credentialsDir, { force: true, recursive: true });
  1170. }
  1171. });
  1172. it("preserves a canonical credential snapshot written by a newer version", async () => {
  1173. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-future-credentials-"));
  1174. const credentialStore = createSharedZCodeCredentialStore({
  1175. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-future-credentials-secret" },
  1176. filePath: join(credentialsDir, "credentials.json"),
  1177. });
  1178. const sessions: McpOAuthSession[] = [];
  1179. const keyPrefix = createCredentialKeyPrefix(
  1180. "credential-pair-test",
  1181. "https://mcp.example.test/mcp",
  1182. testAuthorizationCodeConfig(),
  1183. );
  1184. const futureSnapshot = JSON.stringify({
  1185. client_information: dynamicClientInformation("future-client"),
  1186. published_by: "future-publisher",
  1187. tokens: oauthTokens("future-client"),
  1188. version: 3,
  1189. });
  1190. try {
  1191. await credentialStore.save(`${keyPrefix}:authorization_credentials`, futureSnapshot);
  1192. const session = await createTestOAuthSession(credentialStore, "future-reader");
  1193. sessions.push(session);
  1194. // 未知版本必须保留原值:CLI 与 desktop 独立升级、共享同一份凭据文件,旧版本不能把新版本
  1195. // 写入的 canonical pair 当损坏数据删除。没有可用 client 时改为要求交互授权(PR2 过渡 seam),
  1196. // 而不是返回 undefined 让 SDK 自行做一次动态注册。
  1197. await expect(session.provider.clientInformation()).rejects.toMatchObject({
  1198. code: MCP_OAUTH_INTERACTIVE_REQUIRED_ERROR_CODE,
  1199. reason: "no_credentials",
  1200. });
  1201. await expect(session.provider.tokens()).resolves.toBeUndefined();
  1202. await expect(credentialStore.load(`${keyPrefix}:authorization_credentials`)).resolves.toBe(
  1203. futureSnapshot,
  1204. );
  1205. } finally {
  1206. await Promise.all(sessions.map((session) => session.close()));
  1207. await rm(credentialsDir, { force: true, recursive: true });
  1208. }
  1209. });
  1210. it("removes both legacy credential halves when the legacy client is invalid", async () => {
  1211. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-legacy-invalidation-"));
  1212. const credentialStore = createSharedZCodeCredentialStore({
  1213. env: { ZCODE_CREDENTIAL_SECRET: "mcp-oauth-legacy-invalidation-secret" },
  1214. filePath: join(credentialsDir, "credentials.json"),
  1215. });
  1216. const sessions: McpOAuthSession[] = [];
  1217. const config = testAuthorizationCodeConfig();
  1218. const keyPrefix = createCredentialKeyPrefix(
  1219. "credential-pair-test",
  1220. "https://mcp.example.test/mcp",
  1221. config,
  1222. );
  1223. try {
  1224. await credentialStore.save(
  1225. `${keyPrefix}:client_information`,
  1226. JSON.stringify(dynamicClientInformation("legacy-client")),
  1227. );
  1228. await credentialStore.save(
  1229. `${keyPrefix}:tokens`,
  1230. JSON.stringify(oauthTokens("legacy-client")),
  1231. );
  1232. const session = await createTestOAuthSession(credentialStore, "legacy-invalidation");
  1233. sessions.push(session);
  1234. await expect(session.provider.clientInformation()).resolves.toBeDefined();
  1235. await expect(session.provider.tokens()).resolves.toBeDefined();
  1236. await session.provider.invalidateCredentials?.("client");
  1237. await expect(credentialStore.load(`${keyPrefix}:client_information`)).resolves.toBeNull();
  1238. await expect(credentialStore.load(`${keyPrefix}:tokens`)).resolves.toBeNull();
  1239. } finally {
  1240. await Promise.all(sessions.map((session) => session.close()));
  1241. await rm(credentialsDir, { force: true, recursive: true });
  1242. }
  1243. });
  1244. it("discovers authorization_code OAuth for a bare HTTP MCP config", async () => {
  1245. const authorizationRequests: Array<Record<string, string>> = [];
  1246. const authTokenRequests: Array<Record<string, string>> = [];
  1247. const mcpAuthorizations: string[] = [];
  1248. const registrationRequests: Array<Record<string, unknown>> = [];
  1249. const pkceChallenges = new Map<string, string>();
  1250. let authBaseUrl = "";
  1251. const authServer = await listen(
  1252. createServer(async (req, res) => {
  1253. await handleAuthorizationCodeAuthServerRequest(req, res, {
  1254. authBaseUrl,
  1255. authorizationRequests,
  1256. pkceChallenges,
  1257. registrationRequests,
  1258. tokenRequests: authTokenRequests,
  1259. });
  1260. }),
  1261. );
  1262. authBaseUrl = serverBaseUrl(authServer);
  1263. let mcpUrl = "";
  1264. const resourceMetadataPath = "/.well-known/oauth-protected-resource/mcp";
  1265. const mcpServer = await listen(
  1266. createServer(async (req, res) => {
  1267. await handleProtectedMcpRequest(req, res, {
  1268. authBaseUrl,
  1269. authorizations: mcpAuthorizations,
  1270. mcpUrl,
  1271. resourceMetadataPath,
  1272. });
  1273. }),
  1274. );
  1275. mcpUrl = `${serverBaseUrl(mcpServer)}/mcp`;
  1276. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-auto-"));
  1277. const credentialStore = createSharedZCodeCredentialStore({
  1278. env: {
  1279. ZCODE_CREDENTIAL_SECRET: "mcp-oauth-e2e-secret",
  1280. },
  1281. filePath: join(credentialsDir, "credentials.json"),
  1282. });
  1283. const adapter = createMcpAdapter({
  1284. mcpOAuth: {
  1285. authorizationTimeoutMs: 5_000,
  1286. credentialStore,
  1287. openAuthorizationUrl: async ({ authorizationUrl }) => {
  1288. const authorizationResponse = await fetch(authorizationUrl, {
  1289. redirect: "manual",
  1290. });
  1291. expect(authorizationResponse.status).toBe(302);
  1292. const location = authorizationResponse.headers.get("location");
  1293. if (!location) {
  1294. throw new Error("Authorization server did not redirect to callback URL");
  1295. }
  1296. const callbackResponse = await fetch(location);
  1297. expect(callbackResponse.status).toBe(200);
  1298. },
  1299. },
  1300. });
  1301. try {
  1302. const status = await adapter.connectServer("notion", {
  1303. type: "http",
  1304. url: mcpUrl,
  1305. });
  1306. expect(status).toMatchObject({
  1307. status: "connected",
  1308. toolCount: 1,
  1309. transport: "http",
  1310. });
  1311. await expect(adapter.listTools()).resolves.toMatchObject([
  1312. {
  1313. serverName: "notion",
  1314. toolName: "oauth_ping",
  1315. },
  1316. ]);
  1317. expect(registrationRequests).toHaveLength(1);
  1318. expect(registrationRequests[0]).toMatchObject({
  1319. client_name: "ZCode notion",
  1320. grant_types: ["authorization_code", "refresh_token"],
  1321. response_types: ["code"],
  1322. scope: MCP_SCOPE,
  1323. });
  1324. expect(authorizationRequests).toEqual([
  1325. expect.objectContaining({
  1326. client_id: DYNAMIC_CLIENT_ID,
  1327. resource: mcpUrl,
  1328. response_type: "code",
  1329. scope: MCP_SCOPE,
  1330. }),
  1331. ]);
  1332. expect(authTokenRequests).toEqual([
  1333. expect.objectContaining({
  1334. code: "interactive-code-1",
  1335. grant_type: "authorization_code",
  1336. resource: mcpUrl,
  1337. }),
  1338. ]);
  1339. expect(mcpAuthorizations).toContain(`Bearer ${OAUTH_ACCESS_TOKEN}`);
  1340. } finally {
  1341. await adapter.close();
  1342. await rm(credentialsDir, { force: true, recursive: true });
  1343. }
  1344. });
  1345. it("isolates persisted authorization_code credentials by authorization config", async () => {
  1346. const credentialsDir = await mkdtemp(join(tmpdir(), "zcode-mcp-oauth-"));
  1347. const credentialStore = createSharedZCodeCredentialStore({
  1348. env: {
  1349. ZCODE_CREDENTIAL_SECRET: "mcp-oauth-e2e-secret",
  1350. },
  1351. filePath: join(credentialsDir, "credentials.json"),
  1352. });
  1353. const serverName = "figma";
  1354. const serverUrl = "https://mcp.example.test/mcp";
  1355. const keyPrefixA = createCredentialKeyPrefix(serverName, serverUrl, {
  1356. type: "authorization_code",
  1357. clientName: "ZCode Test",
  1358. scope: MCP_SCOPE,
  1359. });
  1360. const keyPrefixB = createCredentialKeyPrefix(serverName, serverUrl, {
  1361. type: "authorization_code",
  1362. clientName: "ZCode Test",
  1363. scope: "mcp:tools:readonly",
  1364. });
  1365. try {
  1366. await credentialStore.save(
  1367. `${keyPrefixA}:client_information`,
  1368. JSON.stringify({
  1369. client_id: DYNAMIC_CLIENT_ID,
  1370. client_secret: DYNAMIC_CLIENT_SECRET,
  1371. }),
  1372. );
  1373. await credentialStore.save(
  1374. `${keyPrefixA}:tokens`,
  1375. JSON.stringify({
  1376. access_token: OAUTH_ACCESS_TOKEN,
  1377. refresh_token: "oauth-e2e-refresh-token",
  1378. token_type: "Bearer",
  1379. }),
  1380. );
  1381. expect(keyPrefixB).not.toBe(keyPrefixA);
  1382. await expect(credentialStore.load(`${keyPrefixA}:client_information`)).resolves.toContain(
  1383. DYNAMIC_CLIENT_ID,
  1384. );
  1385. await expect(credentialStore.load(`${keyPrefixA}:tokens`)).resolves.toContain(
  1386. OAUTH_ACCESS_TOKEN,
  1387. );
  1388. await expect(credentialStore.load(`${keyPrefixB}:client_information`)).resolves.toBeNull();
  1389. await expect(credentialStore.load(`${keyPrefixB}:tokens`)).resolves.toBeNull();
  1390. } finally {
  1391. await rm(credentialsDir, { force: true, recursive: true });
  1392. }
  1393. });
  1394. });
  1395. async function handleAuthServerRequest(
  1396. req: IncomingMessage,
  1397. res: ServerResponse,
  1398. options: {
  1399. authBaseUrl: string;
  1400. tokenRequests: Array<Record<string, string>>;
  1401. },
  1402. ): Promise<void> {
  1403. const url = new URL(req.url ?? "/", "http://localhost");
  1404. if (req.method === "GET" && url.pathname === "/.well-known/oauth-authorization-server") {
  1405. sendJson(res, 200, {
  1406. issuer: options.authBaseUrl,
  1407. authorization_endpoint: `${options.authBaseUrl}/authorize`,
  1408. token_endpoint: `${options.authBaseUrl}/token`,
  1409. response_types_supported: ["code"],
  1410. grant_types_supported: ["client_credentials"],
  1411. token_endpoint_auth_methods_supported: ["client_secret_basic"],
  1412. });
  1413. return;
  1414. }
  1415. if (req.method === "POST" && url.pathname === "/token") {
  1416. if (!isValidClientSecretBasic(req.headers.authorization)) {
  1417. sendJson(res, 401, {
  1418. error: "invalid_client",
  1419. });
  1420. return;
  1421. }
  1422. const body = new URLSearchParams(await readRequestBody(req));
  1423. options.tokenRequests.push(Object.fromEntries(body.entries()));
  1424. sendJson(res, 200, {
  1425. access_token: OAUTH_ACCESS_TOKEN,
  1426. expires_in: 3600,
  1427. scope: body.get("scope") ?? MCP_SCOPE,
  1428. token_type: "Bearer",
  1429. });
  1430. return;
  1431. }
  1432. res.writeHead(404);
  1433. res.end();
  1434. }
  1435. async function handleAuthorizationCodeAuthServerRequest(
  1436. req: IncomingMessage,
  1437. res: ServerResponse,
  1438. options: {
  1439. authBaseUrl: string;
  1440. authorizationRequests: Array<Record<string, string>>;
  1441. /**
  1442. * 要求 redirect_uri 与注册值完全一致(含端口)。
  1443. *
  1444. * 默认的 loopback 比较按 RFC 8252 忽略端口,这恰好掩盖了根因 2:真实授权服务器(如
  1445. * auth.exa.ai)可能做精确匹配,失配时按 RFC 6749 §4.1.2.1 禁止回跳、就地渲染错误页。
  1446. */
  1447. exactRedirectUriMatch?: boolean;
  1448. pkceChallenges: Map<string, string>;
  1449. registrationRequests: Array<Record<string, unknown>>;
  1450. strictAuthorizationState?: StrictAuthorizationServerState;
  1451. tokenRequests: Array<Record<string, string>>;
  1452. },
  1453. ): Promise<void> {
  1454. const url = new URL(req.url ?? "/", "http://localhost");
  1455. if (req.method === "GET" && url.pathname === "/.well-known/oauth-authorization-server") {
  1456. sendJson(res, 200, {
  1457. issuer: options.authBaseUrl,
  1458. authorization_endpoint: `${options.authBaseUrl}/authorize`,
  1459. token_endpoint: `${options.authBaseUrl}/token`,
  1460. registration_endpoint: `${options.authBaseUrl}/register`,
  1461. response_types_supported: ["code"],
  1462. grant_types_supported: ["authorization_code", "refresh_token"],
  1463. token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"],
  1464. code_challenge_methods_supported: ["S256"],
  1465. scopes_supported: [MCP_SCOPE],
  1466. });
  1467. return;
  1468. }
  1469. if (req.method === "POST" && url.pathname === "/register") {
  1470. const body = JSON.parse(await readRequestBody(req)) as Record<string, unknown>;
  1471. options.registrationRequests.push(body);
  1472. const registrationIndex = options.registrationRequests.length;
  1473. const clientId = options.strictAuthorizationState
  1474. ? `${DYNAMIC_CLIENT_ID}-${registrationIndex}`
  1475. : DYNAMIC_CLIENT_ID;
  1476. const clientSecret = options.strictAuthorizationState
  1477. ? `${DYNAMIC_CLIENT_SECRET}-${registrationIndex}`
  1478. : DYNAMIC_CLIENT_SECRET;
  1479. if (options.strictAuthorizationState) {
  1480. const redirectUris = Array.isArray(body.redirect_uris)
  1481. ? body.redirect_uris.filter((entry): entry is string => typeof entry === "string")
  1482. : [];
  1483. options.strictAuthorizationState.clients.set(clientId, { clientSecret, redirectUris });
  1484. }
  1485. sendJson(res, 201, {
  1486. ...body,
  1487. client_id: clientId,
  1488. client_secret: clientSecret,
  1489. client_id_issued_at: 1,
  1490. client_secret_expires_at: 0,
  1491. token_endpoint_auth_method: "client_secret_basic",
  1492. });
  1493. return;
  1494. }
  1495. if (req.method === "GET" && url.pathname === "/authorize") {
  1496. options.authorizationRequests.push(Object.fromEntries(url.searchParams.entries()));
  1497. const clientId = url.searchParams.get("client_id") ?? "";
  1498. const redirectUri = url.searchParams.get("redirect_uri");
  1499. const codeChallenge = url.searchParams.get("code_challenge");
  1500. const registeredClient = options.strictAuthorizationState?.clients.get(clientId);
  1501. if (
  1502. !redirectUri ||
  1503. !codeChallenge ||
  1504. url.searchParams.get("code_challenge_method") !== "S256" ||
  1505. (options.strictAuthorizationState &&
  1506. (!registeredClient ||
  1507. !registeredClient.redirectUris.some((registeredUri) =>
  1508. options.exactRedirectUriMatch
  1509. ? redirectUri === registeredUri
  1510. : matchesRegisteredRedirectUri(redirectUri, registeredUri),
  1511. )))
  1512. ) {
  1513. sendJson(res, 400, {
  1514. error: "invalid_request",
  1515. });
  1516. return;
  1517. }
  1518. const authorizationCode = `interactive-code-${options.authorizationRequests.length}`;
  1519. options.pkceChallenges.set(authorizationCode, codeChallenge);
  1520. options.strictAuthorizationState?.authorizationCodes.set(authorizationCode, {
  1521. clientId,
  1522. codeChallenge,
  1523. redirectUri,
  1524. });
  1525. const callbackUrl = new URL(redirectUri);
  1526. callbackUrl.searchParams.set("code", authorizationCode);
  1527. const state = url.searchParams.get("state");
  1528. if (state) callbackUrl.searchParams.set("state", state);
  1529. res.writeHead(302, {
  1530. Location: callbackUrl.toString(),
  1531. });
  1532. res.end();
  1533. return;
  1534. }
  1535. if (req.method === "POST" && url.pathname === "/token") {
  1536. const body = new URLSearchParams(await readRequestBody(req));
  1537. const clientCredentials = parseClientSecretBasic(req.headers.authorization);
  1538. options.tokenRequests.push({
  1539. ...Object.fromEntries(body.entries()),
  1540. ...(clientCredentials ? { client_id: clientCredentials.clientId } : {}),
  1541. });
  1542. if (body.get("grant_type") === "refresh_token") {
  1543. const refreshToken = body.get("refresh_token") ?? "";
  1544. const refreshClientId = options.strictAuthorizationState?.refreshTokens.get(refreshToken);
  1545. const refreshClient = refreshClientId
  1546. ? options.strictAuthorizationState?.clients.get(refreshClientId)
  1547. : undefined;
  1548. if (
  1549. !refreshClientId ||
  1550. !refreshClient ||
  1551. clientCredentials?.clientId !== refreshClientId ||
  1552. clientCredentials.clientSecret !== refreshClient.clientSecret
  1553. ) {
  1554. sendJson(res, 400, { error: "invalid_grant" });
  1555. return;
  1556. }
  1557. sendJson(res, 200, {
  1558. access_token: `${refreshClientId}-refreshed-access-token`,
  1559. expires_in: 3600,
  1560. refresh_token: refreshToken,
  1561. scope: MCP_SCOPE,
  1562. token_type: "Bearer",
  1563. });
  1564. return;
  1565. }
  1566. const authorizationCode = body.get("code") ?? "";
  1567. const codeVerifier = body.get("code_verifier") ?? "";
  1568. const expectedChallenge = options.pkceChallenges.get(authorizationCode);
  1569. const actualChallenge = createHash("sha256").update(codeVerifier).digest("base64url");
  1570. const strictAuthorization =
  1571. options.strictAuthorizationState?.authorizationCodes.get(authorizationCode);
  1572. const strictClient = strictAuthorization
  1573. ? options.strictAuthorizationState?.clients.get(strictAuthorization.clientId)
  1574. : undefined;
  1575. const hasValidClient = options.strictAuthorizationState
  1576. ? Boolean(
  1577. strictAuthorization &&
  1578. strictClient &&
  1579. clientCredentials?.clientId === strictAuthorization.clientId &&
  1580. clientCredentials.clientSecret === strictClient.clientSecret &&
  1581. body.get("redirect_uri") === strictAuthorization.redirectUri,
  1582. )
  1583. : isValidClientSecretBasic(
  1584. req.headers.authorization,
  1585. DYNAMIC_CLIENT_ID,
  1586. DYNAMIC_CLIENT_SECRET,
  1587. );
  1588. if (!hasValidClient) {
  1589. sendJson(res, 400, { error: "invalid_grant" });
  1590. return;
  1591. }
  1592. if (!expectedChallenge || actualChallenge !== expectedChallenge) {
  1593. sendJson(res, 400, { error: "invalid_grant" });
  1594. return;
  1595. }
  1596. options.pkceChallenges.delete(authorizationCode);
  1597. options.strictAuthorizationState?.authorizationCodes.delete(authorizationCode);
  1598. sendJson(res, 200, {
  1599. access_token: OAUTH_ACCESS_TOKEN,
  1600. expires_in: 3600,
  1601. refresh_token: "oauth-e2e-refresh-token",
  1602. scope: MCP_SCOPE,
  1603. token_type: "Bearer",
  1604. });
  1605. return;
  1606. }
  1607. res.writeHead(404);
  1608. res.end();
  1609. }
  1610. async function followAuthorizationRedirect(authorizationUrl: string): Promise<void> {
  1611. const authorizationResponse = await fetch(authorizationUrl, { redirect: "manual" });
  1612. expect(authorizationResponse.status).toBe(302);
  1613. const location = authorizationResponse.headers.get("location");
  1614. if (!location) throw new Error("Authorization server did not redirect to callback URL");
  1615. const callbackResponse = await fetch(location);
  1616. expect(callbackResponse.status).toBe(200);
  1617. }
  1618. async function handleProtectedMcpRequest(
  1619. req: IncomingMessage,
  1620. res: ServerResponse,
  1621. options: {
  1622. authBaseUrl: string;
  1623. authorizations: string[];
  1624. /** 调用方已经消费过请求体时传入,避免二次读取空流。 */
  1625. body?: string;
  1626. mcpUrl: string;
  1627. resourceMetadataPath: string;
  1628. /** 403 insufficient_scope challenge 的 scope;置位时对 tools/list 生效。 */
  1629. stepUpScope?: string;
  1630. },
  1631. ): Promise<void> {
  1632. const url = new URL(req.url ?? "/", "http://localhost");
  1633. if (req.method === "GET" && url.pathname === options.resourceMetadataPath) {
  1634. sendJson(res, 200, {
  1635. authorization_servers: [options.authBaseUrl],
  1636. resource: options.mcpUrl,
  1637. resource_name: "ZCode OAuth E2E MCP",
  1638. scopes_supported: [MCP_SCOPE],
  1639. });
  1640. return;
  1641. }
  1642. if (req.method === "GET" && url.pathname === "/mcp") {
  1643. res.writeHead(405);
  1644. res.end();
  1645. return;
  1646. }
  1647. if (req.method !== "POST" || url.pathname !== "/mcp") {
  1648. res.writeHead(404);
  1649. res.end();
  1650. return;
  1651. }
  1652. const authorization = req.headers.authorization;
  1653. if (authorization) options.authorizations.push(authorization);
  1654. if (authorization !== `Bearer ${OAUTH_ACCESS_TOKEN}`) {
  1655. res.writeHead(401, {
  1656. "WWW-Authenticate": [
  1657. `Bearer resource_metadata="${new URL(options.resourceMetadataPath, options.mcpUrl).href}", scope="${MCP_SCOPE}"`,
  1658. ],
  1659. });
  1660. res.end();
  1661. return;
  1662. }
  1663. const message = JSON.parse(options.body ?? (await readRequestBody(req))) as {
  1664. id?: string | number;
  1665. method?: string;
  1666. };
  1667. // 403 insufficient_scope:Bearer 合法但 scope 不足。challenge 同时带 resource_metadata,
  1668. // 验证编排层把 challenge 的发现线索传进 Phase 2(spec §5.2 / §8 item 15)。
  1669. if (options.stepUpScope && message.method === "tools/list") {
  1670. res.writeHead(403, {
  1671. "WWW-Authenticate": [
  1672. `Bearer error="insufficient_scope", scope="${options.stepUpScope}", resource_metadata="${new URL(options.resourceMetadataPath, options.mcpUrl).href}"`,
  1673. ],
  1674. });
  1675. res.end();
  1676. return;
  1677. }
  1678. if (message.method === "initialize") {
  1679. sendJson(res, 200, {
  1680. id: message.id,
  1681. jsonrpc: "2.0",
  1682. result: {
  1683. capabilities: { tools: {} },
  1684. protocolVersion: "2025-11-25",
  1685. serverInfo: {
  1686. name: "oauth-e2e-mcp",
  1687. version: "1.0.0",
  1688. },
  1689. },
  1690. });
  1691. return;
  1692. }
  1693. if (message.method === "tools/list") {
  1694. sendJson(res, 200, {
  1695. id: message.id,
  1696. jsonrpc: "2.0",
  1697. result: {
  1698. tools: [
  1699. {
  1700. description: "OAuth protected ping",
  1701. inputSchema: {
  1702. properties: {},
  1703. type: "object",
  1704. },
  1705. name: "oauth_ping",
  1706. },
  1707. ],
  1708. },
  1709. });
  1710. return;
  1711. }
  1712. if (message.method === "tools/call") {
  1713. sendJson(res, 200, {
  1714. id: message.id,
  1715. jsonrpc: "2.0",
  1716. result: {
  1717. content: [{ type: "text", text: "pong" }],
  1718. isError: false,
  1719. },
  1720. });
  1721. return;
  1722. }
  1723. if (message.method === "server/discover") {
  1724. sendJson(res, 200, {
  1725. error: {
  1726. code: -32601,
  1727. message: "Method not found",
  1728. },
  1729. id: message.id,
  1730. jsonrpc: "2.0",
  1731. });
  1732. return;
  1733. }
  1734. sendJson(res, 202, {});
  1735. }
  1736. function isValidClientSecretBasic(
  1737. value: string | undefined,
  1738. clientId = OAUTH_CLIENT_ID,
  1739. clientSecret = OAUTH_CLIENT_SECRET,
  1740. ): boolean {
  1741. if (!value?.startsWith("Basic ")) return false;
  1742. const decoded = Buffer.from(value.slice("Basic ".length), "base64").toString("utf8");
  1743. return decoded === `${clientId}:${clientSecret}`;
  1744. }
  1745. function createStrictAuthorizationServerState(): StrictAuthorizationServerState {
  1746. return {
  1747. authorizationCodes: new Map(),
  1748. clients: new Map(),
  1749. refreshTokens: new Map(),
  1750. };
  1751. }
  1752. async function createTestOAuthSession(
  1753. credentialStore: SharedZCodeCredentialStore,
  1754. adapterInstanceId: string,
  1755. serverUrl = "https://mcp.example.test/mcp",
  1756. ): Promise<McpOAuthSession> {
  1757. return await createMcpAuthorizationCodeOAuthSession({
  1758. adapterInstanceId,
  1759. config: testAuthorizationCodeConfig(),
  1760. options: { credentialStore },
  1761. serverName: "credential-pair-test",
  1762. serverUrl,
  1763. });
  1764. }
  1765. function testAuthorizationCodeConfig() {
  1766. return {
  1767. type: "authorization_code" as const,
  1768. clientName: "ZCode Credential Pair Test",
  1769. scope: MCP_SCOPE,
  1770. };
  1771. }
  1772. function dynamicClientInformation(clientId: string): OAuthClientInformationMixed {
  1773. return {
  1774. client_id: clientId,
  1775. client_secret: `${clientId}-secret`,
  1776. token_endpoint_auth_method: "client_secret_basic",
  1777. };
  1778. }
  1779. function oauthTokens(clientId: string): OAuthTokens {
  1780. return {
  1781. access_token: `${clientId}-access-token`,
  1782. refresh_token: `${clientId}-refresh-token`,
  1783. token_type: "Bearer",
  1784. };
  1785. }
  1786. function createTestLogger(): { logger: Logger; warn: ReturnType<typeof vi.fn> } {
  1787. const warn = vi.fn();
  1788. const logger: Logger = {
  1789. child: () => logger,
  1790. debug: vi.fn(),
  1791. error: vi.fn(),
  1792. info: vi.fn(),
  1793. warn,
  1794. };
  1795. return { logger, warn };
  1796. }
  1797. async function saveDynamicClientInformation(
  1798. session: McpOAuthSession,
  1799. clientInformation: OAuthClientInformationMixed,
  1800. ): Promise<void> {
  1801. if (!session.provider.saveClientInformation) {
  1802. throw new Error("OAuth provider does not support dynamic client registration");
  1803. }
  1804. await session.provider.saveClientInformation(clientInformation);
  1805. }
  1806. function parseClientSecretBasic(
  1807. value: string | undefined,
  1808. ): { clientId: string; clientSecret: string } | undefined {
  1809. if (!value?.startsWith("Basic ")) return undefined;
  1810. const decoded = Buffer.from(value.slice("Basic ".length), "base64").toString("utf8");
  1811. const separatorIndex = decoded.indexOf(":");
  1812. if (separatorIndex < 0) return undefined;
  1813. return {
  1814. clientId: decoded.slice(0, separatorIndex),
  1815. clientSecret: decoded.slice(separatorIndex + 1),
  1816. };
  1817. }
  1818. function matchesRegisteredRedirectUri(requestedValue: string, registeredValue: string): boolean {
  1819. try {
  1820. const requested = new URL(requestedValue);
  1821. const registered = new URL(registeredValue);
  1822. const isLoopback =
  1823. requested.protocol === "http:" &&
  1824. registered.protocol === "http:" &&
  1825. requested.hostname === registered.hostname &&
  1826. (requested.hostname === "127.0.0.1" || requested.hostname === "[::1]");
  1827. if (!isLoopback) return requested.href === registered.href;
  1828. return (
  1829. requested.pathname === registered.pathname &&
  1830. requested.search === registered.search &&
  1831. requested.hash === registered.hash
  1832. );
  1833. } catch {
  1834. return false;
  1835. }
  1836. }
  1837. /** 统计当前活跃的 TCP server handle 数,用来断言连接期没有新开 callback listener。 */
  1838. function countTcpServers(): number {
  1839. return process.getActiveResourcesInfo().filter((resource) => resource === "TCPSERVERWRAP").length;
  1840. }
  1841. function sendJson(res: ServerResponse, statusCode: number, body: unknown): void {
  1842. res.writeHead(statusCode, {
  1843. "Content-Type": "application/json",
  1844. });
  1845. res.end(JSON.stringify(body));
  1846. }
  1847. async function readRequestBody(req: IncomingMessage): Promise<string> {
  1848. const chunks: Buffer[] = [];
  1849. for await (const chunk of req) {
  1850. chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
  1851. }
  1852. return Buffer.concat(chunks).toString("utf8");
  1853. }
  1854. async function listen(server: Server): Promise<Server> {
  1855. await new Promise<void>((resolve) => {
  1856. server.listen(0, "127.0.0.1", resolve);
  1857. });
  1858. servers.push(server);
  1859. return server;
  1860. }
  1861. async function closeServer(server: Server): Promise<void> {
  1862. if (!server.listening) return;
  1863. await new Promise<void>((resolve, reject) => {
  1864. server.close((error) => {
  1865. if (error) reject(error);
  1866. else resolve();
  1867. });
  1868. });
  1869. }
  1870. function serverBaseUrl(server: Server): string {
  1871. const address = server.address();
  1872. if (!address || typeof address === "string") {
  1873. throw new Error("Test server is not listening on a TCP port");
  1874. }
  1875. return `http://127.0.0.1:${address.port}`;
  1876. }